<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use App\Models\PerizinanStatus;
use App\Models\FastestPermohonan;
use App\Models\TerakhirTerbit;
use Carbon\Carbon;

class PerizinanApiService
{
    private $baseUrl;
    private $bearerToken;
    private $apiKey;

    public function __construct()
    {
        $this->baseUrl = config('services.perizinan.base_url', 'https://wsdev.jakarta.go.id/gateway/DataPerizinanLingkungan/1.0');
        $this->bearerToken = config('services.perizinan.bearer_token');
        $this->apiKey = config('services.perizinan.api_key');
    }

    /**
     * Fetch summary by status from API
     */
    public function fetchSummaryByStatus($kategori)
    {
        try {
            $url = "{$this->baseUrl}/summary_by_status";

            Log::info("Fetching data from API", [
                'url' => $url,
                'kategori' => $kategori
            ]);

            $response = Http::timeout(60) // Increase timeout to 60 seconds
                ->retry(3, 100) // Retry 3 times with 100ms delay
                ->withHeaders([
                    'Authorization' => 'Bearer ' . $this->bearerToken,
                    'x-Gateway-APIKey' => $this->apiKey,
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ])->get($url, [
                    'kategori' => $kategori
                ]);

            if ($response->successful()) {
                $data = $response->json();

                Log::info("API Response received", [
                    'kategori' => $kategori,
                    'success' => $data['success'] ?? false,
                    'data_count' => count($data['data'] ?? [])
                ]);

                return $data;
            } else {
                Log::error("API request failed", [
                    'kategori' => $kategori,
                    'status' => $response->status(),
                    'body' => $response->body()
                ]);

                return null;
            }
        } catch (\Exception $e) {
            Log::error("Exception occurred while fetching API data", [
                'kategori' => $kategori,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return null;
        }
    }

    /**
     * Sync data to database
     */
    public function syncToDatabase($kategori)
    {
        $apiData = $this->fetchSummaryByStatus($kategori);

        if (!$apiData || !($apiData['success'] ?? false)) {
            Log::warning("Failed to fetch data for kategori: {$kategori}");
            return false;
        }

        $syncDate = Carbon::today();
        $apiLastUpdated = Carbon::parse($apiData['last_updated']);
        $syncedCount = 0;

        foreach ($apiData['data'] as $item) {
            // Check if data already exists for today
            $exists = PerizinanStatus::where('Kategori_ID', $kategori)
                ->where('StatusID', $item['id'])
                ->whereDate('SyncDate', $syncDate)
                ->exists();

            if (!$exists) {
                PerizinanStatus::create([
                    'Kategori_ID' => $kategori,
                    'StatusID' => $item['id'],
                    'Label' => $item['label'],
                    'Value' => $item['value'],
                    'ApiLastUpdated' => $apiLastUpdated,
                    'SyncDate' => $syncDate
                ]);

                $syncedCount++;
            }
        }

        Log::info("Data synced successfully", [
            'kategori' => $kategori,
            'synced_count' => $syncedCount,
            'sync_date' => $syncDate->format('Y-m-d'),
            'api_last_updated' => $apiLastUpdated->format('Y-m-d H:i:s')
        ]);

        return true;
    }

    /**
     * Fetch fastest permohonan from API
     */
    public function fetchFastestPermohonan($kategori, $limit = 5)
    {
        try {
            $url = "{$this->baseUrl}/fastest_permohonan";

            Log::info("Fetching fastest permohonan data from API", [
                'url' => $url,
                'kategori' => $kategori,
                'limit' => $limit
            ]);

            $response = Http::timeout(60) // Increase timeout to 60 seconds
                ->retry(3, 100) // Retry 3 times with 100ms delay
                ->withHeaders([
                    'Authorization' => 'Bearer ' . $this->bearerToken,
                    'x-Gateway-APIKey' => $this->apiKey,
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ])->get($url, [
                    'kategori' => $kategori,
                    'limit' => $limit
                ]);

            if ($response->successful()) {
                $data = $response->json();

                Log::info("Fastest permohonan API Response received", [
                    'kategori' => $kategori,
                    'limit' => $limit,
                    'success' => $data['success'] ?? false,
                    'data_count' => count($data['data'] ?? [])
                ]);

                return $data;
            } else {
                Log::error("Fastest permohonan API request failed", [
                    'kategori' => $kategori,
                    'limit' => $limit,
                    'status' => $response->status(),
                    'body' => $response->body()
                ]);

                return null;
            }
        } catch (\Exception $e) {
            Log::error("Exception occurred while fetching fastest permohonan data", [
                'kategori' => $kategori,
                'limit' => $limit,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return null;
        }
    }

    /**
     * Sync fastest permohonan data to database
     */
    public function syncFastestDataToDatabase($kategori, $limit = 5)
    {
        $apiData = $this->fetchFastestPermohonan($kategori, $limit);

        if (!$apiData || !($apiData['success'] ?? false)) {
            Log::warning("Failed to fetch fastest permohonan data for kategori: {$kategori}");
            return false;
        }

        $syncDate = Carbon::today();
        $apiLastUpdated = Carbon::parse($apiData['last_updated']);
        $syncedCount = 0;

        // Delete existing data for today to ensure we have fresh data
        FastestPermohonan::where('Kategori_ID', $kategori)
            ->whereDate('SyncDate', $syncDate)
            ->delete();

        foreach ($apiData['data'] as $index => $item) {
            FastestPermohonan::create([
                'Kategori_ID' => $kategori,
                'Nama' => $item['nama'],
                'Total' => $item['total'],
                'DurasiPemohon' => $item['durasi_pemohon'],
                'DurasiPetugas' => $item['durasi_petugas'],
                'ApiLastUpdated' => $apiLastUpdated,
                'SyncDate' => $syncDate
            ]);

            $syncedCount++;
        }

        Log::info("Fastest permohonan data synced successfully", [
            'kategori' => $kategori,
            'synced_count' => $syncedCount,
            'sync_date' => $syncDate->format('Y-m-d'),
            'api_last_updated' => $apiLastUpdated->format('Y-m-d H:i:s')
        ]);

        return true;
    }

    /**
     * Fetch terakhir terbit from API
     */
    public function fetchTerakhirTerbit($kategori, $limit = 5)
    {
        try {
            $url = "{$this->baseUrl}/terakhir_terbit";

            Log::info("Fetching terakhir terbit data from API", [
                'url' => $url,
                'kategori' => $kategori,
                'limit' => $limit
            ]);

            $response = Http::timeout(60) // Increase timeout to 60 seconds
                ->retry(3, 100) // Retry 3 times with 100ms delay
                ->withHeaders([
                    'Authorization' => 'Bearer ' . $this->bearerToken,
                    'x-Gateway-APIKey' => $this->apiKey,
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json'
                ])->get($url, [
                    'kategori' => $kategori,
                    'limit' => $limit
                ]);

            if ($response->successful()) {
                $data = $response->json();

                Log::info("Terakhir terbit API Response received", [
                    'kategori' => $kategori,
                    'limit' => $limit,
                    'success' => $data['success'] ?? false,
                    'data_count' => count($data['data'] ?? [])
                ]);

                return $data;
            } else {
                Log::error("Terakhir terbit API request failed", [
                    'kategori' => $kategori,
                    'limit' => $limit,
                    'status' => $response->status(),
                    'body' => $response->body()
                ]);

                return null;
            }
        } catch (\Exception $e) {
            Log::error("Exception occurred while fetching terakhir terbit data", [
                'kategori' => $kategori,
                'limit' => $limit,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            return null;
        }
    }

    /**
     * Sync terakhir terbit data to database
     */
    public function syncTerakhirTerbitToDatabase($kategori, $limit = 5)
    {
        $apiData = $this->fetchTerakhirTerbit($kategori, $limit);

        if (!$apiData || !($apiData['success'] ?? false)) {
            Log::warning("Failed to fetch terakhir terbit data for kategori: {$kategori}");
            return false;
        }

        $syncDate = Carbon::today();
        $apiLastUpdated = Carbon::parse($apiData['last_updated']);
        $syncedCount = 0;

        // Delete existing data for today to ensure we have fresh ranking
        TerakhirTerbit::where('Kategori_ID', $kategori)
            ->whereDate('SyncDate', $syncDate)
            ->delete();

        foreach ($apiData['data'] as $index => $item) {
            TerakhirTerbit::create([
                'Kategori_ID' => $kategori,
                'NamaIzin' => $item['nama_izin'],
                'Pemohon' => $item['pemohon'],
                'TanggalTerbit' => Carbon::parse($item['tanggal_terbit']),
                'ApiLastUpdated' => $apiLastUpdated,
                'SyncDate' => $syncDate
            ]);

            $syncedCount++;
        }

        Log::info("Terakhir terbit data synced successfully", [
            'kategori' => $kategori,
            'synced_count' => $syncedCount,
            'sync_date' => $syncDate->format('Y-m-d'),
            'api_last_updated' => $apiLastUpdated->format('Y-m-d H:i:s')
        ]);

        return true;
    }

    /**
     * Sync all categories
     */
    public function syncAllCategories($includeFastest = true, $includeTerakhirTerbit = true)
    {
        $categories = ['pertek', 'amdal'];
        $results = [];

        foreach ($categories as $kategori) {
            // Sync status data
            $results[$kategori]['status'] = $this->syncToDatabase($kategori);

            // Sync fastest data if requested
            if ($includeFastest) {
                $results[$kategori]['fastest'] = $this->syncFastestDataToDatabase($kategori, 5);
            }

            // Sync terakhir terbit data if requested
            if ($includeTerakhirTerbit) {
                $results[$kategori]['terakhir_terbit'] = $this->syncTerakhirTerbitToDatabase($kategori, 5);
            }
        }

        return $results;
    }
}
