<?php

namespace App\Http\Controllers;

use App\Models\JobExperience;
use App\Models\JobTitle;
use App\Services\SalaryMarketComparisonService;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class HomeController extends Controller
{
    public function index(Request $request)
    {

        // return DB::getDefaultConnection();
        // return $user = auth()->user();

        // Fetch Recent Jobs
        $jobs = JobExperience::published()
            ->whereNotNull('country')
            ->where('country', '!=', '')
            ->whereNotNull('job_title')
            ->whereNotNull('currency')
            ->latest()
            ->limit(3)
            ->get();


        $country = session('db_connection');
        // 4️⃣ Ensure country is either US or CA
        if (!in_array($country, ['CA', 'US'])) {
            $country = 'CA';
        }
        if ($country == 'CA') {
            $country = "Canada";
        }
        if ($country == 'US') {
            $country = "United States";
        }


        if ($jobs->count() < 5) {

            $jobs = array_map(fn($j) => (object) $j, $this->getRandomJobsByCountry($country, 3));
        }

        // Job Titles List
        $jobTitles = [];

        // Countries List
        $countries = Cache::remember('all_countries', 60 * 60 * 24, function () {
            try {
                $response = Http::get('https://restcountries.com/v3.1/all?fields=name,cca2');
                if ($response->successful()) {
                    return collect($response->json())
                        ->map(fn($c) => $c['name']['common'])
                        ->sort()
                        ->values()
                        ->toArray();
                }
            } catch (\Exception $e) {
                // Silent fail
            }
            return ['United States', 'United Kingdom', 'Canada', 'Nigeria', 'Germany', 'India'];
        });

        // return session('db_connection');
        return view('home', compact('jobs', 'jobTitles', 'countries'));
    }


    public function seeSalary(Request $request)
    {
        $countries = Cache::remember('all_countries', 60 * 60 * 24, function () {
            try {
                $response = Http::get('https://restcountries.com/v3.1/all?fields=name,cca2');
                if ($response->successful()) {
                    return collect($response->json())
                        ->map(fn($c) => $c['name']['common'])
                        ->sort()
                        ->values()
                        ->toArray();
                }
            } catch (\Exception $e) {
                // Silent fail
            }

            return ['United States', 'United Kingdom', 'Canada', 'Nigeria', 'Germany', 'India', 'France', 'Australia'];
        });

        $jobTitle = $request->query('job_title');
        $locationSearch = $request->query('location');
        $stateSearch = $request->query('state');
        $postcodeSearch = $request->query('postcode');
        $currency = $request->query('currency') ?? "USD";

        // Default to annually if not set
        $pay_frequency = $request->query('pay_frequency') ?? 'annually';

        $results = [];

        if (!$jobTitle) {
            return view('salary.index', [
                'salaryData' => [],
                'jobTitle' => $jobTitle,
                'location' => $locationSearch,
                'state' => $stateSearch,
                'postcode' => $postcodeSearch,
                'countries' => $countries,
                'currency' => $currency,
            ]);
        }

        /*
        |--------------------------------------------------------------------------
        | 1️⃣ Always Call AI Service First
        |--------------------------------------------------------------------------
        */
        $aiPayload = [
            'job_title' => $jobTitle,
            'level' => $request->query('level'),
            'experience' => (int) $request->query('experience', 0),
            'location' => [
                'country' => $locationSearch,
                'state' => $stateSearch,
                'city' => null,
            ],
            'pay_frequency' => $pay_frequency,
            'base_salary' => null,
            'company' => [
                'size' => null,
                'industry' => null,
            ]
        ];

        $marketService = app()->make(SalaryMarketComparisonService::class);
        // return $marketComparison = $marketService->compare($aiPayload);
        $marketComparison = Cache::remember(
            "ai_salary_{$jobTitle}_{$locationSearch}_{$currency}_{$pay_frequency}",
            3600,
            fn() => $marketService->compare($aiPayload)
        );

        $aiData = null;
        if (is_array($marketComparison) && isset($marketComparison['percentiles'], $marketComparison['market_comparison'])) {
            $values = [
                'Lower Pay' => (int) $marketComparison['percentiles']['p25'],
                'Average' => (int) $marketComparison['percentiles']['p50'],
                'Above Pay' => (int) $marketComparison['percentiles']['p75'],
                'Top Pay' => (int) $marketComparison['percentiles']['p90'],
            ];

            asort($values);

            $aiData = [
                'source' => 'ai',
                'currency' => $marketComparison['currency'] ?? $currency,
                'market_average' => (int) $marketComparison['market_comparison']['avg'],
                'chart' => [
                    'values' => $values,
                    'max' => max($values),
                ],
            ];
        }

        /*
        |--------------------------------------------------------------------------
        | 2️⃣ Fetch JobExperience Data (If Any) and adjust for pay frequency
        |--------------------------------------------------------------------------
        */
        $query = JobExperience::published()
            ->whereNotNull('country')
            ->where('country', '!=', '')
            ->where('job_title', 'LIKE', "%{$jobTitle}%");

        if ($locationSearch) {
            $query->where('country', 'LIKE', "%{$locationSearch}%");
        }

        if ($stateSearch) {
            $query->where('state', 'LIKE', "%{$stateSearch}%");
        }

        if ($postcodeSearch) {
            $query->where('post_code', 'LIKE', "%{$postcodeSearch}%");
        }

        if ($currency) {
            $query->where('currency', $currency);
        }

        $experiences = $query->get();

        $experienceData = null;

        if ($experiences->isNotEmpty()) {
            // Conversion factor based on frequency
            $factor = match (strtolower($pay_frequency)) {
                'monthly' => 12,
                'semi-monthly' => 24,
                'biweekly' => 26,
                'weekly' => 52,
                'hourly' => 2080, // assuming 40h/week * 52 weeks
                default => 1, // annually
            };

            $minSalary = $experiences->min('annual_base_salary') / $factor;
            $maxSalary = $experiences->max('annual_base_salary') / $factor;
            $avgSalary = $experiences->avg('annual_base_salary') / $factor;

            $experienceData = [
                'source' => 'experience',
                'currency' => $currency,
                'min' => round($minSalary, 2),
                'max' => round($maxSalary, 2),
                'average' => round($avgSalary, 2),
                'companies' => $experiences->pluck('company_name')->filter()->unique()->count(),
            ];
        }

        /*
        |--------------------------------------------------------------------------
        | 3️⃣ Return Array of Jobs
        |--------------------------------------------------------------------------
        */
        $results[] = [
            'job_title' => $jobTitle,
            'location' => [
                'country' => $locationSearch,
                'state' => $stateSearch,
                'city' => $request->query('city'),
                'postcode' => $postcodeSearch,
                'flag' => $this->getFlagByCountryName($locationSearch),
            ],
            'ai_market_data' => $aiData,
            'experience_data' => $experienceData,
        ];

        return view('salary.index', [
            'salaryData' => $results,
            'jobTitle' => $jobTitle,
            'location' => $locationSearch,
            'state' => $stateSearch,
            'postcode' => $postcodeSearch,
            'countries' => $countries,
            'currency' => $currency,
            'pay_frequency' => $pay_frequency,
        ]);
    }



    public function viewSalary(Request $request, string $location, string $jobTitle)
    {
        $countryName = urldecode($location);
        $decodedJobTitle = urldecode($jobTitle);
        $state = $request->query('state');
        $city = $request->query('city');
        $postcode = $request->query('postcode');
        $currency = $request->currency ?? "USD";

        // Default pay frequency is annually
        $pay_frequency = $request->query('pay_frequency') ?? 'annually';

        /*
        |--------------------------------------------------------------------------
        | 1️⃣ COMMUNITY DATA (JobExperience)
        |--------------------------------------------------------------------------
        */

        if ($currency == 'all') {
            $query = JobExperience::published()
                ->where('country', 'LIKE', "%{$countryName}%");
        } else {
            $query = JobExperience::published()
                ->where('country', 'LIKE', "%{$countryName}%")
                ->where('currency', $currency);
        }

        if ($decodedJobTitle && strtolower($decodedJobTitle) !== 'all-roles') {
            $query->where('job_title', 'LIKE', "%{$decodedJobTitle}%");
        }

        if ($state) {
            $query->where('state', 'LIKE', "%{$state}%");
        }

        if ($city) {
            $query->where('city', 'LIKE', "%{$city}%");
        }

        if ($postcode) {
            $query->where('post_code', 'LIKE', "%{$postcode}%");
        }

        $allMatchingSalaries = (clone $query)->get();

        $experienceData = null;
        $avgSalary = 0;
        $records = [];

        if ($allMatchingSalaries->isNotEmpty()) {
            // Conversion factor based on pay frequency
            $factor = match (strtolower($pay_frequency)) {
                'monthly' => 12,
                'semi-monthly' => 24,
                'biweekly' => 26,
                'weekly' => 52,
                'hourly' => 2080, // 40h/week * 52 weeks
                default => 1, // annually
            };

            $minSalary = $allMatchingSalaries->min('annual_base_salary') / $factor;
            $maxSalary = $allMatchingSalaries->max('annual_base_salary') / $factor;
            $avgSalary = $allMatchingSalaries->avg('annual_base_salary') / $factor;

            $experienceData = [
                'min' => round($minSalary, 2),
                'max' => round($maxSalary, 2),
                'average' => round($avgSalary, 2),
                'companies' => $allMatchingSalaries->pluck('company_name')->unique()->count(),
                'currency' => $currency,
            ];

            $records = $allMatchingSalaries
                ->pluck('annual_base_salary')
                ->map(fn($salary) => round($salary / $factor, 2))
                ->sort()
                ->values()
                ->toArray();

            $records = array_merge([0], $records, [0]);
        }

        $experiences = $query->latest()->paginate(20);

        /*
        |--------------------------------------------------------------------------
        | 2️⃣ AI MARKET DATA (ALWAYS CALL)
        |--------------------------------------------------------------------------
        */

        $aiPayload = [
            'job_title' => $decodedJobTitle,
            'experience' => 0,
            'location' => [
                'country' => $countryName,
                'state' => $state,
                'city' => $city,
            ],
            'base_salary' => null,
            'company' => [
                'size' => null,
                'industry' => null,
            ],
            'pay_frequency' => $pay_frequency,
        ];

        $marketService = app()->make(SalaryMarketComparisonService::class);

        $marketComparison = Cache::remember(
            "ai_salary_{$decodedJobTitle}_{$countryName}_{$currency}_{$pay_frequency}_{$pay_frequency}",
            3600 * 4,
            fn() => $marketService->compare($aiPayload)
        );

        $aiData = null;

        if (is_array($marketComparison) && isset($marketComparison['percentiles'], $marketComparison['market_comparison'])) {
            // Adjust AI salaries if pay frequency is not annual
            $factor = match (strtolower($pay_frequency)) {
                'monthly' => 12,
                'semi-monthly' => 24,
                'biweekly' => 26,
                'weekly' => 52,
                'hourly' => 2080,
                default => 1,
            };

            $values = [
                'p25' => (int) $marketComparison['percentiles']['p25'] / $factor,
                'p50' => (int) $marketComparison['percentiles']['p50'] / $factor,
                'p75' => (int) $marketComparison['percentiles']['p75'] / $factor,
                'p90' => (int) $marketComparison['percentiles']['p90'] / $factor,
            ];

            $aiData = [
                'min' => round(min($values), 2),
                'max' => round(max($values), 2),
                'average' => round((int) $marketComparison['market_comparison']['avg'] / $factor, 2),
                'currency' => $marketComparison['currency'],
            ];
        }

        /*
        |--------------------------------------------------------------------------
        | 3️⃣ RETURN VIEW
        |--------------------------------------------------------------------------
        */

        $dataAll = [
            'location' => $countryName,
            'jobTitle' => $decodedJobTitle,
            'currency' => $currency,
            'pay_frequency' => $pay_frequency,
            'country_flag' => $this->getFlagByCountryName($countryName),
            'experienceData' => $experienceData,
            'aiData' => $aiData,
            'avg_salary' => $avgSalary,
            'records' => $records,
            'experiences' => $experiences,
            'state' => $state,
            'city' => $city,
            'postcode' => $postcode,
        ];

        return view('salary.view', $dataAll);
    }


    private function getFlagByCountryName($countryName)
    {
        $countryNameEncoded = rawurlencode($countryName);
        $url = "https://restcountries.com/v3.1/name/{$countryNameEncoded}?fullText=true";

        try {
            $response = @file_get_contents($url);
            if ($response) {
                $data = json_decode($response, true);
                if (!empty($data[0]['flags']['png'])) {
                    return $data[0]['flags']['png'];
                }
            }
        } catch (\Exception $e) {
            Log::error('Flag fetch error: ' . $e->getMessage());
        }

        return 'https://via.placeholder.com/48x36.png?text=?';
    }
}