<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\HazardRisk;
use Illuminate\Http\Request;
use App\Models\SwmsQuestions;
use App\Models\SwmsGeneralNote;
use App\Models\SwmsProtectionTool;
use Illuminate\Support\Facades\Validator;
use App\Models\SwmsSafetyPlanningQuestion;
use DB;

class SWMSReportController extends Controller
{

    public function swmsHazardRiskGet(Request $request)
    {
        try {
            $userTable = $this->getUserTable();
            $user = auth()->user();

            if ($userTable === 'customer') {
                $hazardRisk = HazardRisk::where('customer_id', $user->id)
                    ->where('workspace_id', $user->current_workspace_id);
            } elseif ($userTable === 'emp') {
                $hazardRisk = HazardRisk::where('customer_id', $user->customer_id)
                    ->where('workspace_id', $user->workspace_id);
            } else {
                return $this->error('You do not have permission to access this data.', 403);
            }
            if($request->filled('pagination') || !empty($request->filters)){
                $hazardRisk = $this->searchFilterRecord($hazardRisk, $request);
            }else{
                $hazardRisk = $hazardRisk->orderBy('id', 'desc')->get();
            }
            // If no records found
            if ($hazardRisk->isEmpty()) {
                storeReportsLogs([
                    'employee_id' => $user->id,
                    'message' => 'No hazard risks found.',
                    'report_id' => 0,
                    'report_type' => 'swms_report',
                    'error_type' => 'Data not found',
                ]);
                return $this->error('No hazard risks found.', 404);
            }
            return $this->withCount($hazardRisk, 'Data retrieved successfully.');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Hazard risk retrieval error: ' . substr($e->getMessage(), 0, 200),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }

    public function swmsHazardRiskStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'type' => 'required|in:hazard,risk', // Ensure only valid types
            'status' => 'required|in:0,1', // Ensure only valid statuses
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Hazard Risk error: ' . $validator->errors()->first(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error($validator->errors()->first(), 422);
        }
        try {
            $validatedData = $validator->validated();
            $userTable = $this->getUserTable();
            // Set customer_id and workspace_id
            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);
            }
            $hazardRisk = HazardRisk::create($validatedData);
            if (!$hazardRisk) {
                return $this->error('Failed to save Hazard Risk.');
            }
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Hazard risk saved Successfully',
                'report_id' => 0,
                'report_type' => 'swms_report'
            ]);
            return $this->success($hazardRisk, 'Saved Successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Hazard risk store error: ' . substr($e->getMessage(), 0, 200),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }



    public function swmsHazardRiskUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'type' => 'required|in:hazard,risk',
            'status' => 'required|in:0,1',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Hazard Risk Update error: ' . $validator->errors()->first(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error($validator->errors()->first(), 422);
        }
        try {
            $userTable = $this->getUserTable();
            $user = auth()->user();
            $hazardRisk = HazardRisk::find($request->id);
            if (!$hazardRisk) {
                return $this->error('Record not found.', 404);
            }
            if ($userTable === 'customer' && ($hazardRisk->customer_id !== $user->id || $hazardRisk->workspace_id !== $user->current_workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($hazardRisk->customer_id !== $user->customer_id || $hazardRisk->workspace_id !== $user->workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            // Update record
            $hazardRisk->update($validator->validated());
            storeReportsLogs([
                'employee_id' => $user->id,
                'message' => 'Hazard risk updated successfully',
                'report_id' => 0,
                'report_type' => 'swms_report'
            ]);
            return $this->success($hazardRisk, 'Updated Successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Hazard risk update error: ' . substr($e->getMessage(), 0, 200),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage(), 500);
        }
    }
    public function swmsHazardRiskDelete($id)
    {
        try {
            $hazardRisk = HazardRisk::find($id);
            if (!$hazardRisk) {
                $log = [
                    'employee_id' => auth()->user()->id,
                    'message' => 'Hazard risk Item Id not found please refresh and try again.',
                    'report_id' =>  0,
                    'report_type' => 'swms_report',
                    'error_type' => 'Validation error',
                ];
                storeReportsLogs($log);
                return $this->message('Data not found ', 404);
            }
            $userTable = $this->getUserTable();
            $user = auth()->user();
            if ($userTable === 'customer' && ($hazardRisk->customer_id !== $user->id || $hazardRisk->workspace_id !== $user->current_workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($hazardRisk->customer_id !== $user->customer_id || $hazardRisk->workspace_id !== $user->workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            // if ($hazardRisk->status == 0) {
            //     $log = [
            //         'employee_id' => auth()->user()->id,
            //         'message' => 'Hazard risk Item Id not found please refresh and try again.',
            //         'report_id' =>  0,
            //         'report_type' => 'swms_report',
            //         'error_type' => 'Validation error',
            //     ];
            //     storeReportsLogs($log);
            //     return $this->message('Item Id not found please refresh and try again', 422);
            // }
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Hazard Risk Record Deleted Successfully.',
                'report_id' =>  0,
                'report_type' => 'swms_report'
            ];
            $hazardRisk->delete();
            storeReportsLogs($log);
            return $this->message('Deleted Successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Hazard risk delete error:' .   $shortMessage,
                'report_id' =>  0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred : ' . $e->getMessage());
        }
    }
    public function swmsHazardRiskQuestionStore(Request $request)
    {
        // Validate request
        $validator = Validator::make($request->all(), [
            'question' => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'status' => 'required|in:0,1',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Hazard Risk Question error: ' . $validator->errors()->first(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            // Get user table and set customer_id & workspace_id
            $userTable = $this->getUserTable();
            $user = auth()->user();
            if ($userTable === "customer") {
                $customerId = $user->id;
                $workspaceId = $user->current_workspace_id;
            } elseif ($userTable === "emp") {
                $customerId = $user->customer_id;
                $workspaceId = $user->workspace_id;
            } else {
                return $this->error('You do not have permission to create this record.', 403);
            }
            // Create the record
            $swmsQuestion = SwmsQuestions::create([
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'question' => $request->question,
                'description' => $request->description,
                'status' => $request->status,
            ]);
            // Log activity
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Hazard risk question saved successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report',
            ]);
            return $this->success($swmsQuestion, 'Saved Successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Hazard risk store error: ' . $e->getMessage(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }
    public function swmsQuestionGet()
    {
        try {
            $userTable = $this->getUserTable();
            $user = auth()->user();
            if ($userTable === "customer") {
                $questions = SwmsQuestions::where('customer_id', $user->id)
                    ->where('workspace_id', $user->current_workspace_id)
                    ->get();
            } elseif ($userTable === "emp") {
                $questions = SwmsQuestions::where('customer_id', $user->customer_id)
                    ->where('workspace_id', $user->workspace_id)
                    ->get();
            } else {
                return $this->error('You do not have permission to access these records.', 403);
            }
            if ($questions->isEmpty()) {
                storeReportsLogs([
                    'employee_id' => $user->id,
                    'message' => 'SWMS Question retrieval failed. No records found.',
                    'report_id' => 0,
                    'report_type' => 'swms_report',
                    'error_type' => 'Validation error',
                ]);
                return $this->message('No records found.', 404);
            }
            return $this->withCount($questions, 'Retrieved successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Question retrieval error: ' . $e->getMessage(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }

    public function swmsQuestionUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'question' => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'status' => 'required|in:0,1',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Question update error: ' . $validator->errors()->first(),
                'report_id' => null,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $userTable = $this->getUserTable();
            $user = auth()->user();
            $question = SwmsQuestions::find($request->id);
            if (!$question) {
                return $this->message('Record not found.', 404);
            }
            if (
                ($userTable === "customer" && ($question->customer_id !== $user->id || $question->workspace_id !== $user->current_workspace_id)) ||
                ($userTable === "emp" && ($question->customer_id !== $user->customer_id || $question->workspace_id !== $user->workspace_id))
            ) {
                return $this->error('You do not have permission to update this record.', 403);
            }
            // Update question
            $question->update($request->only(['question', 'description', 'status']));
            storeReportsLogs([
                'employee_id' => $user->id,
                'message' => 'SWMS Question updated successfully',
                'report_id' => 0,
                'report_type' => 'swms_report'
            ]);

            return $this->success($question, 'Updated Successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Question update error: ' . $e->getMessage(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }

    public function swmsQuestionDelete($id)
    {
        try {
            $userTable = $this->getUserTable();
            $user = auth()->user();
            $question = SwmsQuestions::find($id);
            if (!$question) {
                return $this->message('No record found to be deleted.', 404);
            }
            if (
                ($userTable === "customer" && ($question->customer_id !== $user->id || $question->workspace_id !== $user->current_workspace_id)) ||
                ($userTable === "emp" && ($question->customer_id !== $user->customer_id || $question->workspace_id !== $user->workspace_id))
            ) {
                return $this->error('You do not have permission to delete this record.', 403);
            }
            $question->delete();
            storeReportsLogs([
                'employee_id' => $user->id,
                'message' => 'SWMS Question deleted successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report'
            ]);
            return $this->message('Deleted Successfully.');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Question delete error: ' . $e->getMessage(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }

    public function swmsSafetyPlanningQuestionStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'question' => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'type' => 'required|in:hazard,risk',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Safety Planning error: ' . $validator->errors()->first(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $userTable = $this->getUserTable();
            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;
            } else {
                return $this->error('You do not have permission to create this record.', 403);
            }
            $validatedData = $validator->validated();
            $validatedData['customer_id'] = $customerId;
            $validatedData['workspace_id'] = $workspaceId;
            $swmsQuestion = SwmsSafetyPlanningQuestion::create($validatedData);
            if (!$swmsQuestion) {
                return $this->error('Failed to save. Please try again.', 500);
            }
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Safety Planning Question stored successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report',
            ];
            storeReportsLogs($log);
            return $this->success($swmsQuestion, 'Saved successfully.');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Safety Planning store error: ' . $shortMessage,
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error',
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $e->getMessage(), 500);
        }
    }
    public function swmsSafetyPlanningQuestionGet(Request $request)
    {
        try {
            $userTable = $this->getUserTable();
            $user = auth()->user();
            if ($userTable === "customer") {
                $swmsSafetyPlanningQuestions = SwmsSafetyPlanningQuestion::where('customer_id', $user->id)
                    ->where('workspace_id', $user->current_workspace_id);
            } elseif ($userTable === "emp") {
                $swmsSafetyPlanningQuestions = SwmsSafetyPlanningQuestion::where('customer_id', $user->customer_id)
                    ->where('workspace_id', $user->workspace_id);
            } else {
                return $this->error('You do not have permission to access these records.', 403);
            }
            if($request->filled('pagination') || !empty($request->filters)){
                $swmsSafetyPlanningQuestions = $this->searchFilterRecord($swmsSafetyPlanningQuestions, $request);
            }else{
                $swmsSafetyPlanningQuestions = $swmsSafetyPlanningQuestions->orderBy('id', 'desc')->get();
            }
            if ($swmsSafetyPlanningQuestions->isEmpty()) {
                return $this->error('No records found.', 404);
            }
            return $this->withCount($swmsSafetyPlanningQuestions, 'Retrieved successfully.');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Safety Planning question get error: ' . $shortMessage,
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $e->getMessage(), 500);
        }
    }

    public function swmsSafetyPlanningQuestionUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'question' => 'required|string|max:255',
            'description' => 'nullable|string|max:255',
            'type' => 'required',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Safety Planning Question update error: ' . $validator->errors()->first(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error'
            ];
            storeReportsLogs($log);
            return $this->error($validator->errors()->first(), 422);
        }
        try {
            $swmsSafetyPlanningQuestions = SwmsSafetyPlanningQuestion::find($request->id);
            if (!$swmsSafetyPlanningQuestions) {
                return $this->error('Record not found.', 404);
            }
            $userTable = $this->getUserTable();
            $user = auth()->user();
            if (
                ($userTable === "customer" && ($swmsSafetyPlanningQuestions->customer_id !== $user->id || $swmsSafetyPlanningQuestions->workspace_id !== $user->current_workspace_id)) ||
                ($userTable === "emp" && ($swmsSafetyPlanningQuestions->customer_id !== $user->customer_id || $swmsSafetyPlanningQuestions->workspace_id !== $user->workspace_id))
            ) {
                return $this->error('You do not have permission to update this record.', 403);
            }
            // Update the record
            $swmsSafetyPlanningQuestions->update($request->only(['question', 'description', 'type']));
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Safety Planning Question ID ' . $request->id . ' updated successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return $this->success($swmsSafetyPlanningQuestions, 'Updated Successfully.');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Safety Planning Question update error: ' . $shortMessage,
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $e->getMessage(), 500);
        }
    }

    public function swmsSafetyPlanningQuestionDelete($id)
    {

        try {
            // Fetch the record
            $question = SwmsSafetyPlanningQuestion::find($id);
            if (!$question) {
                return $this->error('No record found to be deleted.', 404);
            }
            $userTable = $this->getUserTable();
            $user = auth()->user();
            if (
                ($userTable === "customer" && ($question->customer_id !== $user->id || $question->workspace_id !== $user->current_workspace_id)) ||
                ($userTable === "emp" && ($question->customer_id !== $user->customer_id || $question->workspace_id !== $user->workspace_id))
            ) {
                return $this->error('You do not have permission to delete this record.', 403);
            }
            // Delete the record
            $question->delete();
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Safety Planning Question ID ' . $id . ' deleted successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return $this->message('Deleted Successfully.');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Safety Planning Question delete error: ' . $shortMessage,
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $e->getMessage(), 500);
        }
    }
    // General NOtes
    public function swmsGeneralNotesStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'type' => 'required',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS General Notes error: ' . $validator->errors()->first(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error'
            ]);
            return $this->error($validator->errors()->first(), 422);
        }
        try {
            $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);
            }
            $generalNote = SwmsGeneralNote::create($validatedData);
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS General Notes Saved Successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report'
            ]);
            return $this->success($generalNote, 'Saved Successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS General Notes store error: ' . substr($e->getMessage(), 0, 200),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage(), 500);
        }
    }

    public function swmsGeneralNotesGet(Request $request)
    {
        try {
            $userTable = $this->getUserTable();
            $query = SwmsGeneralNote::query();
            // Apply Customer & Employee Access Check
            if ($userTable === "customer") {
                $query->where('customer_id', auth()->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)){
                $generalNotes = $this->searchFilterRecord($query, $request);
            }else{
                $generalNotes = $query->orderBy('id', 'desc')->get();
            }
            if ($generalNotes->isEmpty()) {
                storeReportsLogs([
                    'employee_id' => auth()->user()->id,
                    'message' => 'SWMS General Notes retrieval failed. No records found.',
                    'report_id' => 0,
                    'report_type' => 'swms_report',
                    'error_type' => 'Data Not Found'
                ]);
                return $this->error('No records found.', 404);
            }
            return $this->withCount($generalNotes, 'Retrieved Successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS General Notes get error: ' . substr($e->getMessage(), 0, 200),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage(), 500);
        }
    }

    public function swmsGeneralNotesUpdate(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required|string|max:255',
            'description' => 'nullable|string',
            'type' => 'required',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS General Notes update error: ' . $validator->errors()->first(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error($validator->errors()->first(), 422);
        }
        try {
            $userTable = $this->getUserTable();
            $generalNote = SwmsGeneralNote::find($request->id);
            if (!$generalNote) {
                return $this->error('Record not found.', 404);
            }
            $user = auth()->user();
            if (
                ($userTable === "customer" && ($generalNote->customer_id !== $user->id || $generalNote->workspace_id !== $user->current_workspace_id)) ||
                ($userTable === "emp" && ($generalNote->customer_id !== $user->customer_id || $generalNote->workspace_id !== $user->workspace_id))
            ) {
                return $this->error('You do not have permission to update this record.', 403);
            }
            if (!$generalNote) {
                return $this->error('Record not found.', 404);
            }
            $generalNote->update([
                'title' => $request->input('title'),
                'description' => $request->input('description'),
                'type' => $request->input('type'),
            ]);
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS General Notes ID ' . $request->id . ' updated successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report'
            ]);
            return $this->success($generalNote, 'Updated Successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS General Notes update error: ' . substr($e->getMessage(), 0, 200),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage(), 500);
        }
    }
    public function swmsGeneralNotesDelete($id)
    {
        try {
            $userTable = $this->getUserTable();
            $generalNote = SwmsGeneralNote::find($id);
            if (!$generalNote) {
                return $this->error('Record not found.', 404);
            }
            $user = auth()->user();
            if (
                ($userTable === "customer" && ($generalNote->customer_id !== $user->id || $generalNote->workspace_id !== $user->current_workspace_id)) ||
                ($userTable === "emp" && ($generalNote->customer_id !== $user->customer_id || $generalNote->workspace_id !== $user->workspace_id))
            ) {
                return $this->error('You do not have permission to update this record.', 403);
            }
            if (!$generalNote) {
                return $this->error('No record found to be deleted.', 404);
            }
            $generalNote->delete();
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS General Notes ID ' . $id . ' deleted successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report'
            ]);
            return $this->message('Deleted Successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS General Notes delete error: ' . substr($e->getMessage(), 0, 200),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage(), 500);
        }
    }
    public function swmsProtectionToolStore(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'title' => 'required|string|max:255',
                'description' => 'nullable|string|max:255',
                'image' => 'required|image|mimes:png,jpeg,jpg|max:2048', 
            ],
            [
                'image.mimes' => 'Image must be in PNG, JPG, or JPEG format.',
                'image.image' => 'The file must be an image.',
            ]
        );
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Protection Tool error: ' . $validator->errors()->first(),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error( $validator->errors()->first(), 422);
        }
        try {
            $validatedData = $validator->validated();
            // Assign customer_id and workspace_id based on user type
            $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);
            }
            // Handle image upload
            if ($request->hasFile('image')) {
                $validatedData['image'] = $this->handleFileImageUpload($request, 'SWMSReportDocuments')['path'] ?? null;
            }
            // Store record using Eloquent ORM
            $protectionTool = SwmsProtectionTool::create($validatedData);
            if (!$protectionTool) {
                storeReportsLogs([
                    'employee_id' => auth()->user()->id,
                    'message' => 'SWMS Protection Tool failed to save. Please retry.',
                    'report_id' => 0,
                    'report_type' => 'swms_report',
                    'error_type' => 'Database error',
                ]);
                return $this->error('Failed to Save. Please retry.', 422);
            }
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Protection Tool saved successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report',
            ]);
            return $this->success($protectionTool , 'Saved Successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Protection Tool save error: ' . substr($e->getMessage(), 0, 200),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }
    public function swmsProtectionToolGet(Request $request)
    {
        try {
            $userTable = $this->getUserTable();
            $query = SwmsProtectionTool::query();
            if ($userTable === "customer") {
                $query->where('customer_id', auth()->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)){
                $protectionTools = $this->searchFilterRecord($query, $request);
            }else{
                $protectionTools = $query->orderBy('id', 'desc')->get();
            }
            if ($protectionTools->isEmpty()) {
                storeReportsLogs([
                    'employee_id' => auth()->user()->id,
                    'message' => 'SWMS Protection Tool - No records found.',
                    'report_id' => 0,
                    'report_type' => 'swms_report',
                    'error_type' => 'Data retrieval issue',
                ]);
                return $this->error('No records found.', 404);
            }
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Protection Tools retrieved successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report',
            ]);
            return $this->withCount($protectionTools , 'Data retrieved successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Protection Tool retrieval error: ' . substr($e->getMessage(), 0, 200),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }    
    public function swmsProtectionToolUpdate(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'title' => 'required|string|max:255',
                'description' => 'nullable|string|max:255',
                'image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048',
            ],
            [
                'image.*.mimes' => 'Image must be in png, jpg, or jpeg format.',
                'image.*.image' => 'The file must be an image.',
            ]
        );
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Protection tool update ID ' . $request->id . ' error: ' . $validator->errors()->first(),
                'report_id' =>  0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $swmsProtectionTool = SwmsProtectionTool::find($request->id);
            $userTable = $this->getUserTable();
            if ($userTable === "customer" && ($swmsProtectionTool->customer_id !== auth()->id() || $swmsProtectionTool->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->message('You do not have permission to update this record.', 403);
            } elseif ($userTable === "emp" && ($swmsProtectionTool->customer_id !== auth()->user()->customer_id || $swmsProtectionTool->workspace_id !== auth()->user()->workspace_id)) {
                return $this->message('You do not have permission to update this record.', 403);
            }
            $swmsProtectionTool->update([
                'title' => $request->title,
                'description' => $request->description
            ]);
            if ($request->hasFile('image')) {
                $imagePath = $this->handleFileImageUpload($request, 'SWMSReportDocuments', $swmsProtectionTool->image)['path'] ?? null;
                $swmsProtectionTool->image = $imagePath;
                $swmsProtectionTool->save();
            }
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Protection Tool ID ' . $request->id . ' updated successfully.',
                'report_id' => 0,
                'report_type' => 'swms_report',
            ]);
            return $this->success($swmsProtectionTool, 'Updated successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Protection tool update error: ' . substr($e->getMessage(), 0, 200),
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }
    
    public function swmsProtectionToolDelete($id)
    {
        try {
            // Fetch the record
            $swmsProtectionTool = SwmsProtectionTool::find($id);
            if (!$swmsProtectionTool) {
                storeReportsLogs([
                    'employee_id' => auth()->user()->id,
                    'message' => 'SWMS Protection tool ID ' . $id . ' not found.',
                    'report_id' =>  0,
                    'report_type' => 'swms_report',
                    'error_type' => 'Not found error',
                ]);
                return $this->message('Record not found.', 404);
            }
            // User validation for customer & employee
            $userTable = $this->getUserTable();
            if ($userTable === "customer" && ($swmsProtectionTool->customer_id !== auth()->id() || $swmsProtectionTool->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->message('You do not have permission to delete this record.', 403);
            } elseif ($userTable === "emp" && ($swmsProtectionTool->customer_id !== auth()->user()->customer_id || $swmsProtectionTool->workspace_id !== auth()->user()->workspace_id)) {
                return $this->message('You do not have permission to delete this record.', 403);
            }
            // Delete the associated image if it exists
            if ($swmsProtectionTool->image && file_exists(public_path($swmsProtectionTool->image))) {
                unlink(public_path($swmsProtectionTool->image));
            }
            $swmsProtectionTool->delete();
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Protection tool ID ' . $id . ' deleted successfully.',
                'report_id' =>  0,
                'report_type' => 'swms_report',
            ]);
            return $this->message('Deleted successfully');
        } catch (\Exception $e) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Protection tool deletion error: ' . substr($e->getMessage(), 0, 200),
                'report_id' =>  0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred: ' . $e->getMessage());
        }
    }
    
}
