<?php

namespace App\Http\Controllers;

use App\Models\CaseRole;
use Illuminate\Http\Request;

class CaseRoleController extends Controller
{
    public function caseRole()
    {
        return view('modules.edit.case-roles');
    }

    public function caseRoleList()
    {
        $caseRoles = CaseRole::all();
        return view('modules.edit.case-roles-list', compact('caseRoles'));
    }

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

    public function index()
    {
        $caseRoles = CaseRole::all();
        return view('modules.edit.case-roles', compact('caseRoles'));
    }

    public function list()
    {
        $caseRoles = CaseRole::all();
        return view('modules.edit.case-roles-list', compact('caseRoles'));
    }

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

    public function store(Request $request)
    {
        $validated = $request->validate([
            'role_name' => 'required|string|max:50|unique:case_roles,role_name',
            'description' => 'nullable|string',
        ]);

        $validated['is_active'] = true; // Default to active

        CaseRole::create($validated);

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

    public function show($id)
    {
        $caseRole = CaseRole::findOrFail($id);
        return view('modules.edit.case-roles-show', compact('caseRole'));
    }

    public function edit($id)
    {
        $caseRole = CaseRole::findOrFail($id);
        return view('modules.edit.edit-case-roles', compact('caseRole'));
    }

    public function update(Request $request, $id)
    {
        $caseRole = CaseRole::findOrFail($id);

        $validated = $request->validate([
            'role_name' => 'required|string|max:50|unique:case_roles,role_name,' . $caseRole->role_id . ',role_id',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
        ]);

        $caseRole->update($validated);

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

    public function destroy($id)
    {
        $caseRole = CaseRole::findOrFail($id);
        $caseRole->delete();

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