<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AccountingPeriod;
use App\Models\FiscalYear;
use App\Services\Audit\AuditLogger;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

final class PeriodController extends Controller
{
    public function __construct(private readonly AuditLogger $audit) {}

    public function index(Request $request): View
    {
        abort_unless($request->user()->hasPermission('periods.view'),403);
        $years=FiscalYear::query()->with(['periods.lockedBy'])->where('company_id',$request->user()->company_id)->latest('starts_on')->get();
        return view('admin.periods.index',compact('years'));
    }

    public function lock(Request $request, AccountingPeriod $period): RedirectResponse
    {
        abort_unless($request->user()->hasPermission('periods.manage'),403);
        $this->ensureCompany($request,$period);
        $data=$request->validate(['reason'=>['required','string','max:1000']]);
        if($period->is_locked)return back()->with('warning','The period is already locked.');
        $old=$period->toArray();
        $period->update(['is_locked'=>true,'locked_at'=>now(),'locked_by'=>$request->user()->id,'lock_reason'=>$data['reason']]);
        $this->audit->log('locked','periods',$period,$old,$period->toArray(),$data['reason']);
        return back()->with('success','Accounting period locked.');
    }

    public function reopen(Request $request, AccountingPeriod $period): RedirectResponse
    {
        abort_unless($request->user()->hasPermission('periods.reopen'),403);
        $this->ensureCompany($request,$period);
        $data=$request->validate(['reason'=>['required','string','max:1000']]);
        if(! $period->is_locked)return back()->with('warning','The period is already open.');
        $old=$period->toArray();
        $period->update(['is_locked'=>false,'locked_at'=>null,'locked_by'=>null,'lock_reason'=>'Reopened: '.$data['reason']]);
        $this->audit->log('reopened','periods',$period,$old,$period->toArray(),$data['reason']);
        return back()->with('success','Accounting period reopened with audit record.');
    }

    private function ensureCompany(Request $request, AccountingPeriod $period):void
    {
        abort_unless((int)$period->fiscalYear()->value('company_id')===(int)$request->user()->company_id,404);
    }
}
