<?php

namespace App\Http\Controllers;

use App\Models\CaseReason;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class CaseReasonController extends Controller
{
    public function index()
    {
        $caseReasons = CaseReason::orderBy('reason_name')->paginate(10);
        return view('modules.edit.case-reasons-list', compact('caseReasons'));
    }

    public function create()
    {
        return view('modules.edit.add-case-reasons');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'reason_code' => 'required|string|max:20|unique:case_reasons,reason_code',
            'reason_name' => 'required|string|max:255',
            'reason_description' => 'nullable|string',
        ]);

        // Set default values for removed settings fields
        $validated['status'] = true; // Default to active
        $validated['requires_approval'] = false; // Default to not requiring approval
        $validated['created_by'] = auth()->id();
        $validated['updated_by'] = auth()->id();

        CaseReason::create($validated);

        return redirect()->route('modules.edit.case-reasons.list')->with('success', 'Case reason created successfully.');
    }

    public function show($id)
    {
        $caseReason = CaseReason::findOrFail($id);
        return view('modules.edit.case-reasons-show', compact('caseReason'));
    }

    public function edit($id)
    {
        $caseReason = CaseReason::findOrFail($id);
        return view('modules.edit.edit-case-reasons', compact('caseReason'));
    }

    public function update(Request $request, $id)
    {
        $caseReason = CaseReason::findOrFail($id);

        $validated = $request->validate([
            'reason_code' => ['required', 'string', 'max:20', Rule::unique('case_reasons', 'reason_code')->ignore($caseReason->reason_code, 'reason_code')],
            'reason_name' => 'required|string|max:255',
            'reason_description' => 'nullable|string',
            'status' => 'required|in:0,1',
        ]);

        // Convert string values to boolean
        $validated['status'] = (bool) $validated['status'];
        $validated['updated_by'] = auth()->id();

        $caseReason->update($validated);

        return redirect()->route('modules.edit.case-reasons.list')->with('success', 'Case reason updated successfully.');
    }

    public function destroy($id)
    {
        $caseReason = CaseReason::findOrFail($id);
        $caseReason->delete();

        return redirect()->route('modules.edit.case-reasons.list')->with('success', 'Case reason deleted successfully.');
    }
}
