<?php

namespace App\Http\Controllers;

use App\Models\Server;
use App\Services\LimitService;
use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use App\Models\BandwidthUsage;
use App\Models\ServerIp;
use App\Services\WalletService;
use GuzzleHttp\Client;
use App\Mail\ServerCreatedMail;
use Illuminate\Support\Facades\Mail;
use App\Mail\ServerDeletedMail;

class ServerController extends Controller
{
    private $parspackToken;
    private $parspackBase;
    private $vultrToken;
    private $hetznerToken;
    private $limitService;

    public function __construct(LimitService $limitService)
    {
        $this->limitService = $limitService;
        $this->parspackToken = config('services.parspack.token');
        $this->parspackBase = 'https://my.abrha.net/cserver/api/public/v1/vms/';
        $this->vultrToken = config('services.vultr.api_key');
        $this->hetznerToken = config('services.hetzner.api_token');
    }



    // ================= UPDATE ADD IPS FOR ALL PROVIDERS =================

public function serverIps(Server $server)
{
    if ($server->user_id !== auth()->id()) {
        abort(403, 'اجازه دسترسی ندارید.');
    }

    $ips = [];
    switch ($server->provider) {
        case 'hetzner':
            $ips = $this->getHetznerIps($server);
            break;
        case 'vultr':
            $ips = $this->getVultrIps($server);
            break;
        default:
            $ips = $server->ips;
            break;
    }

    return response()->json([
        'ips' => $ips,
        'provider' => $server->provider,
    ]);
}

// گرفتن آیپی‌ها برای Hetzner
public function getHetznerIps(Server $server)
{
    $token = config('services.hetzner.api_token');
    $response = Http::withHeaders([
        'Authorization' => 'Bearer ' . $token,
    ])->get("https://api.hetzner.cloud/v1/servers/{$server->provider_id}");

    if ($response->successful()) {
        $public_net = $response->json('server.public_net');
        return [
            [
                'ip' => $public_net['ipv4']['ip'] ?? '',
                'type' => 'ipv4',
                'rdns' => $public_net['ipv4']['dns_ptr'] ?? '',
                'is_primary' => true,
            ],
            [
                'ip' => $public_net['ipv6']['ip'] ?? '',
                'type' => 'ipv6',
                'rdns' => $public_net['ipv6']['dns_ptr'] ?? '',
                'is_primary' => true,
            ]
        ];
    }
    return [];
}


// گرفتن آیپی‌ها برای Vultr
public function getVultrIps(Server $server)
{
    $token = config('services.vultr.api_key');
    $id = $server->provider_id;

    $ips = [];
    $ipv4 = Http::withHeaders([
        'Authorization' => 'Bearer ' . $token,
    ])->get("https://api.vultr.com/v2/instances/{$id}/ipv4");
    if ($ipv4->successful()) {
        foreach($ipv4->json('ipv4') ?? [] as $item){
            $ips[] = [
                'ip' => $item['ip'] ?? '',
                'type' => 'ipv4',
                'rdns' => $item['rdns'] ?? '',
                'is_primary' => isset($item['is_main']) ? $item['is_main'] : false,
            ];
        }
    }
    $ipv6 = Http::withHeaders([
        'Authorization' => 'Bearer ' . $token,
    ])->get("https://api.vultr.com/v2/instances/{$id}/ipv6");
    if ($ipv6->successful()) {
        foreach($ipv6->json('ipv6') ?? [] as $item){
            $ips[] = [
                'ip' => $item['ip'] ?? '',
                'type' => 'ipv6',
                'rdns' => $item['rdns'] ?? '',
                'is_primary' => false,
            ];
        }
    }
    return $ips;
}

// افزودن IP جدید (نمونه Vultr)
public function addVultrIp(Server $server)
{
    $token = config('services.vultr.api_key');
    $id = $server->provider_id;

    $response = Http::withHeaders([
        'Authorization' => 'Bearer ' . $token,
    ])->post("https://api.vultr.com/v2/instances/{$id}/ipv4");

    if ($response->successful() && !empty($response->json('ipv4'))) {
        // دیتای IP جدید را می‌توانی در جدول server_ips ذخیره کنی
        return response()->json(['success' => true, 'data' => $response->json('ipv4')]);
    }
    return response()->json(['success' => false, 'error' => $response->body()]);
}

// افزودن IP برای Hetzner
public function addHetznerIp(Server $server)
{
    $token = config('services.hetzner.api_token');
    $response = Http::withHeaders([
        'Authorization' => 'Bearer ' . $token,
    ])->post("https://api.hetzner.cloud/v1/primary-ips", [
        'type' => 'ipv4',
        'server' => $server->provider_id,
    ]);
    return $response->json();
}

// حذف IP Vultr
public function deleteVultrIp(Server $server, $ip_id)
{
    $token = config('services.vultr.api_key');
    $id = $server->provider_id;
    $response = Http::withHeaders([
        'Authorization' => 'Bearer ' . $token,
    ])->delete("https://api.vultr.com/v2/instances/{$id}/ipv4/{$ip_id}");

    return response()->json(['success' => $response->successful()]);
}

// حذف IP Hetzner
public function deleteHetznerIp($ip_id)
{
    $token = config('services.hetzner.api_token');
    $response = Http::withHeaders([
        'Authorization' => 'Bearer ' . $token,
    ])->delete("https://api.hetzner.cloud/v1/primary-ips/{$ip_id}");

    return response()->json(['success' => $response->successful()]);
}

// حذف آی‌پی از جدول (در سیستم خودت)
public function deleteIpFromDb($ip_id)
{
    $ip = ServerIp::findOrFail($ip_id);
    $ip->delete();
    return response()->json(['success'=>true]);
}

// ذخیره آی‌پی جدید در دیتابیس (اگر بخواهی فقط local باشد)
public function saveIpToDb(Server $server, $ip, $type = 'ipv4')
{
    $ip = ServerIp::create([
        'server_id' => $server->id,
        'ip' => $ip,
        'type' => $type,
        'status' => 'active',
        'is_primary' => false
    ]);
    return $ip;
}



    // ================= UPDATE BANDWIDTH FOR ALL PROVIDERS =================

    public function updateServerBandwidth(Server $server)
    {
        $provider = strtolower($server->provider);

        if ($provider === 'hetzner') {
            return $this->updateHetznerBandwidth($server);
        } elseif ($provider === 'vultr') {
            return $this->updateVultrBandwidth($server);
        } elseif ($provider === 'arvancloud' || $provider === 'arvan') {
            return $this->updateArvanBandwidth($server);
        } else {
            // برای بقیه providerها هندل کن
            return false;
        }
    }

    // ================= HETZNER =================

    public function updateHetznerBandwidth(Server $server)
    {
        $hetzner_token = $this->hetznerToken;
        $hetzner_id = $server->provider_id;

        $response = Http::withToken($hetzner_token)
            ->get("https://api.hetzner.cloud/v1/servers/{$hetzner_id}");

        if ($response->failed()) {
            // Log::error('Hetzner bandwidth error: '.$response->body());
            return false;
        }

        $data = $response->json('server');
        $outgoing = $data['outgoing_traffic'] ?? 0;   // bytes
        $included = $data['included_traffic'] ?? 0;   // bytes

        $used_tb = round($outgoing / pow(1024, 4), 2);  // TB
        $limit_tb = round($included / pow(1024, 4), 2); // TB

        $period = now()->startOfMonth()->toDateString();

        BandwidthUsage::updateOrCreate(
            [
                'server_id' => $server->id,
                'period'    => $period,
            ],
            [
                'used_tb'  => $used_tb,
                'limit_tb' => $limit_tb > 0 ? $limit_tb : 30,
            ]
        );
        return true;
    }

    // ================= VULTR =================

public function updateVultrBandwidth(Server $server)
{
    $token = config('services.vultr.api_key');
    $id = $server->provider_id;

    $instanceResp = Http::withHeaders([
        'Authorization' => 'Bearer ' . $token,
        'Accept' => 'application/json',
    ])->get("https://api.vultr.com/v2/instances/{$id}");

    $allowed_bandwidth = null;
    $limit_tb = 0;
    if ($instanceResp->successful()) {
        $instance = $instanceResp->json('instance');
        $allowed_bandwidth = $instance['allowed_bandwidth'] ?? null;
        if ($allowed_bandwidth !== null && $allowed_bandwidth > 0) {

            $limit_tb = $allowed_bandwidth;
        } else {
            $limit_tb = 0;
        }
    }

    // گرفتن مصرف
    $response = Http::withHeaders([
        'Authorization' => 'Bearer ' . $token,
        'Accept' => 'application/json',
    ])->get("https://api.vultr.com/v2/instances/{$id}/bandwidth");

    $usedBytes = 0;
    if ($response->successful()) {
        $bandwidth = $response->json('bandwidth');
        foreach ($bandwidth as $day => $usage) {
            if (is_array($usage) && isset($usage['outgoing_bytes'])) {
                $usedBytes += $usage['outgoing_bytes'];
            }
        }
    }
    $used_tb = round($usedBytes / pow(1024, 4), 2);

    $period = now()->startOfMonth()->toDateString();

    \Log::info("VULTR DEBUG", [
      'server_id' => $server->id,
      'allowed_bandwidth' => $allowed_bandwidth,
      'limit_tb' => $limit_tb,
      'used_tb' => $used_tb
    ]);

    \App\Models\BandwidthUsage::updateOrCreate(
        [
            'server_id' => $server->id,
            'period'    => $period,
        ],
        [
            'used_tb'  => $used_tb,
            'limit_tb' => $limit_tb,
        ]
    );
}
    // ================= ARVAN CLOUD =================

