<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Hash;
use Auth;
use App\Models\IncidentRiskCategory;
use DB;



class IncidentRiskCategoryController extends Controller
{

    public function index(Request $request)
    {
        try {
            $userTable = $this->getUserTable();
            $query = IncidentRiskCategory::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, 'Get Incident Risk Categorys Successfully');
        } catch (\Exception $e) {
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }

    public function show(Request $request)
    {
        $incidentInjury =  IncidentRiskCategory::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 Risk Category Successfully');
    }

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



    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',
            'description' => 'required',
            'status' => '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);
        }
        $incidentRiskCategory = IncidentRiskCategory::create($validatedData);
        return $this->success($incidentRiskCategory, 'Incident Risk Category Saved Successfully');
    }

    public function destroy($id)
    {
        $incidentInjury = IncidentRiskCategory::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 Risk Category');
        }
        return $this->message('Incident Risk Category Deleted Successfully');
    }
}
