<?php

declare(strict_types=1);

namespace App\Http\Controllers\Barangay;

use App\Enums\UserActions;
use App\Http\Controllers\Helpers\Permissions\UserPermissions;
use App\Http\Controllers\Helpers\ResponseHelper;
use App\Models\Barangay\Blotter;
use App\Models\Barangay\BlotterHearing;
use Hypervel\Http\Request;
use Hypervel\Support\Facades\Auth;
use Hypervel\Support\Facades\Validator;

class BlotterHearingController
{
    private function checkWrite(): bool
    {
        return UserPermissions::isActionPermitted(Auth::user()->acct_type, UserActions::ManageBlotterHearings);
    }

    public function index(Request $request)
    {
        $blotter = Blotter::where('hashkey', $request->input('blotter'))->first();
        if (!$blotter) return ResponseHelper::returnError('Blotter not found', 404);

        $hearings = BlotterHearing::with('officer')
            ->where('blotter_id', $blotter->id)
            ->orderBy('hearing_date')
            ->get();

        return response()->json(['success' => true, 'data' => $hearings]);
    }

    public function schedule(Request $request)
    {
        if (!$this->checkWrite()) return ResponseHelper::returnUnauthorized();

        $validator = Validator::make($request->all(), [
            'blotter'      => 'required|string',
            'hearing_date' => 'required|date',
            'officer_id'   => 'nullable|integer|exists:users,id',
            'notes'        => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        $blotter = Blotter::where('hashkey', $request->input('blotter'))->first();
        if (!$blotter) return ResponseHelper::returnError('Blotter not found', 404);

        $hearing = BlotterHearing::create([
            'blotter_id'   => $blotter->id,
            'hearing_date' => $request->input('hearing_date'),
            'status'       => 'SCHEDULED',
            'officer_id'   => $request->input('officer_id', $blotter->assigned_officer_id),
            'notes'        => $request->input('notes'),
        ]);

        return response()->json(['success' => true, 'data' => $hearing, 'message' => 'Hearing scheduled']);
    }

    public function update(Request $request)
    {
        if (!$this->checkWrite()) return ResponseHelper::returnUnauthorized();

        $hearing = BlotterHearing::find($request->input('hearing_id'));
        if (!$hearing) return ResponseHelper::returnError('Hearing not found', 404);

        $data = $request->only(['status', 'notes', 'resolution', 'next_hearing_date']);
        $hearing->update($data);

        return response()->json(['success' => true, 'data' => $hearing, 'message' => 'Hearing updated']);
    }
}