    public function updateArvanBandwidth(Server $server)
    {
        $arvan_token = $this->arvanToken;
        $region = $server->arvan_region; // باید در جدول سرور ذخیره شده باشد
        $arvan_id = $server->provider_id;
        $from = now()->startOfMonth()->toDateString();
        $to = now()->toDateString();

        $response = Http::withHeaders([
            'Authorization' => 'Apikey ' . $arvan_token,
            'Accept'        => 'application/json',
        ])->get("https://napi.arvancloud.ir/ecc/v2/regions/{$region}/servers/{$arvan_id}/metrics", [
            'from' => $from,
            'to' => $to,
            'metric_type' => 'network',
        ]);

        if ($response->failed()) {
            // Log::error('Arvan bandwidth error: '.$response->body());
            return false;
        }

        $result = $response->json();
        // فرض: نتیجه خروجی مصرفی در $result['data']['out']
        $usedBytes = $result['data']['out'] ?? 0;
        $used_tb = round($usedBytes / pow(1024, 4), 2);
        $limit_tb = 10; // سقف، بر مبنای پلن

        $period = now()->startOfMonth()->toDateString();
        BandwidthUsage::updateOrCreate(
            [
                'server_id' => $server->id,
                'period'    => $period,
            ],
            [
                'used_tb'  => $used_tb,
                'limit_tb' => $limit_tb,
            ]
        );
        return true;
    }

    // =============== (Optional) متد دسته‌ای برای همه سرورها (cron job or manual) =============

    public function updateAllServersBandwidth()
    {
        $servers = Server::all();
        foreach ($servers as $server) {
            $this->updateServerBandwidth($server);
        }
        return response()->json(['message' => 'All servers bandwidth updated!']);
    }

public function create($projectId)
{
    $project = Project::findOrFail($projectId);
    if ($project->user_id !== auth()->id()) {
        abort(403, 'شما به این پروژه دسترسی ندارید.');
    }
    return view('servers.create', compact('project'));
}

public function store(Request $request, $projectId)
{
    $project = Project::findOrFail($projectId);

    $request->validate([
        'provider' => 'required|string|max:50',
        'name'     => 'nullable|string|max:255',
        'region'   => 'nullable|string|max:255',
    ]);

    $provider = $request->provider;
    $user = \App\Models\User::find(auth()->id());

    $min_balances = [
        'vultr'    => 50000,
        'arvan'    => 100000,
        'parspack' => 100000,
        'hetzner'  => 100000,
    ];
    $min_balance = $min_balances[$provider] ?? 0;

    if ($user->wallet_balance < $min_balance) {
        return response()->json([
            'status'  => 'error',
            'message' => 'برای ساخت این سرور باید حداقل ' . number_format($min_balance) . ' تومان موجودی کیف پول داشته باشید.'
        ], 422);
    }

    // ==================== VULTR ====================
    if ($provider === 'vultr') {
        $request->validate([
            'region' => 'required|string',
            'plan'   => 'required|string',
            'os_id'  => 'required|numeric',
        ]);

        $plan_id = $request->plan;
        $planApiResponse = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->vultrToken,
            'Accept'        => 'application/json',
        ])->get('https://api.vultr.com/v2/plans?type=vc2');
        
        $priceHourlyUSD = null;
        if ($planApiResponse->successful()) {
            $plans = $planApiResponse->json('plans') ?? [];
            foreach ($plans as $plan) {
                if (isset($plan['id']) && $plan['id'] == $plan_id) {
                    $priceHourlyUSD = $plan['hourly_cost'] ?? null;
                    break;
                }
            }
        }
        
        if (!$priceHourlyUSD) {
            return response()->json([
                'status' => 'error',
                'message' => 'خطا در دریافت قیمت ساعتی پلن ولتر!'
            ], 422);
        }
        
