<?php

namespace App\Http\Controllers;

use App\Models\CompActionLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CompActionLogController extends Controller
{
    /**
     * Get all CompActionLog records.
     */
    public function index()
    {
        $logs = CompActionLog::with(['complaint', 'actionUser', 'compAction'])->get();
        return response()->json($logs);
    }

    /**
     * Get a specific CompActionLog record by CA_Sr.
     */
    public function show($id)
    {
        $log = CompActionLog::with(['complaint', 'actionUser', 'compAction'])->find($id);

        if (!$log) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        return response()->json($log);
    }

    /**
     * Create a new CompActionLog record.
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'Cmp_Id' => 'required|integer|exists:complaint_books,Cmp_Id',
            'Act_U_ID' => 'required|integer|exists:users_master,U_Id',
            'CA_ID' => 'required|integer|exists:comp_actions,CA_ID',
            'Ca_Desc' => 'required|string|max:255',
        ]);

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

        $log = CompActionLog::create($validator->validated());

        return response()->json($log, 201);
    }

    /**
     * Update a CompActionLog record by CA_Sr.
     */
    public function update(Request $request, $id)
    {
        $log = CompActionLog::find($id);

        if (!$log) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        $validator = Validator::make($request->all(), [
            'Cmp_Id' => 'nullable|integer|exists:complaint_books,Cmp_Id',
            'Act_U_ID' => 'nullable|integer|exists:users_master,U_Id',
            'CA_ID' => 'nullable|integer|exists:comp_actions,CA_ID',
            'Ca_Desc' => 'nullable|string|max:255',
        ]);

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

        $updateData = array_filter($request->only(['Cmp_Id', 'Act_U_ID', 'CA_ID', 'Ca_Desc']));
        $log->update($updateData);

        return response()->json($log);
    }

    /**
     * Delete a CompActionLog record by CA_Sr.
     */
    public function destroy($id)
    {
        $log = CompActionLog::find($id);

        if (!$log) {
            return response()->json(['message' => 'Record not found'], 404);
        }

        $log->delete();
        return response()->json(['message' => 'Deleted successfully']);
    }
}
