<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\CompanySetting;
use App\Services\Leave\LeaveOpeningBalanceImportService;
use App\Services\Leave\LeaveLedgerService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LeaveLedgerController extends Controller
{
    public function importForm(LeaveLedgerService $ledger)
    {
        $year = $ledger->leaveYear();
        $companyId = (int) Auth::user()?->company_id;
        $allowMonthlyOpeningOverride = $ledger->allowsMonthlyOpeningOverride($companyId);

        return view('leaves.opening-balances-import', compact('year', 'allowMonthlyOpeningOverride'));
    }

    public function importStore(Request $request, LeaveOpeningBalanceImportService $importService, LeaveLedgerService $ledger)
    {
        $companyId = (int) Auth::user()?->company_id;
        abort_unless($companyId > 0, 403);

        $validated = $request->validate([
            'year' => ['required', 'integer', 'min:2000', 'max:2100'],
            'file' => ['required', 'file', 'mimes:csv,txt', 'max:5120'],
        ]);

        $result = $importService->importFromCsv(
            $request->file('file'),
            $companyId,
            (int) $validated['year'],
            Auth::id()
        );

        $message = "Imported {$result['success']} row(s). Failed {$result['failed']} row(s).";

        return redirect()
            ->route('leaves.dashboard')
            ->with($result['failed'] > 0 ? 'warning' : 'success', $message)
            ->with('import_errors', $result['errors']);
    }

    public function downloadTemplate(LeaveOpeningBalanceImportService $importService)
    {
        $headers = $importService->templateHeaders();
        $callback = static function () use ($headers) {
            $out = fopen('php://output', 'w');
            fputcsv($out, $headers);
            fputcsv($out, ['EMP001', 'user@company.com', 'CL', '2']);
            fclose($out);
        };

        return response()->streamDownload($callback, 'leave-opening-balances-template.csv', [
            'Content-Type' => 'text/csv',
        ]);
    }

    public function updatePolicy(Request $request, LeaveLedgerService $ledger)
    {
        $companyId = (int) Auth::user()?->company_id;
        abort_unless($companyId > 0, 403);

        $validated = $request->validate([
            'allow_advance_monthly' => ['nullable', 'boolean'],
            'allow_monthly_opening_override' => ['nullable', 'boolean'],
        ]);

        CompanySetting::withoutGlobalScopes()->updateOrCreate(
            ['company_id' => $companyId, 'key' => LeaveLedgerService::SETTING_ALLOW_ADVANCE_MONTHLY],
            ['value' => ($validated['allow_advance_monthly'] ?? false) ? '1' : '0']
        );

        CompanySetting::withoutGlobalScopes()->updateOrCreate(
            ['company_id' => $companyId, 'key' => LeaveLedgerService::SETTING_ALLOW_MONTHLY_OPENING_OVERRIDE],
            ['value' => ($validated['allow_monthly_opening_override'] ?? false) ? '1' : '0']
        );

        return redirect()->route('leaves.dashboard')->with('success', 'Leave accrual policy updated.');
    }
}