        $dollarRate = 120000;
        $priceHourlyToman = $priceHourlyUSD * $dollarRate;
        $finalHourlyPrice = ceil($priceHourlyToman * 1.20);

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->vultrToken,
            'Content-Type'  => 'application/json',
            'Accept'        => 'application/json',
        ])->post('https://api.vultr.com/v2/instances', [
            'region' => $request->region,
            'plan'   => $request->plan,
            'os_id'  => $request->os_id,
            'label'  => $request->name ?? ('vultr-' . uniqid()),
        ]);

        if ($response->successful()) {
            $instance = $response->json()['instance'];
            
            $serverData = [
                'user_id'      => auth()->id(),
                'project_id'   => $project->id,
                'name'         => $request->name ?? $instance['label'],
                'region'       => $request->region,
                'status'       => 'creating',
                'provider'     => 'vultr',
                'provider_id'  => $instance['id'],
                'plan'         => $request->plan,
                'image'        => $request->os_id,
                'ip_address'   => $instance['main_ip'] !== '0.0.0.0' ? $instance['main_ip'] : null,
                'password'     => $instance['default_password'] ?? null,
                'price_hourly_toman' => $finalHourlyPrice,
            ];
            
            Log::info('Vultr Server Data Before Create', $serverData);
            $server = Server::create($serverData);
            Log::info('Vultr Server After Create', $server->toArray());

            // ✅ ذخیره Primary IPv4 (رایگان - شامل قیمت سرور)
            if (!empty($instance['main_ip']) && $instance['main_ip'] !== '0.0.0.0') {
                \App\Models\ServerIp::create([
                    'server_id' => $server->id,
                    'user_id' => $server->user_id,
                    'ip' => $instance['main_ip'],
                    'type' => 'ipv4',
                    'is_primary' => 1,
                    'is_floating' => 0,
                    'assigned_at' => now(),
                    'status' => 'active',
                    'provider' => 'vultr',
                    'provider_ip_id' => null,
                    'location' => $request->region,
                    'datacenter' => null,
                    'hourly_cost' => 0, // رایگان
                    'netmask' => $instance['netmask_v4'] ?? null,
                    'gateway' => $instance['gateway_v4'] ?? null,
                    'rdns' => null,
                ]);
                Log::info('✅ Vultr Primary IPv4 saved', ['ip' => $instance['main_ip']]);
            }

            // ✅ ذخیره Primary IPv6 (رایگان - اگه داره)
            if (!empty($instance['v6_main_ip'])) {
                \App\Models\ServerIp::create([
                    'server_id' => $server->id,
                    'user_id' => $server->user_id,
                    'ip' => $instance['v6_main_ip'],
                    'type' => 'ipv6',
                    'is_primary' => 1,
                    'is_floating' => 0,
                    'assigned_at' => now(),
                    'status' => 'active',
                    'provider' => 'vultr',
                    'provider_ip_id' => null,
                    'location' => $request->region,
                    'datacenter' => null,
                    'hourly_cost' => 0, // رایگان
                    'netmask' => '/' . ($instance['v6_network_size'] ?? 64),
                    'gateway' => null,
                    'rdns' => null,
                ]);
                Log::info('✅ Vultr Primary IPv6 saved', ['ip' => $instance['v6_main_ip']]);
            }

            // ✅ ارسال ایمیل با 30 ثانیه تاخیر
            try {
                \Mail::to($user->email)->later(
                    now()->addSeconds(30),
                    new \App\Mail\ServerCreatedMail($user, $server, config('app.url') . '/cloud/')
                );
                Log::info('EMAIL_QUEUED', ['user_email' => $user->email, 'server_id' => $server->id]);
            } catch (\Exception $e) {
                Log::error('EMAIL_SEND_FAILED', ['error' => $e->getMessage(), 'server_id' => $server->id]);
            }

        } else {
            return response()->json([
                'status'  => 'error',
                'message' => ($response->json()['error'] ?? 'خطا در ساخت سرور ولتر!'),
            ], 500);
        }
    }
    
    // ==================== PARSPACK ====================
    elseif ($provider === 'parspack') {
        $request->validate([
            'region' => 'required|string',
            'size'   => 'required|string',
            'image'  => 'required|string',
            'name'   => 'nullable|string|max:255',
        ]);
        
        $client = new Client();
        $response = $client->post($this->parspackBase, [
            'headers' => [
                'Authorization'   => 'Bearer ' . $this->parspackToken,
                'Accept-Language' => 'fa',
                'Content-Type'    => 'application/json',
            ],
            'json' => [
                'region' => $request->region,
                'size'   => $request->size,
                'image'  => $request->image,
                'name'   => $request->name ?? ('parspack-' . uniqid()),
            ],
            'timeout' => 20,
        ]);
        
        $body = json_decode($response->getBody()->getContents(), true);
        
        if(isset($body['id'])) {
            $serverData = [
                'user_id'      => auth()->id(),
                'project_id'   => $project->id,
                'name'         => $request->name ?? $body['name'],
                'region'       => $request->region,
                'status'       => 'creating',
                'provider'     => 'parspack',
                'provider_id'  => $body['id'],
                'plan'         => $request->size,
                'image'        => $request->image,
                'ip_address'   => $body['ip'] ?? null,
                'password'     => $body['password'] ?? null,
            ];
            
            Log::info('Parspack Server Data Before Create', $serverData);
            $server = Server::create($serverData);
            Log::info('Parspack Server After Create', $server->toArray());

            // ✅ ذخیره Primary IP (اگه در response هست)
            if (!empty($body['ip'])) {
                \App\Models\ServerIp::create([
                    'server_id' => $server->id,
                    'user_id' => $server->user_id,
                    'ip' => $body['ip'],
                    'type' => 'ipv4',
                    'is_primary' => 1,
                    'is_floating' => 0,
                    'assigned_at' => now(),
                    'status' => 'active',
                    'provider' => 'parspack',
                    'provider_ip_id' => null,
                    'location' => $request->region,
                    'datacenter' => null,
                    'hourly_cost' => 0, // رایگان
                    'rdns' => null,
                ]);
                Log::info('✅ Parspack Primary IP saved', ['ip' => $body['ip']]);
            }

            // ✅ ارسال ایمیل
            try {
                \Mail::to($user->email)->later(
                    now()->addSeconds(30),
                    new \App\Mail\ServerCreatedMail($user, $server, config('app.url') . '/cloud/')
                );
                Log::info('EMAIL_QUEUED', ['user_email' => $user->email, 'server_id' => $server->id]);
            } catch (\Exception $e) {
                Log::error('EMAIL_SEND_FAILED', ['error' => $e->getMessage(), 'server_id' => $server->id]);
            }

        } else {
            return response()->json(['status'=>'error','message'=>'خطا در ساخت سرور پارس‌پک!'], 500);
        }
    }
    
    // ==================== ARVAN ====================
    elseif ($provider === 'arvan') {
        $request->validate([
            'region'    => 'required|string',
            'plan'      => 'required|string',
            'image'     => 'required|string',
            'disk_size' => 'required|numeric',
        ]);
        
        // TODO: منطق ساخت سرور آروان
        $serverData = [
            'user_id'      => auth()->id(),
            'project_id'   => $project->id,
            'name'         => $request->name,
            'region'       => $request->region,
            'status'       => 'creating',
            'provider'     => 'arvan',
            'provider_id'  => null,
            'plan'         => $request->plan,
            'image'        => $request->image,
            'ip_address'   => null,
            'password'     => null,
        ];
        
        Log::info('Arvan Server Data Before Create', $serverData);
        $server = Server::create($serverData);
        Log::info('Arvan Server After Create', $server->toArray());

        // ✅ ارسال ایمیل
        try {
            \Mail::to($user->email)->later(
                now()->addSeconds(30),
                new \App\Mail\ServerCreatedMail($user, $server, config('app.url') . '/cloud/')
            );
            Log::info('EMAIL_QUEUED', ['user_email' => $user->email, 'server_id' => $server->id]);
        } catch (\Exception $e) {
            Log::error('EMAIL_SEND_FAILED', ['error' => $e->getMessage(), 'server_id' => $server->id]);
        }
    }
    
    // ==================== HETZNER ====================
    elseif ($provider === 'hetzner') {
        $request->validate([
            'region' => 'required|string',
            'plan'   => 'required|string',
            'image'  => 'required|string',
        ]);
        
        $planApi = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->hetznerToken,
            'Accept'        => 'application/json',
        ])->get('https://api.hetzner.cloud/v1/server_types');

        $hourlyEuro = null;
        if ($planApi->successful()) {
            $plans = $planApi->json('server_types') ?? [];
            foreach ($plans as $plan) {
                if ($plan['name'] == $request->plan) {
                    if (isset($plan['prices']) && is_array($plan['prices'])) {
                        foreach ($plan['prices'] as $price) {
                            if (isset($price['location']) && $price['location'] == $request->region) {
                                $hourlyEuro = $price['price_hourly']['net'] ?? null;
                                break 2;
                            }
                        }
                    }
                }
            }
        }
        
        if (!$hourlyEuro) {
            return response()->json([
                'status' => 'error',
                'message' => 'خطا در دریافت قیمت ساعتی پلن هتزنر!'
            ], 422);
        }
        
        $euroRate = 135000;
        $priceHourlyToman = $hourlyEuro * $euroRate;
        $totalHourlyPrice = ceil($priceHourlyToman * 1.25);
        
        // ✅ تقسیم قیمت: سرور + IPv4 + IPv6
        $ipv4Cost = 250;
        $ipv6Cost = 120;
        $serverOnlyCost = $totalHourlyPrice - $ipv4Cost - $ipv6Cost;

        $payload = [
            'name'         => $request->name ?? ('hetzner-' . uniqid()),
            'server_type'  => $request->plan,
            'location'     => $request->region,
            'image'        => $request->image,
            'start_after_create' => true,
        ];

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->hetznerToken,
            'Content-Type'  => 'application/json',
            'Accept'        => 'application/json',
        ])->post('https://api.hetzner.cloud/v1/servers', $payload);

        if ($response->successful()) {
            $hetzServer = $response->json()['server'] ?? [];
            
            // ✅ ذخیره سرور با قیمت بدون IP
            $serverData = [
                'user_id'      => auth()->id(),
                'project_id'   => $project->id,
                'name'         => $payload['name'],
                'region'       => $request->region,
                'status'       => 'creating',
                'provider'     => 'hetzner',
                'provider_id'  => $hetzServer['id'] ?? null,
                'plan'         => $request->plan,
                'image'        => $request->image,
                'ip_address'   => $hetzServer['public_net']['ipv4']['ip'] ?? null,
                'password'     => $hetzServer['root_password'] ?? null,
                'price_hourly_toman' => $serverOnlyCost, // بدون IP
            ];
            
            Log::info('Hetzner Server Data Before Create', $serverData);
            $server = Server::create($serverData);
            Log::info('Hetzner Server After Create', $server->toArray());

            // ✅ ذخیره Primary IPv4 (250 تومان/ساعت)
            if (isset($hetzServer['public_net']['ipv4']['ip'])) {
                \App\Models\ServerIp::create([
                    'server_id' => $server->id,
                    'user_id' => $server->user_id,
                    'ip' => $hetzServer['public_net']['ipv4']['ip'],
                    'type' => 'ipv4',
                    'is_primary' => 1,
                    'is_floating' => 0,
                    'assigned_at' => now(),
                    'status' => 'active',
                    'provider' => 'hetzner',
                    'provider_ip_id' => $hetzServer['public_net']['ipv4']['id'] ?? null,
                    'location' => $hetzServer['datacenter']['location']['name'] ?? $request->region,
                    'datacenter' => $hetzServer['datacenter']['name'] ?? null,
                    'hourly_cost' => $ipv4Cost, // 250 تومان
                    'rdns' => $hetzServer['public_net']['ipv4']['dns_ptr'][0]['dns_ptr'] ?? null,
                ]);
                Log::info('✅ Hetzner Primary IPv4 saved', [
                    'ip' => $hetzServer['public_net']['ipv4']['ip'],
                    'hourly_cost' => $ipv4Cost
                ]);
            }

            // ✅ ذخیره Primary IPv6 (120 تومان/ساعت)
            if (isset($hetzServer['public_net']['ipv6']['ip'])) {
                \App\Models\ServerIp::create([
                    'server_id' => $server->id,
                    'user_id' => $server->user_id,
                    'ip' => $hetzServer['public_net']['ipv6']['ip'],
                    'type' => 'ipv6',
                    'is_primary' => 1,
                    'is_floating' => 0,
                    'assigned_at' => now(),
                    'status' => 'active',
                    'provider' => 'hetzner',
                    'provider_ip_id' => $hetzServer['public_net']['ipv6']['id'] ?? null,
                    'location' => $hetzServer['datacenter']['location']['name'] ?? $request->region,
                    'datacenter' => $hetzServer['datacenter']['name'] ?? null,
                    'hourly_cost' => $ipv6Cost, // 120 تومان
                    'rdns' => $hetzServer['public_net']['ipv6']['dns_ptr'][0]['dns_ptr'] ?? null,
                ]);
                Log::info('✅ Hetzner Primary IPv6 saved', [
                    'ip' => $hetzServer['public_net']['ipv6']['ip'],
                    'hourly_cost' => $ipv6Cost
                ]);
            }

            // ✅ ارسال ایمیل
            try {
                \Mail::to($user->email)->later(
                    now()->addSeconds(30),
                    new \App\Mail\ServerCreatedMail($user, $server, config('app.url') . '/cloud/')
                );
                Log::info('EMAIL_QUEUED', ['user_email' => $user->email, 'server_id' => $server->id]);
            } catch (\Exception $e) {
                Log::error('EMAIL_SEND_FAILED', ['error' => $e->getMessage(), 'server_id' => $server->id]);
            }

        } else {
            $error = $response->json();
            Log::error('Hetzner server create error', ['error' => $error, 'payload' => $payload]);
            return response()->json([
                'status'  => 'error',
                'message' => ($error['error']['message'] ?? $error['message'] ?? 'خطا در ساخت سرور هتزنر!'),
            ], 500);
        }
    }
    
    else {
        return response()->json(['status'=>'error','message'=>'provider نامعتبر!'], 400);
    }

    return response()->json([
        'status'    => 'success',
        'message'   => 'سرور با موفقیت ساخته شد و در حال ساخت است',
        'server_id' => $server->id ?? null,
    ]);
}

