<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use App\Models\Server;
use App\Models\Project;

class ParspackController extends Controller
{
    private $apiToken = '490|13KlsDV5A3vsMeTDgQ308JGGX7zgAh21i9lBVSI84dee8b5d';
    private $baseUrl  = 'https://my.abrha.net/cserver/api/public/v1/';

    // گرفتن لیست مناطق و پلن‌های کامل
    public function locations()
    {
        try {
            // گرفتن مناطق
            $regionsResponse = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->apiToken,
                'Accept'        => 'application/json',
                'Content-Type'  => 'application/json',
            ])->get($this->baseUrl . 'regions');

            // گرفتن پلن‌ها
            $sizesResponse = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->apiToken,
                'Accept'        => 'application/json',
                'Content-Type'  => 'application/json',
            ])->get($this->baseUrl . 'sizes');

            if ($regionsResponse->successful() && $sizesResponse->successful()) {
                $regionsData = $regionsResponse->json();
                $sizesData   = $sizesResponse->json();

                // مناطق (regions)
                $locations = collect($regionsData['regions'])->map(function ($region, $index) {
                    return [
                        'id' => $index,
                        'name' => $region['name'],
                        'slug' => $region['slug'],
                        'sizes' => $region['sizes'],
                        'countries' => [
                            [
                                'id' => $index,
                                'name' => $region['name'],
                                'flag' => $region['slug'] . '.png',
                            ]
                        ]
                    ];
                });

                // همه پلن‌ها (sizes) با جزئیات کامل
                $plans = isset($sizesData['sizes']) ? $sizesData['sizes'] : $sizesData;

                return response()->json([
                    'status' => 'success',
                    'locations' => $locations,
                    'parspack_plans' => $plans
                ]);
            }

            return response()->json(['status' => 'error','message'=>'خطا در دریافت داده‌ها از API پارس‌پک'], 500);

        } catch (\Exception $e) {
            Log::error('Locations error: ' . $e->getMessage());
            return response()->json(['status' => 'error','message'=>'خطا: '.$e->getMessage()], 500);
        }
    }

    // گرفتن لیست تصاویر
    public function images()
    {
        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->apiToken,
                'Accept'        => 'application/json',
                'Content-Type'  => 'application/json',
            ])->get($this->baseUrl . 'images');

            if ($response->successful()) {
                $data = $response->json();
                return response()->json(['status' => 'success','images' => $data['images'] ?? []]);
            }

            return response()->json(['status' => 'error','message'=>'خطا در دریافت تصاویر از API پارس‌پک'], $response->status());

        } catch (\Exception $e) {
            Log::error('Images error: ' . $e->getMessage());
            return response()->json(['status' => 'error','message'=>'خطا: '.$e->getMessage()], 500);
        }
    }

    // ساخت VM و ذخیره در دیتابیس
    public function createVM(Request $request, $projectId)
    {
        $project = Project::findOrFail($projectId);

        // اعتبارسنجی ورودی‌ها
        $request->validate([
            'region' => 'required|string',
            'size'   => 'required|string',
            'image'  => 'required|string',
        ]);

        $serverName = 'vm-' . Str::random(6);

        $payload = [
            'name'   => $serverName,
            'region' => $request->region,
            'size'   => $request->size,
            'image'  => $request->image,
        ];

        try {
            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->apiToken,
                'Accept'        => 'application/json',
                'Content-Type'  => 'application/json',
            ])->post($this->baseUrl . 'vms', $payload);

            if (!$response->successful()) {
                Log::error('Error creating VM: ' . $response->body());
                return response()->json(['status'=>'error','message'=>'خطا در ساخت سرور: '.$response->body()], $response->status());
            }

            $data = $response->json();

            // ذخیره در دیتابیس
            $server = Server::create([
                'user_id'     => auth()->id(),
                'project_id'  => $project->id,
                'parspack_id' => $data['uuid'] ?? null,
                'name'        => $serverName,
                'region'      => $request->region,
                'plan'        => $request->size,
                'image'       => $request->image,
                'status'      => 'creating', // حالت اولیه
                'progress'    => 0,
                'ip_address'  => null,
            ]);

            return response()->json([
                'status' => 'success',
                'message' => 'سرور با موفقیت ساخته شد و در حال آماده‌سازی است',
                'server' => $server,
                'api_response' => $data
            ]);

        } catch (\Exception $e) {
            Log::error('Exception in createVM: ' . $e->getMessage());
            return response()->json(['status'=>'error','message'=>'خطا در ساخت سرور: '.$e->getMessage()], 500);
        }
    }
}