<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\DisciplineRecord;
use App\Models\Employee;

class DisciplineController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('role:super_admin,hr_admin,president,dept_head');
    }

    public function index(Request $request)
    {
        $user  = auth()->user();

        $baseQuery = DisciplineRecord::when(
            $user->isDeptHead(),
            fn($q) => $q->whereHas('employee', fn($e) => $e->where('department_id', $user->department_id))
        );

        $counts = [
            'open'        => (clone $baseQuery)->where('status','open')->count(),
            'in_progress' => (clone $baseQuery)->where('status','in_progress')->count(),
            'resolved'    => (clone $baseQuery)->where('status','resolved')->count(),
            'closed'      => (clone $baseQuery)->where('status','closed')->count(),
        ];

        $query = (clone $baseQuery)->with(['employee.user','employee.department','reportedBy','handledBy']);

        if ($request->status)          $query->where('status', $request->status);
        if ($request->infraction_type) $query->where('infraction_type', $request->infraction_type);
        if ($request->search) {
            $s = $request->search;
            $query->where(fn($q) =>
                $q->where('case_number','like',"%$s%")
                  ->orWhereHas('employee', fn($e) =>
                      $e->where('first_name','like',"%$s%")->orWhere('last_name','like',"%$s%")
                  )
            );
        }

        $records = $query->latest()->paginate(15)->withQueryString();
        return view('discipline.index', compact('records','counts'));
    }

    public function create()
    {
        $employees = Employee::with('user')->where('status','active')->get();
        return view('discipline.create', compact('employees'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'employee_id'     => 'required|exists:employees,id',
            'infraction_type' => 'required|string',
            'incident_date'   => 'required|date',
            'description'     => 'required|string',
        ]);

        $record = DisciplineRecord::create(array_merge(
            $request->except(['_token']),
            ['reported_by' => auth()->id(), 'status' => 'open']
        ));

        return redirect()->route('discipline.show', $record)
            ->with('success', "Discipline case {$record->case_number} created.");
    }

    public function show(DisciplineRecord $discipline)
    {
        $discipline->load(['employee.user','employee.department','reportedBy','handledBy']);
        return view('discipline.show', compact('discipline'));
    }

    public function edit(DisciplineRecord $discipline)
    {
        $employees = Employee::with('user')->where('status','active')->get();
        return view('discipline.edit', compact('discipline','employees'));
    }

    public function update(Request $request, DisciplineRecord $discipline)
    {
        $discipline->update($request->except(['_token','_method']));
        return redirect()->route('discipline.show', $discipline)->with('success','Record updated.');
    }

    public function takeAction(Request $request, DisciplineRecord $discipline)
    {
        $request->validate([
            'action_taken'   => 'required|string',
            'action_details' => 'required|string',
            'action_date'    => 'required|date',
        ]);

        $discipline->update([
            'action_taken'    => $request->action_taken,
            'action_details'  => $request->action_details,
            'action_date'     => $request->action_date,
            'suspension_days' => $request->suspension_days,
            'handled_by'      => auth()->id(),
            'status'          => 'resolved',
        ]);

        if ($request->action_taken === 'suspension')  $discipline->employee->update(['status' => 'suspended']);
        if ($request->action_taken === 'termination') $discipline->employee->update(['status' => 'terminated']);

        return back()->with('success','Disciplinary action recorded.');
    }

    public function close(DisciplineRecord $discipline)
    {
        $discipline->update(['status' => 'closed']);
        return back()->with('success','Case closed.');
    }
}
