<?php

namespace App\Observers;

use App\Models\User;
use App\Models\Server;
use Illuminate\Support\Facades\Http;

class UserObserver
{
    public function updated(User $user)
    {
        if (
            $user->wallet_balance >= 5000 &&
            $user->getOriginal('wallet_balance') < 5000
        ) {
            $servers = Server::where('user_id', $user->id)
                ->where('status', 'suspended')
                ->get();

            foreach ($servers as $server) {
                $server->status = 'active';
                $server->suspended_at = null;
                $server->save();

                // فعال‌سازی واقعی سرور Vultr
                if ($server->provider === 'vultr' && $server->provider_id) {
                    try {
                        $apiKey = config('services.vultr.api_key');
                        $response = Http::withHeaders([
                            'Authorization' => 'Bearer ' . $apiKey,
                            'Content-Type'  => 'application/json',
                            'Accept'        => 'application/json',
                        ])->post("https://api.vultr.com/v2/instances/{$server->provider_id}/start");
                        // لاگ اختیاری
                    } catch (\Exception $e) {
                        \Log::error("Vultr auto-start error for server {$server->id}: ".$e->getMessage());
                    }
                }

                // فعال‌سازی واقعی سرور Hetzner
                if ($server->provider === 'hetzner' && $server->provider_id) {
                    try {
                        $apiKey = config('services.hetzner.api_token');
                        $response = Http::withHeaders([
                            'Authorization' => 'Bearer ' . $apiKey,
                            'Content-Type'  => 'application/json',
                            'Accept'        => 'application/json',
                        ])->post("https://api.hetzner.cloud/v1/servers/{$server->provider_id}/actions/poweron");
                        // لاگ اختیاری
                    } catch (\Exception $e) {
                        \Log::error("Hetzner auto-start error for server {$server->id}: ".$e->getMessage());
                    }
                }
            }
        }
    }
}