public function globalStatus()
{
    $user = auth()->user();
    $active = \App\Models\Server::where('user_id', $user->id)
        ->whereIn('status', ['active','running','on'])
        ->count();

    $pending = \App\Models\Server::where('user_id', $user->id)
        ->whereIn('status', ['creating','pending','starting','initializing','installing'])
        ->count();

    $off = \App\Models\Server::where('user_id', $user->id)
        ->whereIn('status', ['off','stopped'])
        ->count();

    // اگر خواستی لیست کامل هم برگردانی (اختیاری)
    // $servers = \App\Models\Server::where('user_id', $user->id)->get();

    return response()->json([
        'stats' => [
            'active'  => $active,
            'pending' => $pending,
            'off'     => $off,
        ],
        // 'servers' => $servers, // اگر خواستی لیست کامل هم برگردانی
    ]);
}

    /**
     * حذف سرور
     */
    public function destroy(Server $server)
    {
        $user = $server->user;
        
        Log::info('DESTROY_CALLED', ['server_id' => $server->id, 'provider' => $server->provider]);

        try {
            // ✅ بررسی محدودیت حذف (فقط برای سرورها)
            if (!$this->limitService->canDelete($user->id)) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'شما از تعداد حذف‌های ماهانه فراتر رفته‌اید. محدودیت: ' . $this->limitService->getLimits()['deletions'] . ' حذف در ماه'
                ], 403);
            }

            if ($server->provider === 'vultr') {
                return $this->destroyVultr($server, $user);
            } elseif ($server->provider === 'arvan') {
                return $this->destroyArvan($server, $user);
            } elseif ($server->provider === 'hetzner') {
                return $this->destroyHetzner($server, $user);
            } else {
                return $this->destroyOther($server, $user);
            }

        } catch (\Exception $e) {
            Log::error("Delete server error: " . $e->getMessage());
            return response()->json(['status' => 'error', 'message' => 'خطا در حذف سرور'], 500);
        }
    }

    /**
     * حذف سرور ولتر
     */
    private function destroyVultr($server, $user)
    {
        Log::info('DESTROY_VULTR_BRANCH', ['server_id' => $server->id, 'provider' => $server->provider_id]);

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->vultrToken,
            'Accept'        => 'application/json',
        ])->delete("https://api.vultr.com/v2/instances/{$server->provider_id}");

        Log::info('VULTR_DELETE_RESPONSE', [
            'status' => $response->status(),
            'body' => $response->body(),
        ]);

        if ($response->successful()) {
            Log::info('VULTR_DELETE_SUCCESS', [
                'server_id' => $server->id,
                'user_email' => $user->email ?? null
            ]);

            // ارسال ایمیل حذف سرور
            if ($user && $user->email) {
                try {
                    Mail::to($user->email)->send(new ServerDeletedMail($user, $server));
                    Log::info('EMAIL_SENT: ServerDeletedMail', [
                        'user_email' => $user->email,
                        'server_id' => $server->id
                    ]);
                } catch (\Exception $e) {
                    Log::error('EMAIL_ERROR: ServerDeletedMail', [
                        'user_email' => $user->email ?? null,
                        'server_id' => $server->id,
                        'error_message' => $e->getMessage()
                    ]);
                }
            }

            // حذف سرور از دیتابیس
            $server->delete();

            // ✅ ثبت حذف در deletion_logs
            $this->limitService->logDeletion($user->id, $server->id);

            return response()->json([
                'status' => 'success',
                'message' => 'سرور ولتر حذف شد',
                'refresh' => true
            ]);
        }

        return response()->json([
            'status' => 'error',
            'message' => 'خطا در حذف ولتر',
            'refresh' => false
        ]);
    }

    /**
     * حذف سرور آروان
     */
    private function destroyArvan($server, $user)
    {
        Log::info('DESTROY_ARVAN_BRANCH', [
            'server_id' => $server->id,
            'provider_id' => $server->provider_id,
            'region' => $server->region
        ]);

        // بررسی محدودیت زمانی (30 دقیقه)
        $createdAt = $server->created_at ?? null;
        if ($createdAt) {
            $minutesPassed = \Carbon\Carbon::parse($createdAt)->diffInMinutes(now());
            if ($minutesPassed < 30) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'امکان حذف این نوع سرور تا ۳۰ دقیقه پس از ساخت سرور وجود ندارد. لطفاً پس از ' . (30 - $minutesPassed) . ' دقیقه دیگر اقدام کنید.'
                ]);
            }
        }

        $arvanToken = config('services.arvan.token');
        $response = Http::withHeaders([
            'Authorization' => 'Apikey ' . $arvanToken,
            'Accept'        => 'application/json',
        ])->delete("https://napi.arvancloud.ir/ecc/v1/regions/{$server->region}/servers/{$server->provider_id}");

        Log::info('ARVAN_DELETE_RESPONSE', [
            'status' => $response->status(),
            'body' => $response->body(),
        ]);

        if ($response->successful()) {
            // ارسال ایمیل حذف سرور
            if ($user && $user->email) {
                try {
                    Mail::to($user->email)->send(new ServerDeletedMail($user, $server));
                } catch (\Exception $e) {
                    Log::error('EMAIL_ERROR: ServerDeletedMail', ['error' => $e->getMessage()]);
                }
            }

            // حذف سرور از دیتابیس
            $server->delete();

            // ✅ ثبت حذف در deletion_logs
            $this->limitService->logDeletion($user->id, $server->id);

            return response()->json([
                'status' => 'success',
                'message' => 'سرور حذف شد',
                'refresh' => true
            ]);
        } elseif ($response->status() == 403 || $response->status() == 400) {
            return response()->json([
                'status' => 'error',
                'message' => 'امکان حذف سرور وجود ندارد. لطفاً بعد از گذشت ۳۰ دقیقه اقدام کنید.'
            ]);
        }

        return response()->json([
            'status' => 'error',
            'message' => 'خطا در حذف سرور'
        ]);
    }

    /**
     * حذف سرور هتزنر
     */
    private function destroyHetzner($server, $user)
    {
        Log::info('DESTROY_HETZNER_BRANCH', ['server_id' => $server->id, 'provider_id' => $server->provider_id]);

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->hetznerToken,
            'Accept'        => 'application/json',
        ])->delete("https://api.hetzner.cloud/v1/servers/{$server->provider_id}");

        Log::info('HETZNER_DELETE_RESPONSE', [
            'status' => $response->status(),
            'body' => $response->body(),
        ]);

        if ($response->successful()) {
            // ارسال ایمیل حذف سرور
            if ($user && $user->email) {
                try {
                    Mail::to($user->email)->send(new ServerDeletedMail($user, $server));
                    Log::info('EMAIL_SENT: ServerDeletedMail', [
                        'user_email' => $user->email,
                        'server_id' => $server->id
                    ]);
                } catch (\Exception $e) {
                    Log::error('EMAIL_ERROR: ServerDeletedMail', [
                        'user_email' => $user->email ?? null,
                        'server_id' => $server->id,
                        'error_message' => $e->getMessage()
                    ]);
                }
            }

            // حذف سرور از دیتابیس
            $server->delete();

            // ✅ ثبت حذف در deletion_logs
            $this->limitService->logDeletion($user->id, $server->id);

            return response()->json([
                'status' => 'success',
                'message' => 'سرور هتزنر حذف شد',
                'refresh' => true
            ]);
        }

        return response()->json([
            'status' => 'error',
            'message' => 'خطا در حذف هتزنر'
        ]);
    }

    /**
     * حذف سرور سایر providerها
     */
    private function destroyOther($server, $user)
    {
        Log::info('DESTROY_OTHER_BRANCH', ['server_id' => $server->id, 'provider' => $server->provider]);

        // ارسال ایمیل حذف سرور
        if ($user && $user->email) {
            try {
                Mail::to($user->email)->send(new ServerDeletedMail($user, $server));
                Log::info('EMAIL_SENT: ServerDeletedMail', [
                    'user_email' => $user->email,
                    'server_id' => $server->id
                ]);
            } catch (\Exception $e) {
                Log::error('EMAIL_ERROR: ServerDeletedMail', [
                    'user_email' => $user->email ?? null,
                    'server_id' => $server->id,
                    'error_message' => $e->getMessage()
                ]);
            }
        }

        // حذف سرور از دیتابیس
        $server->delete();

        // ✅ ثبت حذف در deletion_logs
        $this->limitService->logDeletion($user->id, $server->id);

        return response()->json([
            'status' => 'success',
            'message' => 'سرور حذف شد',
            'refresh' => true
        ]);
    
}

 public function reboot(Server $server)
{
    try {
        if ($server->provider === 'vultr') {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->vultrToken,
                'Content-Type'  => 'application/json',
                'Accept'        => 'application/json',
            ])->post("https://api.vultr.com/v2/instances/{$server->provider_id}/reboot");
            return response()->json([
                'status' => $response->successful() ? 'success' : 'error',
                'message' => $response->successful() ? 'ریستارت ولتر موفق بود' : 'خطا در ریستارت ولتر',
            ]);
        } elseif ($server->provider === 'parspack') {
            $this->callParspackAction($server->provider_id, 'reboot');
            return response()->json(['status'=>'success','message'=>'ریستارت پارس‌پک موفق بود']);
        } elseif ($server->provider === 'hetzner') {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->hetznerToken,
                'Accept'        => 'application/json',
            ])->post("https://api.hetzner.cloud/v1/servers/{$server->provider_id}/actions/reboot");
            return response()->json([
                'status' => $response->successful() ? 'success' : 'error',
                'message' => $response->successful() ? 'ریستارت هتزنر موفق بود' : 'خطا در ریستارت هتزنر',
            ]);
        } elseif ($server->provider === 'arvan') {
            // ------ افزوده شده ویژه Arvan ------
            $arvanToken = config('services.arvan.token');
            $region     = $server->region;         // مثل "ir-thr-ba1"
            $providerId = $server->provider_id;    // uuid سرور آروان

            $response = Http::withHeaders([
                'Authorization' => 'Apikey ' . $arvanToken,
                'Accept'        => 'application/json',
            ])->post("https://napi.arvancloud.ir/ecc/v1/regions/{$region}/servers/{$providerId}/reboot");

            return response()->json([
                'status' => $response->successful() ? 'success' : 'error',
                'message' => $response->successful() ? 'ریستارت سرور موفق بود' : 'خطا در ریستارت سرور',
            ]);
        } else {
            return response()->json(['status'=>'error','message'=>'ریبوت برای این provider پیاده‌سازی نشده است.']);
        }
    } catch (\Exception $e) {
        Log::error("Reboot server error: ".$e->getMessage());
        return response()->json(['status'=>'error','message'=>'خطا در ریبوت سرور', 'details' => $e->getMessage()], 500);
    }
}

    public function power(Request $request, Server $server)
    {
        $state = $request->input('state');
        try {
            $user = $server->user;
            if ($state == 1 && ($server->status === 'suspended' || ($user && $user->wallet_balance < 5000))) {
                return response()->json([
                    'status' => 'error',
                    'message' => 'امکان روشن کردن این سرور وجود ندارد (مسدود یا اعتبار ناکافی).'
                ], 403);
            }

            if ($server->provider === 'vultr') {
                $action = $state ? 'start' : 'halt';
                $response = Http::withHeaders([
                    'Authorization' => 'Bearer ' . $this->vultrToken,
                    'Content-Type'  => 'application/json',
                    'Accept'        => 'application/json',
                ])->post("https://api.vultr.com/v2/instances/{$server->provider_id}/{$action}");

                if ($response->successful()) {
                    $statusResp = Http::withHeaders([
                        'Authorization' => 'Bearer ' . $this->vultrToken,
                        'Accept'        => 'application/json',
                    ])->get("https://api.vultr.com/v2/instances/{$server->provider_id}");

                    if ($statusResp->successful()) {
                        $instance = $statusResp->json()['instance'] ?? [];
                        if (!empty($instance['status'])) {
                            $server->status = $instance['status'];
                            $server->save();
                        }
                    }
                }
                return response()->json([
                    'status' => $response->successful() ? 'success' : 'error',
                    'message' => $response->successful() ? "وضعیت سرور ولتر تغییر کرد" : 'خطا در تغییر وضعیت سرور',
                    'current_status' => $state ? 'active' : 'off'
                ]);
                
            } elseif ($server->provider === 'hetzner') {
                $endpoint = $state ? 'poweron' : 'poweroff';
                $response = Http::withHeaders([
                    'Authorization' => 'Bearer ' . $this->hetznerToken,
                    'Accept'        => 'application/json',
                ])->post("https://api.hetzner.cloud/v1/servers/{$server->provider_id}/actions/{$endpoint}");

                if ($response->successful()) {
                    $statusResp = Http::withHeaders([
                        'Authorization' => 'Bearer ' . $this->hetznerToken,
                        'Accept'        => 'application/json',
                    ])->get("https://api.hetzner.cloud/v1/servers/{$server->provider_id}");

                    if ($statusResp->successful()) {
                        $apiServer = $statusResp->json()['server'] ?? [];
                        if (!empty($apiServer['status'])) {
                            $server->status = $apiServer['status'];
                            $server->save();
                        }
                    }
                }
                return response()->json([
                    'status' => $response->successful() ? 'success' : 'error',
                    'message' => $response->successful() ? "وضعیت سرور هتزنر تغییر کرد" : 'خطا در تغییر وضعیت سرور',
                    'current_status' => $state ? 'active' : 'off'
                ]);
            } elseif ($server->provider === 'arvan') {
            $arvanToken = config('services.arvan.token');
            $region     = $server->region;
            $providerId = $server->provider_id;
            $endpoint   = $state ? 'power-on' : 'power-off';

            $response = Http::withHeaders([
                'Authorization' => 'Apikey ' . $arvanToken,
                'Accept'        => 'application/json',
            ])->post("https://napi.arvancloud.ir/ecc/v1/regions/{$region}/servers/{$providerId}/{$endpoint}");

            if ($response->successful()) {
                $server->status = $state ? 'active' : 'off';
                $server->save();
            }

            return response()->json([
                'status' => $response->successful() ? 'success' : 'error',
                'message' => $response->successful() ? "وضعیت سرور تغییر کرد" : 'خطا در تغییر وضعیت سرور',
                'current_status' => $state ? 'active' : 'off'
            ]);

        } else {
            return response()->json(['status'=>'error','message'=>'پاور برای این provider پیاده‌سازی نشده است.']);
        }
    } catch (\Exception $e) {
        Log::error("Power server error: ".$e->getMessage());
        return response()->json(['status'=>'error','message'=>'خطا در تغییر وضعیت سرور'], 500);
    }
}

