<?php

namespace App\Http\Controllers;

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



class IncidentInjuryTypeController extends Controller
{

    public function index(Request $request)
    {
        try {
            $userTable = $this->getUserTable();
            $query = IncidentInjuryType::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)
    {
        $incidentInjury =  IncidentInjuryType::find($request->id);
        if (!$incidentInjury) {
            return $this->message('Record not found.', 404);
        };
        $userTable = $this->getUserTable();
        if ($userTable === 'customer' && ($incidentInjury->customer_id !== auth()->id() || $incidentInjury->workspace_id !== auth()->user()->current_workspace_id)) {
            return $this->message('You do not have access to this report.', 403);
        }
        if ($userTable === 'emp' && ($incidentInjury->customer_id !== auth()->user()->customer_id || $incidentInjury->workspace_id !== auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this report.', 403);
        }
        return $this->success($incidentInjury, 'Get Incident Injury Type Successfully');
    }

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

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'status' => 'required|boolean',
            'parent_id' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->message($validator->errors()->first(), 422);
        }
        $validatedData = $validator->validated();
        // Get user type and assign customer & workspace IDs
        $userTable = $this->getUserTable();
        if ($userTable === "customer") {
            $validatedData['customer_id'] = auth()->id();
            $validatedData['workspace_id'] = auth()->user()->current_workspace_id;
        } elseif ($userTable === "emp") {
            $validatedData['customer_id'] = auth()->user()->customer_id;
            $validatedData['workspace_id'] = auth()->user()->workspace_id;
        } else {
            return $this->error('You do not have permission to create this record.', 403);
        }
        // Create Incident Injury Type using ORM
        $incidentInjuryType = IncidentInjuryType::create($validatedData);
        return $this->success($incidentInjuryType, 'Incident Injury Type Saved Successfully');
    }


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