<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\Currency;
use App\Models\FinancialYear;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
use DateTimeZone;
use App\Services\ChartOfAccountsService;
use App\Models\CurrencyRate;

class CompanyController extends Controller
{
    protected $coaService;

    public function __construct(ChartOfAccountsService $coaService)
    {
        $this->coaService = $coaService;
    }

    /**
     * INTERNAL HELPER: Get the current active company for the logged-in user.
     */
    private function getActiveCompany()
    {
        $companyId = Auth::user()->current_company_id ?? Auth::user()->companyid;
        return Company::findOrFail($companyId);
    }

    /**
     * REGISTRATION: Show the business setup form (Step 2).
     */
    public function create(): View
    {
        $timezones = DateTimeZone::listIdentifiers();
        $currencies = $this->getCurrencyList();
        return view('auth.company-setup', compact('timezones', 'currencies'));
    }

    /**
     * REGISTRATION: Store the initial company and setup Chart of Accounts.
     */
    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name'       => ['required', 'string', 'max:255'],
            'email'      => ['nullable', 'email', 'max:255'],
            'phone'      => ['nullable', 'string', 'max:20'],
            'tax_number' => ['nullable', 'string', 'max:50'],
            'currency'   => ['required', 'string', 'size:3'],
            'timezone'   => ['required', 'string', 'in:' . implode(',', DateTimeZone::listIdentifiers())],
            'address'    => ['nullable', 'string', 'max:500'],
        ]);

        $user = Auth::user();

        return DB::transaction(function () use ($user, $data) {
            $company = $user->companies()->create($data);

            // Initialize default accounts for the new business
            $this->coaService->setupDefaultAccounts($company->id, $user->id);

            // Set as active context
            $user->update(['current_company_id' => $company->id]);

            return redirect()->route('dashboard');
        });
    }

    /**
     * PROFILE: Display the company profile/details.
     */
public function show(): View
{
    $companyId = Auth::user()->current_company_id ?? Auth::user()->companyid;
    $company = Company::findOrFail($companyId);

    // Fetch active currencies for the dropdown
    $currencies = Currency::where('company_id', $companyId)
        ->where('is_active', true)
        ->get();

    // Fetch financial years using the uploaded model
    $financialYears = FinancialYear::where('company_id', $companyId)
        ->orderBy('start_date', 'desc')
        ->get();

    // Fetch the latest USD exchange rate for the company
    $usdCurrency = Currency::where('code', 'USD')->first();
    $usdRate = null;
    
    if ($usdCurrency) {
        $usdRate = CurrencyRate::where('company_id', $companyId)
            ->where('target_currency_id', $usdCurrency->id)
            ->orderBy('rate_date', 'desc')
            ->first();
    }

    return view('company.show', compact('company', 'currencies', 'financialYears', 'usdRate'));
}

    /**
     * PROFILE: Update company information from the Profile page.
     */
   public function update(Request $request): RedirectResponse
{
    $company = $this->getActiveCompany();

    $validated = $request->validate([
        'name'       => 'required|string|max:255',
        'email'      => 'nullable|email|max:255',
        'phone'      => 'nullable|string|max:20',
        'tax_number' => 'nullable|string|max:50',
        'address'    => 'nullable|string|max:500',
        'currency'   => 'required|string|size:3', // Reporting Currency
        'timezone'   => 'required|string|in:' . implode(',', DateTimeZone::listIdentifiers()),
        'current_financial_year_id' => 'nullable|exists:financial_years,id',
    ]);

    // Update the company
    $company->update($validated);

    // Logic: If a new financial year was selected, ensure ONLY that one is marked 'is_active'
    if ($request->filled('current_financial_year_id')) {
        // Deactivate all years for this company
        \App\Models\FinancialYear::where('company_id', $company->id)->update(['is_active' => false]);
        
        // Activate the selected one
        \App\Models\FinancialYear::where('id', $request->current_financial_year_id)->update(['is_active' => true]);
    }

    return redirect()->route('company.profile')->with('success', 'Global settings and profile updated successfully.');
}

    /**
     * HELPER: Currency list for the registration drop-down.
     */
    private function getCurrencyList(): array
    {
        return [
            'ZMW' => 'Zambian Kwacha (K)',
            'USD' => 'US Dollar ($)',
            'EUR' => 'Euro (€)',
            'GBP' => 'British Pound (£)',
            'ZAR' => 'South African Rand (R)',
            'BWP' => 'Botswana Pula (P)',
            'INR' => 'Indian Rupee (₹)',
            'CNY' => 'Chinese Yuan (¥)',
            'JPY' => 'Japanese Yen (¥)',
        ];
    }
}