<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\FinancialYear;
use Illuminate\Support\Facades\Auth;

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

    public function index()
    {
        $companyId = $this->getCompanyId();
        $financialYears = FinancialYear::where('company_id', $companyId)
            ->orderBy('start_date', 'desc')
            ->get();

        $activeYear = FinancialYear::where('company_id', $companyId)
            ->where('is_active', true)
            ->first();

        return view('financial-years.index', compact('financialYears', 'activeYear'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'year'       => 'required|string|max:50',
            'start_date' => 'required|date',
            'end_date'   => 'required|date|after:start_date',
            'is_active'  => 'boolean',
        ]);

        if ($request->boolean('is_active')) {
            FinancialYear::where('company_id', $this->getCompanyId())->update(['is_active' => false]);
        }

        FinancialYear::create([
            'company_id' => $this->getCompanyId(),
            'year'       => $validated['year'],
            'start_date' => $validated['start_date'],
            'end_date'   => $validated['end_date'],
            'is_active'  => $request->boolean('is_active'),
            'is_closed'  => false,
            'created_by' => Auth::id(),
            'updated_by' => Auth::id(),
        ]);

        return redirect()->route('financial-years.index')->with('success', 'Financial year created.');
    }

    public function update(Request $request, $id)
    {
        $financialYear = FinancialYear::where('company_id', $this->getCompanyId())->findOrFail($id);

        $validated = $request->validate([
            'year'       => 'required|string|max:50',
            'start_date' => 'required|date',
            'end_date'   => 'required|date|after:start_date',
            'is_active'  => 'boolean',
        ]);

        if ($request->boolean('is_active')) {
            FinancialYear::where('company_id', $this->getCompanyId())
                ->where('id', '!=', $id)
                ->update(['is_active' => false]);
        }

        $financialYear->update(array_merge($validated, ['updated_by' => Auth::id()]));

        return redirect()->route('financial-years.index')->with('success', 'Financial year updated.');
    }

    // ==========================================
    // THE MISSING METHOD THAT CAUSED YOUR ERROR
    // ==========================================
    public function showClose($id)
    {
        $financialYear = FinancialYear::where('company_id', $this->getCompanyId())->findOrFail($id);
        
        if ($financialYear->is_closed) {
            return redirect()->route('financial-years.index')->with('error', 'This year is already closed.');
        }

        return view('financial-years.close', compact('financialYear'));
    }

    public function close(Request $request, $id)
    {
        $financialYear = FinancialYear::where('company_id', $this->getCompanyId())->findOrFail($id);
        
        $request->validate(['confirmation' => 'required|in:CLOSE_YEAR']);

        $financialYear->update([
            'is_closed'  => true,
            'is_active'  => false,
            'updated_by' => Auth::id(),
        ]);

        return redirect()->route('financial-years.index')->with('success', 'Financial year closed.');
    }

    public function reopen($id)
    {
        $financialYear = FinancialYear::where('company_id', $this->getCompanyId())->findOrFail($id);
        
        $financialYear->update([
            'is_closed'  => false,
            'updated_by' => Auth::id(),
        ]);

        return redirect()->route('financial-years.index')->with('success', 'Financial year reopened.');
    }

    public function destroy($id)
    {
        $financialYear = FinancialYear::where('company_id', $this->getCompanyId())->findOrFail($id);
        
        if ($financialYear->is_active) {
            return redirect()->back()->with('error', 'Cannot delete an active year.');
        }

        $financialYear->delete();
        return redirect()->route('financial-years.index')->with('success', 'Financial year deleted.');
    }
}