<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Currency;
use App\Models\CurrencyRate;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;

class CurrencyRateController extends Controller
{
    private function getCompanyId()
    {
        return Auth::user()->companyid ?? Auth::user()->current_company_id;
    }

    public function index()
    {
        $companyId = $this->getCompanyId();
        $rates = CurrencyRate::where('company_id', $companyId)
            ->with(['targetCurrency'])
            ->orderBy('rate_date', 'desc')
            ->paginate(30);

        return view('currency-rates.index', compact('rates'));
    }

    public function sync()
    {
        $apiKey = config('services.exchangerate.api_key');
        $baseCode = 'ZMW'; 
        $companyId = $this->getCompanyId();
        
        // 1. Get or Create Base Currency (ZMW)
        // We check manually to avoid the 'Duplicate Entry' crash
        $baseCurrency = Currency::where('company_id', $companyId)
                                ->where('code', $baseCode)
                                ->first();

        if (!$baseCurrency) {
            try {
                $baseCurrency = Currency::create([
                    'company_id' => $companyId,
                    'branch_id' => Auth::user()->branch_id ?? 1,
                    'code' => $baseCode,
                    'name' => 'Zambian Kwacha',
                    'symbol' => 'K',
                    'symbol_native' => 'K',
                    'decimal_digits' => 2,
                    'rounding' => 0,
                    'is_active' => 1,
                    'created_by' => Auth::id()
                ]);
            } catch (\Exception $e) {
                // If it exists globally but not for this company (depending on your index)
                $baseCurrency = Currency::where('code', $baseCode)->first();
            }
        }

        // 2. Fetch from API
        $response = Http::get("https://v6.exchangerate-api.com/v6/{$apiKey}/latest/{$baseCode}");

        if ($response->successful()) {
            $data = $response->json();
            $apiRates = $data['conversion_rates'];

            // Priority Currencies to pull into your system automatically
            $priorityCurrencies = ['USD', 'GBP', 'EUR', 'ZAR', 'CNY', 'INR', 'BWP', 'MWK', 'TZS'];

            $count = 0;
            DB::beginTransaction();
            try {
                foreach ($apiRates as $code => $rate) {
                    $existsInDb = Currency::where('company_id', $companyId)->where('code', $code)->first();
                    
                    if ($existsInDb || in_array($code, $priorityCurrencies)) {
                        
                        // Ensure the target currency exists
                        if (!$existsInDb) {
                            $existsInDb = Currency::create([
                                'company_id' => $companyId,
                                'branch_id' => Auth::user()->branch_id ?? 1,
                                'code' => $code,
                                'name' => $this->getCurrencyName($code),
                                'symbol' => $code,
                                'symbol_native' => $code,
                                'decimal_digits' => 2,
                                'rounding' => 0,
                                'is_active' => 1,
                                'created_by' => Auth::id()
                            ]);
                        }

                        // 3. ENTER THE RATES
                        // This part was likely skipped due to the previous error
                        CurrencyRate::updateOrCreate(
                            [
                                'company_id'         => $companyId,
                                'base_currency_id'   => $baseCurrency->id,
                                'target_currency_id' => $existsInDb->id,
                                'rate_date'          => now()->format('Y-m-d'),
                            ],
                            [
                                'branch_id'  => Auth::user()->branch_id ?? 1,
                                'rate'       => $rate,
                                'created_by' => Auth::id(),
                            ]
                        );
                        $count++;
                    }
                }
                DB::commit();
                return redirect()->route('currency-rates.index')->with('success', "Success: {$count} currencies synced and rates updated.");
            } catch (\Exception $e) {
                DB::rollBack();
                return redirect()->back()->with('error', 'Error saving rates: ' . $e->getMessage());
            }
        }

        return redirect()->back()->with('error', 'API Connection failed.');
    }

    private function getCurrencyName($code)
    {
        $names = ['USD'=>'US Dollar','GBP'=>'British Pound','EUR'=>'Euro','ZAR'=>'South African Rand','CNY'=>'Chinese Yuan','BWP'=>'Botswana Pula','MWK'=>'Malawian Kwacha','TZS'=>'Tanzanian Shilling'];
        return $names[$code] ?? $code;
    }
}