public function status(Server $server)
{
    try {
        // Vultr
        if ($server->provider === 'vultr') {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->vultrToken,
                'Accept'        => 'application/json',
            ])->get("https://api.vultr.com/v2/instances/{$server->provider_id}");
            if ($response->successful()) {
                $instance = $response->json()['instance'] ?? [];
                if (!empty($instance['main_ip']) && $instance['main_ip'] !== '0.0.0.0') {
                    $server->ip_address = $instance['main_ip'];
                }
                if (!empty($instance['status']) && $server->status !== 'suspended') {
                    $server->status = $instance['status'];
                }
                $server->save();
                return response()->json([
                    'status'      => $instance['status'] ?? 'unknown',
                    'ip_address'  => $instance['main_ip'] ?? '-',
                    'plan'        => $instance['plan'] ?? '-',
                    'image'       => $instance['os'] ?? '-',
                    'region'      => $instance['region'] ?? '-'
                ]);
            }

        // Hetzner
        } elseif ($server->provider === 'hetzner') {
    $response = Http::withHeaders([
        'Authorization' => 'Bearer ' . $this->hetznerToken,
        'Accept'        => 'application/json',
    ])->get("https://api.hetzner.cloud/v1/servers/{$server->provider_id}");
    if ($response->successful()) {
        $apiServer = $response->json()['server'] ?? [];
        if (isset($apiServer['public_net']['ipv4']['ip']) && $apiServer['public_net']['ipv4']['ip']) {
            $server->ip_address = $apiServer['public_net']['ipv4']['ip'];
        }
        if (isset($apiServer['status']) && $apiServer['status'] && $server->status !== 'suspended') {
            $server->status = $apiServer['status'];
        }
        $server->save();
        // نکته کلیدی: هم ایمیج، هم توضیح (name) سیستم عامل برگردان
        return response()->json([
            'status'      => $server->status ?? 'unknown',
            'ip_address'  => $server->ip_address ?? '-',
            'plan'        => $apiServer['server_type']['name'] ?? '-',
            'image'       => $apiServer['image']['id'] ?? '-',
            'image_name'  => $apiServer['image']['description'] ?? $apiServer['image']['name'] ?? $server->image_name ?? null,
            'region'      => $apiServer['datacenter']['location']['name'] ?? '-'
        ]);
    }

        } elseif ($server->provider === 'arvan') {
            $arvanToken = config('services.arvan.token');
            $region = $server->region;
            $providerId = $server->provider_id;
            $response = \Illuminate\Support\Facades\Http::withHeaders([
                'Authorization' => 'Apikey ' . $arvanToken,
                'Accept'        => 'application/json',
            ])->get("https://napi.arvancloud.ir/ecc/v1/regions/{$region}/servers/{$providerId}");

            if ($response->successful()) {
                $data = $response->json()['data'] ?? [];
                // ip_address
                $ip = $data['security_groups'][0]['ip_addresses'][0] ?? '-';

                // flavor = مشخصات سرور
                $flavor = $data['flavor'] ?? [];
                $ram    = $flavor['ram'] ?? null;
                $vcpu   = $flavor['vcpus'] ?? null;
                $disk   = $flavor['disk'] ?? null;

                // سیستم عامل
                $imageName = $data['image']['name'] ?? '-';

                // وضعیت اصلی
                $status = $data['status'] ?? 'unknown';

                // ذخیره وضعیت و آی‌پی در دیتابیس سرور
                if ($server->status !== 'suspended') $server->status = $status;
                if ($ip && $ip !== '-') $server->ip_address = $ip;
                $server->save();

                return response()->json([
                    'status'      => $status,
                    'ip_address'  => $ip,
                    'plan'        => $flavor['name'] ?? '-',
                    'ram'         => $ram,
                    'vcpu'        => $vcpu,
                    'disk'        => $disk,
                    'image'       => $data['image']['id'] ?? '-',
                    'image_name'  => $imageName,
                    'region'      => $data['region'] ?? $server->region ?? '-'
                ]);
            } else {
                return response()->json(['status' => 'unknown']);
            }
        }
    } catch (\Exception $e){
        Log::error("Status fetch error: ".$e->getMessage());
        return response()->json(['status' => 'unknown']);
    }
}

