<?php

namespace App\Http\Controllers;

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


class IncidentInjuryClassificationController extends Controller
{

    public function index(Request $request)
    {
        try {
            $userTable = $this->getUserTable();
            $query = IncidentInjuryClassification::where('del', '0');
            if ($userTable === 'customer') {
                $query->where('customer_id', auth()->user()->id)
                    ->where('workspace_id', auth()->user()->current_workspace_id);
            } elseif ($userTable === 'emp') {
                $query->where('customer_id', auth()->user()->customer_id)
                    ->where('workspace_id', auth()->user()->workspace_id);
            } else {
                return $this->error('You do not have permission to access these records.', 403);
            }
            if($request->filled('pagination') || !empty($request->filters)){
                $query = $this->searchFilterRecord( $query, $request);
            }else{
                $query = $query->orderBy('id', 'desc')->get();
            }
            return $this->success($query, 'Retrieved Successfully');
        } catch (\Exception $e) {
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }


    public function show(Request $request)
    {
        $incidentInjuryClassification =  IncidentInjuryClassification::find($request->id);
        if (!$incidentInjuryClassification) {
            return $this->message('Record not found.', 404);
        };
        $userTable = $this->getUserTable();
        if ($userTable === 'customer' && ($incidentInjuryClassification->customer_id !== auth()->id() || $incidentInjuryClassification->workspace_id !== auth()->user()->current_workspace_id)) {
            return $this->message('You do not have access to this report.', 403);
        }
        if ($userTable === 'emp' && ($incidentInjuryClassification->customer_id !== auth()->user()->customer_id || $incidentInjuryClassification->workspace_id !== auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this report.', 403);
        }
        return $this->success($incidentInjuryClassification, 'Get Incident Injury Classification Successfully');
    }



    public function update(Request $request,)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required|exists:incident_injury_classifications,id',
            'title' => 'required',
            'description' => 'nullable',
            'status' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->message($validator->errors()->first(), 422);
        }
        $incidentInjuryClassification = IncidentInjuryClassification::find($request->id);
        if (!$incidentInjuryClassification) {
            return $this->message('Record not found.', 404);
        };
        $userTable = $this->getUserTable();
        if ($userTable === 'customer' && ($incidentInjuryClassification->customer_id !== auth()->id() || $incidentInjuryClassification->workspace_id !== auth()->user()->current_workspace_id)) {
            return $this->message('You do not have access to this report.', 403);
        }
        if ($userTable === 'emp' && ($incidentInjuryClassification->customer_id !== auth()->user()->customer_id || $incidentInjuryClassification->workspace_id !== auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this report.', 403);
        }
        $incidentInjuryClassification->update($request->only(['title', 'description', 'status']));
        if(!$incidentInjuryClassification){
            return $this->error('Failed to update Incident Injury Classification');
        }
        return $this->success($incidentInjuryClassification , 'Incident Injury Classification Updated Successfully');
    }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'status' => 'required|boolean'
        ]);
        if ($validator->fails()) {
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $userTable = $this->getUserTable(); // Get the user type (customer or emp)
            if ($userTable == "customer") {
                $customerId = auth()->id();
                $workspaceId = auth()->user()->current_workspace_id;
            } elseif ($userTable == "emp") {
                $customerId = auth()->user()->customer_id;
                $workspaceId = auth()->user()->workspace_id;
            }
            // 🔹 Store the Incident Injury Classification
            $incidentInjuryClassification = IncidentInjuryClassification::create([
                'title' => $request->title,
                'description' => $request->description,
                'status' => $request->status,
                'customer_id' => $customerId,   // 🔹 Save Customer ID
                'workspace_id' => $workspaceId  // 🔹 Save Workspace ID
            ]);
            if (!$incidentInjuryClassification) {
                return $this->error('Failed to save Incident Injury Classification');
            }
            return $this->success($incidentInjuryClassification, 'Incident Injury Type Saved Successfully');
        } catch (\Exception $e) {
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }


    public function destroy($id)
    {
        $incidentInjuryClassification = IncidentInjuryClassification::find($id);
        if (!$incidentInjuryClassification) {
            return $this->message('Record not found.', 404);
        }
        // 🔹 Check Access Control
        if($incidentInjuryClassification->del == 1){
            return $this->message('Record is already deleted.', 403);
        };
        $userTable = $this->getUserTable();
        if (
            ($userTable === 'customer' && ($incidentInjuryClassification->customer_id !== auth()->id() || $incidentInjuryClassification->workspace_id !== auth()->user()->current_workspace_id)) ||
            ($userTable === 'emp' && ($incidentInjuryClassification->customer_id !== auth()->user()->customer_id || $incidentInjuryClassification->workspace_id !== auth()->user()->workspace_id))
        ) {
            return $this->message('You do not have access to delete this record.', 403);
        }
        // 🔹 Soft delete the record
        $incidentInjuryClassification->del = 1;
        $incidentInjuryClassification->save();
        if(!$incidentInjuryClassification){
            return $this->error('Failed to delete Incident Injury Classification');
        }
        return $this->message('Incident Injury Classification Deleted Successfully');
     
    }
    
}
