<?php

namespace App\Http\Controllers;

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



class NotifiableClassificationController extends Controller
{

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


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



  
    public function update(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);
        };
        $incidentNotifiClassification = IncidentNotifiableClassification::find($request->id);
        if (!$incidentNotifiClassification) {
            return $this->message('Record not found.', 404);
        };
        $userTable = $this->getUserTable();
        if ($userTable === 'customer' && ($incidentNotifiClassification->customer_id !== auth()->id() || $incidentNotifiClassification->workspace_id !== auth()->user()->current_workspace_id)) {
            return $this->message('You do not have access to this report.', 403);
        }
        if ($userTable === 'emp' && ($incidentNotifiClassification->customer_id !== auth()->user()->customer_id || $incidentNotifiClassification->workspace_id !== auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this report.', 403);
        }
        $incidentNotifiClassification->update($request->only(['title', 'description', 'status', 'parent_id']));
        if (!$incidentNotifiClassification) {
            return $this->error('Failed to update Incident Notifiable Classificatio');
        }
        return $this->success($incidentNotifiClassification, 'Incident Notifiable 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);
        }
        $validatedData = $validator->validated();
        $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);
        }
        $incidentNotifiClassification = IncidentNotifiableClassification::create($validatedData);
        if(!$incidentNotifiClassification){
            return $this->error('Failed to save Incident Notifiable Classification.');
        }
        return $this->success($incidentNotifiClassification, 'Incident Notifiable Classification Saved Successfully');
    }

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

}