public function refreshServers($projectId)
{
    try {
        $project = Project::findOrFail($projectId);
        $servers = $project->servers()->get()->map(function($server){
            try {
                // Vultr
                if ($server->provider === 'vultr') {
                    $response = \Illuminate\Support\Facades\Http::withHeaders([
                        'Authorization' => 'Bearer ' . $this->vultrToken,
                        'Accept'        => 'application/json',
                    ])->get("https://api.vultr.com/v2/instances/{$server->provider_id}");
                    if ($response->successful()) {
                        $instance = $response->json()['instance'] ?? [];
                        if (!empty($instance['main_ip']) && $instance['main_ip'] !== '0.0.0.0') {
                            $server->ip_address = $instance['main_ip'];
                        }
                        if (!empty($instance['status']) && $server->status !== 'suspended') {
                            $server->status = $instance['status'];
                        }
                        $server->save();
                    }
                }

                // ParsPack
                elseif ($server->provider === 'parspack') {
                    $statusData = $this->callParspackAction($server->provider_id, 'status');
                    if ($server->status !== 'suspended') {
                        $server->status = $statusData['status'] ?? $server->status;
                    }
                    $server->save();
                }

                // Hetzner
                elseif ($server->provider === 'hetzner') {
                    $response = \Illuminate\Support\Facades\Http::withHeaders([
                        'Authorization' => 'Bearer ' . $this->hetznerToken,
                        'Accept'        => 'application/json',
                    ])->get("https://api.hetzner.cloud/v1/servers/{$server->provider_id}");
                    if ($response->successful()) {
                        $apiServer = $response->json()['server'] ?? [];
                        $validStatuses = [
                            'running','active','starting','initializing','off','stopped','creating','pending','installing','on','suspended'
                        ];
                        if (
                            isset($apiServer['status']) &&
                            in_array($apiServer['status'], $validStatuses, true) &&
                            $server->status !== 'suspended'
                        ) {
                            $server->status = $apiServer['status'];
                        }
                        if (isset($apiServer['public_net']['ipv4']['ip']) && $apiServer['public_net']['ipv4']['ip']) {
                            $server->ip_address = $apiServer['public_net']['ipv4']['ip'];
                        }
                        $server->save();
                    }
                }

                // ArvanCloud
                elseif ($server->provider === 'arvan') {
                    // جایگزین توکن ابرآروان خودت یا ستاپ از env/config
                    $arvanToken = env('ARVAN_API_TOKEN');
                    $response = \Illuminate\Support\Facades\Http::withHeaders([
                        'Authorization' => 'Apikey ' . $arvanToken,
                        'Accept'        => 'application/json',
                    ])->get("https://napi.arvancloud.ir/ecc/v1/regions/{$server->region}/servers/{$server->provider_id}");
                    if ($response->successful()) {
                        $data = $response->json('data') ?? [];
                        if (!empty($data['status']) && $server->status !== 'suspended') {
                           $server->status = strtolower($data['status']);
                        }
$ip = null;
if (!empty($data['addresses']) && is_array($data['addresses'])) {
    foreach ($data['addresses'] as $addressList) {
        foreach ($addressList as $addrObj) {
            if (!empty($addrObj['addr']) && !empty($addrObj['is_public']) && $addrObj['is_public']) {
                $ip = $addrObj['addr'];
                break 2; // Found, break both loops
            }
        }
    }
}
if ($ip) {
    $server->ip_address = $ip;
    }

    $server->save();
}
                }

                // میتونی سایر providerها را هم همینجا اضافه کنی

            } catch (\Exception $e){
                \Log::error("Fetch server status error: ".$e->getMessage());
            }
            return [
                'id' => $server->id,
                'name' => $server->name ?? '-',
                'ip_address' => $server->ip_address ?? '-',
                'region' => $server->region ?? '-',
                'status' => $server->status ?? 'unknown',
                'progress' => $server->progress ?? 0,
            ];
        });
        return response()->json(['servers' => $servers]);
    } catch (\Exception $e) {
        \Log::error("Refresh servers error: ".$e->getMessage());
        return response()->json(['error' => 'خطا در دریافت اطلاعات سرورها'], 500);
    }
}









 /**
 * نمایش صفحه اصلی Overview
 */
public function overview(Server $server)
{
    $this->authorize('view', $server);
    $serverData = $this->getServerBaseData($server);
    
    // 💰 محاسبه هزینه کلی سرور
    $walletService = app(\App\Services\WalletService::class);
    
    // هزینه کل از ابتدای ساخت
    $totalCostStats = $walletService->getServerCostStats(
        $server->id, 
        $server->created_at->format('Y-m-d'),
        now()->format('Y-m-d')
    );
    
    // هزینه این ماه
    $monthCostStats = $walletService->getServerCostStats(
        $server->id,
        now()->startOfMonth()->format('Y-m-d'),
        now()->format('Y-m-d')
    );
    
    // اضافه کردن هزینه‌ها به serverData
    $serverData['costTillNow'] = $totalCostStats['total_cost'];
    $serverData['costThisMonth'] = $monthCostStats['total_cost'];
    $serverData['costBreakdown'] = [
        'server' => $totalCostStats['server_costs'],
        'ip' => $totalCostStats['ip_costs'],
    ];
    
    return view('servers.overview', $serverData);
}

/**
 * دریافت دیتای پایه سرور (برای همه تب‌ها مشترک)
 */
private function getServerBaseData(Server $server)
{
    $provider = $server->provider ?? 'parspack';
    $apiData = null;
    
    // مشخصات سرور
    [$cpu, $ram, $disk, $osName, $osList, $plans] = $this->getServerSpecs($server, $provider);
    
    // سینک IP ها
    $this->syncServerIps($server, $provider);
    
    // لیست IP ها
    $mainIps = $this->getMainIps($server);
    $additionalIps = $this->getAdditionalIps($server);
    
    // پهنای باند
    [$used_tb, $limit_tb, $percent] = $this->getBandwidthData($server);
    
    return compact(
        'server', 'apiData', 'osList', 'plans', 'provider',
        'mainIps', 'additionalIps', 'cpu', 'ram', 'disk', 'osName',
        'used_tb', 'limit_tb', 'percent'
    );
}

/**
 * دریافت مشخصات سخت‌افزاری سرور
 */
private function getServerSpecs(Server $server, string $provider)
{
    $cpu = $disk = $ram = $osName = "-";
    $osList = [];
    $plans = [];
    
    if ($provider === 'hetzner') {
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $this->hetznerToken,
            'Accept' => 'application/json',
        ])->get("https://api.hetzner.cloud/v1/servers/{$server->provider_id}");
        
        if ($response->successful()) {
            $hetzServer = $response->json()['server'] ?? [];
            
            // OS List
            $osResp = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->hetznerToken,
            ])->get('https://api.hetzner.cloud/v1/images?type=system');
            
            if ($osResp->successful()) {
                $osList = $osResp->json()['images'] ?? [];
            }
            
            // Plans
            $plansResp = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->hetznerToken,
            ])->get('https://api.hetzner.cloud/v1/server_types');
            
            if ($plansResp->successful()) {
                $plans = $plansResp->json()['server_types'] ?? [];
            }
            
            // Get plan info
            $planInfo = collect($plans)->firstWhere('id', $server->plan);
            
            $cpu = $planInfo['cores'] ?? "-";
            $ram = $planInfo['memory'] ?? "-";
            $disk = $planInfo['disk'] ?? "-";
            $osName = $hetzServer['image']['description'] ?? $server->image ?? "-";
        }
    } elseif ($provider === 'vultr') {
        // Vultr logic here
        $cpu = $server->vcpu ?? "-";
        $ram = $server->ram ?? "-";
        $disk = $server->disk ?? "-";
        $osName = $server->image_name ?? "-";
    } else {
        $cpu = $server->vcpu ?? "-";
        $ram = $server->ram ?? "-";
        $disk = $server->disk ?? "-";
        $osName = $server->image_name ?? $server->image ?? "-";
    }
    
    return [$cpu, $ram, $disk, $osName, $osList, $plans];
}

    /**
     * سینک کردن IP های سرور با provider
     */
    private function syncServerIps(Server $server, string $provider)
    {
        $providerMainIps = $this->fetchProviderIps($server, $provider);

        foreach ($providerMainIps as $provIp) {
            $exists = ServerIp::where('server_id', $server->id)
                ->where('ip', $provIp['ip'])
                ->exists();

            if (!$exists && !empty($provIp['ip'])) {
                ServerIp::create([
                    'server_id' => $server->id,
                    'ip' => $provIp['ip'],
                    'type' => $provIp['type'] ?? 'ipv4',
                    'rdns' => is_array($provIp['rdns'] ?? null) ? ($provIp['rdns'][0] ?? null) : ($provIp['rdns'] ?? null),
                    'is_primary' => $provIp['is_primary'] ?? true,
                    'status' => 'active',
                    'provider_ip_id' => $provIp['provider_ip_id'] ?? null,
                ]);
            }
        }
    }

    /**
     * دریافت IP ها از API provider
     */
    private function fetchProviderIps(Server $server, string $provider): array
    {
        $ips = [];

        if ($provider === 'vultr') {
            $ipv4 = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->vultrToken,
            ])->get("https://api.vultr.com/v2/instances/{$server->provider_id}/ipv4");

            if ($ipv4->successful()) {
                foreach ($ipv4->json('ipv4') ?? [] as $item) {
                    $ips[] = [
                        'ip' => $item['ip'] ?? '',
                        'type' => 'ipv4',
                        'rdns' => $item['rdns'] ?? '',
                        'provider_ip_id' => $item['id'] ?? null,
                        'is_primary' => true,
                    ];
                }
            }

            // IPv6 logic...
        } elseif ($provider === 'hetzner') {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->hetznerToken,
            ])->get("https://api.hetzner.cloud/v1/servers/{$server->provider_id}");

            if ($response->successful()) {
                $hetzServer = $response->json()['server'] ?? [];
                
                if (isset($hetzServer['public_net']['ipv4'])) {
                    $ipv4 = $hetzServer['public_net']['ipv4'];
                    $ips[] = [
                        'ip' => $ipv4['ip'] ?? '',
                        'type' => 'ipv4',
                        'rdns' => $ipv4['dns_ptr'] ?? null,
                        'is_primary' => true,
                    ];
                }

                // IPv6 logic...
            }
        }

        return $ips;
    }

    /**
     * دریافت IP های اصلی
     */
private function getMainIps(Server $server)
{
    return ServerIp::where('server_id', $server->id)
        ->where('status', 'active')
        ->where('is_primary', true)
        ->get()
        ->map(function($ip) {
            return [
                'ip' => $ip->ip,
                'type' => $ip->type,
                'rdns' => $ip->rdns ?? '---',
                'id' => $ip->id,
            ];
        })->toArray();
}

    /**
     * دریافت IP های اضافی
     */
private function getAdditionalIps(Server $server)
{
    return ServerIp::where('server_id', $server->id)
        ->where('status', 'active')
        ->where('is_primary', false)
        ->get()
        ->map(function($ip) {
            return [
                'ip' => $ip->ip,
                'type' => $ip->type,
                'rdns' => $ip->rdns ?? '---',
                'id' => $ip->id,
            ];
        })->toArray();
}

    /**
     * دریافت اطلاعات پهنای باند
     */
    private function getBandwidthData(Server $server)
    {
        $period = now()->startOfMonth()->toDateString();
        $bandwidth = BandwidthUsage::where('server_id', $server->id)
            ->where('period', $period)
            ->first();

        $used_tb = $bandwidth->used_tb ?? 0;
        $limit_tb = $bandwidth->limit_tb ?? 1;
        $percent = $limit_tb > 0 ? round(($used_tb / $limit_tb) * 100, 1) : 0;

        return [$used_tb, $limit_tb, $percent];
    }

    /**
     * تب نصب مجدد (AJAX)
     */
    public function reinstallTab(Server $server)
    {
        $this->authorize('view', $server);
        
        $serverData = $this->getServerBaseData($server);
        
        return view('servers.partials.reinstall-tab', $serverData);
    }
    
/**
 * تب شبکه (AJAX)
 */
public function networkTab(Server $server)
{
    $this->authorize('view', $server);
    
    $user = auth()->user();
    $remainingChanges = $user->getRemainingIpChanges();
    
    // ✅ دریافت IP ها با RDNS از دیتابیس
    $mainIps = $server->ips()
        ->where('is_primary', 1)
        ->orderBy('created_at', 'asc')
        ->get()
        ->map(function($ip) use ($server) {
            // ✅ دریافت اطلاعات کامل از API
            $apiData = null;
            
            if ($server->provider === 'vultr') {
                $apiData = $this->fetchVultrIPDetails($server, $ip->ip, $ip->type);
            } elseif ($server->provider === 'hetzner') {
                $apiData = $this->fetchHetznerIPDetails($server, $ip->ip, $ip->type);
            }
            
            return [
                'id' => $ip->id,
                'ip' => $ip->ip,
                'type' => $ip->type,
                'rdns' => $apiData['rdns'] ?? $ip->rdns ?? $ip->reverse_dns ?? 'تنظیم نشده',
                'netmask' => $apiData['netmask'] ?? $ip->netmask ?? '—',
                'gateway' => $apiData['gateway'] ?? $ip->gateway ?? '—',
                'is_primary' => true,
                'status' => $ip->status ?? 'active',
                'created_at' => $ip->created_at,
            ];
        })
        ->toArray();
    
    $additionalIps = $server->ips()
        ->where('is_floating', 1)
        ->orderBy('created_at', 'desc')
        ->get()
        ->map(function($ip) use ($server) {
            // ✅ برای Floating IPs هم RDNS بگیر
            $rdns = $ip->rdns ?? $ip->reverse_dns;
            
            if (!$rdns && $server->provider === 'hetzner') {
                $rdns = $this->fetchHetznerFloatingIPRDNS($ip->ip);
            }
            
            return [
                'id' => $ip->id,
                'ip' => $ip->ip,
                'type' => $ip->type,
                'rdns' => $rdns ?? 'تنظیم نشده',
                'is_floating' => true,
                'status' => $ip->status ?? 'active',
                'created_at' => $ip->created_at,
            ];
        })
        ->toArray();
    
    \Log::info('🔵 Network Tab Data', [
        'server_id' => $server->id,
        'provider' => $server->provider,
        'total_ips' => $server->ips->count(),
        'mainIps_count' => count($mainIps),
        'additionalIps_count' => count($additionalIps),
    ]);
    
    return view('servers.partials.network-tab', compact(
        'server',
        'mainIps',
        'additionalIps',
        'remainingChanges'
    ));
}

/**
 * دریافت جزئیات کامل IP از Vultr
 */
private function fetchVultrIPDetails($server, $ip, $type)
{
    try {
        $response = \Http::withHeaders([
            'Authorization' => 'Bearer ' . config('services.vultr.api_key'),
        ])->get("https://api.vultr.com/v2/instances/{$server->provider_id}");
        
        if ($response->successful()) {
            $instance = $response->json()['instance'] ?? null;
            
            if ($type === 'ipv4' && $instance['main_ip'] === $ip) {
                // ✅ دریافت RDNS برای IPv4
                $rdns = $this->fetchVultrRDNS($server, $ip);
                
                return [
                    'netmask' => $instance['netmask_v4'] ?? '255.255.255.0',
                    'gateway' => $instance['gateway_v4'] ?? null,
                    'rdns' => $rdns,
                ];
            } elseif ($type === 'ipv6' && $instance['v6_main_ip'] === $ip) {
                // ✅ دریافت RDNS برای IPv6
                $rdns = $this->fetchVultrIPv6RDNS($server, $ip);
                
                return [
                    'netmask' => '/' . ($instance['v6_network_size'] ?? 64),
                    'gateway' => $instance['v6_network'] ?? null,
                    'rdns' => $rdns,
                ];
            }
        }
    } catch (\Exception $e) {
        \Log::error('❌ fetchVultrIPDetails Error', [
            'server_id' => $server->id,
            'ip' => $ip,
            'error' => $e->getMessage(),
        ]);
    }
    
    return [];
}

/**
 * دریافت جزئیات کامل IP از Hetzner
 */
private function fetchHetznerIPDetails($server, $ip, $type)
{
    try {
        // ✅ دریافت اطلاعات سرور
        $response = \Http::withHeaders([
            'Authorization' => 'Bearer ' . config('services.hetzner.api_key'),
        ])->get("https://api.hetzner.cloud/v1/servers/{$server->provider_id}");
        
        if ($response->successful()) {
            $hetzServer = $response->json()['server'] ?? null;
            
            if (!$hetzServer) {
                return [];
            }
            
            // ✅ IPv4
            if ($type === 'ipv4' && isset($hetzServer['public_net']['ipv4'])) {
                $ipv4 = $hetzServer['public_net']['ipv4'];
                
                if ($ipv4['ip'] === $ip) {
                    return [
                        'netmask' => '255.255.255.0', // Hetzner معمولاً /32 داره
                        'gateway' => null, // Hetzner Gateway مشخص نمیکنه
                        'rdns' => $ipv4['dns_ptr'][0]['dns_ptr'] ?? null,
                    ];
                }
            }
            
            // ✅ IPv6
            if ($type === 'ipv6' && isset($hetzServer['public_net']['ipv6'])) {
                $ipv6 = $hetzServer['public_net']['ipv6'];
                
                // چک کردن اگه IP با شبکه IPv6 مطابقت داره
                if (strpos($ip, $ipv6['network']) !== false || $ipv6['ip'] === $ip) {
                    return [
                        'netmask' => '/' . ($ipv6['network_size'] ?? 64),
                        'gateway' => $ipv6['network'] ?? null,
                        'rdns' => $ipv6['dns_ptr'][0]['dns_ptr'] ?? null,
                    ];
                }
            }
        }
    } catch (\Exception $e) {
        \Log::error('❌ fetchHetznerIPDetails Error', [
            'server_id' => $server->id,
            'ip' => $ip,
            'error' => $e->getMessage(),
        ]);
    }
    
    return [];
}

/**
 * دریافت RDNS IPv4 از Vultr
 */
private function fetchVultrRDNS($server, $ip)
{
    try {
        $response = \Http::withHeaders([
            'Authorization' => 'Bearer ' . config('services.vultr.api_key'),
        ])->get("https://api.vultr.com/v2/instances/{$server->provider_id}/ipv4/reverse");
        
        if ($response->successful()) {
            $reverseIps = $response->json()['reverse_ipv4s'] ?? [];
            
            foreach ($reverseIps as $reverseIp) {
                if ($reverseIp['ip'] === $ip) {
                    return $reverseIp['reverse'] ?? null;
                }
            }
        }
    } catch (\Exception $e) {
        \Log::warning('Failed to fetch Vultr RDNS', [
            'server_id' => $server->id,
            'ip' => $ip,
            'error' => $e->getMessage(),
        ]);
    }
    
    return null;
}

/**
 * دریافت RDNS IPv6 از Vultr
 */
private function fetchVultrIPv6RDNS($server, $ip)
{
    try {
        $response = \Http::withHeaders([
            'Authorization' => 'Bearer ' . config('services.vultr.api_key'),
        ])->get("https://api.vultr.com/v2/instances/{$server->provider_id}/ipv6/reverse");
        
        if ($response->successful()) {
            $reverseIps = $response->json()['reverse_ipv6s'] ?? [];
            
            foreach ($reverseIps as $reverseIp) {
                if ($reverseIp['ip'] === $ip) {
                    return $reverseIp['reverse'] ?? null;
                }
            }
        }
    } catch (\Exception $e) {
        \Log::warning('Failed to fetch Vultr IPv6 RDNS', [
            'server_id' => $server->id,
            'ip' => $ip,
            'error' => $e->getMessage(),
        ]);
    }
    
    return null;
}

/**
 * دریافت RDNS از Hetzner (قدیمی - حذف کن یا نگه دار برای Fallback)
 */
private function fetchHetznerRDNS($ip)
{
    try {
        $response = \Http::withHeaders([
            'Authorization' => 'Bearer ' . config('services.hetzner.api_key'),
        ])->get('https://api.hetzner.cloud/v1/primary_ips');
        
        if ($response->successful()) {
            $primaryIps = $response->json()['primary_ips'] ?? [];
            
            foreach ($primaryIps as $primaryIp) {
                if ($primaryIp['ip'] === $ip) {
                    return $primaryIp['dns_ptr'][0]['dns_ptr'] ?? null;
                }
            }
        }
    } catch (\Exception $e) {
        \Log::warning('Failed to fetch Hetzner RDNS', [
            'ip' => $ip,
            'error' => $e->getMessage(),
        ]);
    }
    
    return null;
}

/**
 * دریافت RDNS برای Floating IP های Hetzner
 */
private function fetchHetznerFloatingIPRDNS($ip)
{
    try {
        $response = \Http::withHeaders([
            'Authorization' => 'Bearer ' . config('services.hetzner.api_key'),
        ])->get('https://api.hetzner.cloud/v1/floating_ips');
        
        if ($response->successful()) {
            $floatingIps = $response->json()['floating_ips'] ?? [];
            
            foreach ($floatingIps as $floatingIp) {
                if ($floatingIp['ip'] === $ip) {
                    return $floatingIp['dns_ptr'][0]['dns_ptr'] ?? null;
                }
            }
        }
    } catch (\Exception $e) {
        \Log::warning('Failed to fetch Hetzner Floating IP RDNS', [
            'ip' => $ip,
            'error' => $e->getMessage(),
        ]);
    }
    
    return null;
}

    /**
     * تب پهنای باند (AJAX)
     */
    public function bandwidthTab(Server $server)
    {
        $this->authorize('view', $server);
        
        $serverData = $this->getServerBaseData($server);
        
        return view('servers.partials.bandwidth-tab', $serverData);
    }

    /**
     * تب ابیوز (AJAX)
     */
    public function abuseTab(Server $server)
    {
        $this->authorize('view', $server);
        
        return view('servers.partials.abuse-tab', compact('server'));
    }

    /**
     * تب اکتیویتی (AJAX)
     */
    public function activityTab(Server $server)
    {
        $this->authorize('view', $server);
        
        // می‌تونید لاگ‌ها رو از دیتابیس بگیرید
        $activities = []; // ServerActivity::where('server_id', $server->id)->latest()->get();
        
        return view('servers.partials.activity-tab', compact('server', 'activities'));
    }

/**
 * تب هزینه‌ها (AJAX)
 */
public function costsTab(Server $server)
{
    $this->authorize('view', $server);
    
    return view('servers.partials.costs-tab', compact('server'));
}





public function reinstall(Request $request, Server $server)
{
    $request->validate([
        'image_id' => 'required'
    ]);
    try {
        if ($server->provider === 'vultr') {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->vultrToken,
                'Content-Type'  => 'application/json',
                'Accept'        => 'application/json',
            ])->post("https://api.vultr.com/v2/instances/{$server->provider_id}/reinstall", [
                'os_id' => $request->image_id
            ]);
            $data = $response->json();

            if ($response->successful() && !empty($data['instance']['default_password'])) {
                $server->password = $data['instance']['default_password'];
                $server->save();
            }

            return response()->json([
                'success' => $response->successful(),
                'data' => $data,
                'message' => $response->successful() ? 'نصب مجدد ولتر آغاز شد.' : ($data['error'] ?? 'خطا در نصب مجدد ولتر')
            ]);

        } elseif ($server->provider === 'parspack') {
            $client = new Client([
                'base_uri' => 'https://my.abrha.net/cserver/api/public/v1/',
                'headers' => [
                    'Authorization' => 'Bearer ' . $this->parspackToken,
                    'Accept' => 'application/json',
                ]
            ]);
            $payload = [
                'type' => 'rebuild',
                'image' => $request->image_id
            ];
            Log::info("Reinstall request payload for server {$server->provider_id}: ", $payload);
            $response = $client->post("vms/{$server->provider_id}/actions", [
                'json' => $payload
            ]);
            $data = json_decode($response->getBody(), true);

            if (!empty($data['password'])) {
                $server->password = $data['password'];
                $server->save();
            }

            Log::info("Reinstall response for server {$server->provider_id}: ", $data);
            return response()->json(['success' => true, 'data' => $data, 'message' => 'نصب مجدد پارس‌پک آغاز شد.']);

        } elseif ($server->provider === 'hetzner') {
    // Generate new password and cloud-init user_data
    $password = \Illuminate\Support\Str::random(14);
    $userData = <<<CLOUDINIT
#cloud-config
chpasswd:
  list: |
    root:$password
  expire: False
ssh_pwauth: True
CLOUDINIT;

$response = Http::withHeaders([
    'Authorization' => 'Bearer ' . $this->hetznerToken,
    'Content-Type'  => 'application/json',
    'Accept'        => 'application/json',
])->post("https://api.hetzner.cloud/v1/servers/{$server->provider_id}/actions/rebuild", [
    'image'     => $request->image_id,
    'user_data' => $userData
]);

$data = $response->json();
$errorMessage = $data['error']['message'] ?? $data['message'] ?? '';

// ذخیره رمز جدید اگر ری‌اینستال موفق بود
if ($response->successful()) {
    $server->password = $password;
    $server->save();
}

// تعیین پیام مناسب با توجه به وضعیت و ارور دریافتی
if (!$response->successful() && stripos($errorMessage, 'image not found') !== false) {
    $customMessage = 'سیستم عامل انتخابی برای این کلود در دسترس نیست. لطفا سیستم عامل دیگری را انتخاب کنید.';
} else {
    $customMessage = $response->successful()
        ? 'نصب مجدد هتزنر آغاز شد.'
        : ($data['error_message'] ?? $data['message'] ?? 'خطا در نصب مجدد هتزنر');
}

return response()->json([
    'success'  => $response->successful(),
    'data'     => $data,
    'password' => $response->successful() ? $password : null,
    'message'  => $customMessage
]);
} elseif ($server->provider === 'arvan') {
            $arvanToken = config('services.arvan.token');
            $region = $server->region ?? 'ir-thr-fr1';

            Log::info("ARVAN-reinstall: درخواست", [
                'server_id' => $server->provider_id,
                'image_id'  => $request->image_id
            ]);

            $response = Http::withHeaders([
                'Authorization' => 'Apikey ' . $arvanToken,
                'Content-Type'  => 'application/json',
                'Accept'        => 'application/json',
            ])->post("https://napi.arvancloud.ir/ecc/v1/regions/{$region}/servers/{$server->provider_id}/rebuild", [
                'image_id' => $request->image_id
            ]);
            $data = $response->json();

            Log::info("ARVAN-reinstall: پاسخ Arvan", [
                'status' => $response->status(),
                'body' => $response->body(),
            ]);

            if ($response->successful()) {
                // در صورت نیاز به ست کردن رمز جدید، طبق خروجی Arvan کد اضافه کن
                return response()->json([
                    'success' => true,
                    'data' => $data,
                    'message' => 'نصب مجدد آروان آغاز شد.'
                ]);
            } else {
                $arvanError = ($data['error']['message'] ?? $response->body() ?? 'خطا در نصب مجدد آروان');
                return response()->json([
                    'success' => false,
                    'data' => $data,
                    'message' => $arvanError
                ], 500);
            }
        } else {
            return response()->json(['success' => false, 'message' => 'نصب مجدد برای این provider پیاده‌سازی نشده است.']);
        }
    } catch (\Exception $e) {
        Log::error("Reinstall error for server {$server->provider_id}: ".$e->getMessage());
        return response()->json([
            'success' => false,
            'message' => $e->getMessage()
        ]);
    }
}
    private function callParspackAction($uuid, $actionType)
    {
        if(empty($uuid)){
            throw new \Exception("provider_id سرور خالی است!");
        }
        $client = new Client();
        $url = $this->parspackBase . $uuid . '/actions';
        $response = $client->post($url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->parspackToken,
                'Accept-Language' => 'fa',
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'type' => $actionType
            ],
            'timeout' => 10,
        ]);
        $body = json_decode($response->getBody()->getContents(), true);
        if(isset($body['error'])) {
            throw new \Exception($body['error']);
        }
        return $body;
    }
}