<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\Role;
use App\Models\Swms;
use App\Models\WhsItem;
use App\Models\WhsImages;
use App\Models\WhsReport;
use Illuminate\Http\Request;
use App\Models\WhsReportItem;
use App\Models\WhsSignature;
use App\Models\WhsConductedBy;
use App\Models\WhsResponsible;
use App\Models\WhsReportHazards;
use App\Models\EmpCompanyDetails;
use App\Models\GeneratedPdfReport;
use App\Models\WhsAdditionalPerson;
use Carbon\Carbon;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Validator;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Models\Sites;




class WhsStepsController extends Controller
{
    public function whsStep1Store(Request $request)
    {
        $isUpdate = $request->whs_report_id;
        // Validation rules
        $rules = [
            'document_title' => 'required|string',
            'document_number' => 'nullable|string',
            'authorised_by' => 'required|integer',
            'revision_date' => 'nullable|date|after_or_equal:issue_date',
            // 'role_id' => 'nullable|string|max:20',
            // 'priority' => 'nullable|string|max:255',
            'site_id' => 'required',
        ];
        $rules['issue_date'] = $isUpdate != 0 ? 'nullable|date' : 'nullable|date|after_or_equal:today';
        // Validation
        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 1 error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        $message = $isUpdate ? 'Updated Successfully' : 'Saved Successfully';
        $userTable = $this->getUserTable();
        if ($userTable == "customer") {
            $customer_id = auth()->id();
            $workspace_id = auth()->user()->current_workspace_id;
        } elseif ($userTable == "emp") {
            $customer_id = auth()->user()->customer_id;
            $workspace_id = auth()->user()->workspace_id;
        }
        $revisionNumber = null;
        if($request->whs_report_id == 0) {
            $revisionNumber =$this->generateRevisionNumber()['revision_number'];
        }
        if($request->whs_report_id > 0) {
            $revisionNumber = WhsReport::where('id', $request->whs_report_id)->value('revision_number');
        }
        try {
            $data = [
                'title' => $validator->validated()['document_title'],
                'number' => $validator->validated()['document_number'],
                'authorised_by' => $validator->validated()['authorised_by'],
                'revision_number' => $revisionNumber,
                'issue_date' => $validator->validated()['issue_date'],
                'revision_date' => $validator->validated()['revision_date'],
                // 'priority' => $validator->validated()['priority'],
                'site_id' => $validator->validated()['site_id'],
                'created_by' => auth()->user()->id,
                'customer_id' => $customer_id,
                'workspace_id' => $workspace_id,
            ];
            // Create or update the report
            $whs = WhsReport::updateOrCreate(
                ['id' => $request->whs_report_id],
                $data
            );
            $whs_id = $whs->id;
            // Handle roles
            if ($request->role_id) {
                WhsResponsible::where('whs_report_id', $whs_id)->delete();
                $role_ids = explode(',', $request->role_id);
                foreach ($role_ids as $id) {
                    WhsResponsible::firstOrCreate([
                        'whs_report_id' => $whs_id,
                        'role_id' => $id,
                    ]);
                }
            }
            $data['whs_report_id'] = $whs_id;
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 1 ' . $message,
                'report_id' => $whs_id,
                'report_type' => 'whs_report',
            ];
            storeReportsLogs($log);
            return $this->success($data, $message);
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Report Step 1 error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred while saving data' . $e->getMessage(), 500);
        }
    }

    public function whsStep1Edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 1 edit validation error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            // Get user type and find the WHS report
            $userTable = $this->getUserTable();
            $whsReport = WhsReport::where('id', $request->whs_report_id)->with('siteData')->first();
            if ($whsReport) {
                if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                    return $this->message('You do not have access to this report.', 403);
                }
                if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                    return $this->message('You do not have access to this report.', 403);
                }
            }
            // Customer and Employee Access Check
            $data = $whsReport;
            if ($whsReport) {
                $selectedRoleIds = WhsResponsible::where('whs_report_id', $request->whs_report_id)->pluck('role_id');
                if ($selectedRoleIds) {
                    $data['Whs_responsible'] = Role::whereIn('id', $selectedRoleIds)->pluck('id');
                }
            }
            $data['whs_report_id'] = $request->whs_report_id;
            return $this->success($data, 'Record retrieved successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Report Step 1 error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while retrieving data: ' . $e->getMessage());
        }
    }

    public function whsStep2Store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
            'project_id' => 'nullable|integer',
            'date' => 'nullable|date',
            'start_time' => 'nullable|string',
            'end_time' => 'nullable|string',
            'swms_id' => 'nullable|integer',
            'location' => 'nullable|string|max:255',
            'activities' => 'nullable|string',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 2 validation error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        // Check customer and employee access
        $userTable = $this->getUserTable();
        $whsReport = WhsReport::find($request->whs_report_id);
        if (!$whsReport) {
            return $this->message('WHS report not found.', 404);
        }
        if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
            return $this->message('You do not have access to this report.', 403);
        }
        if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
            return $this->message('You do not have access to this report.', 403);
        }
        $start_time = $request->start_time ? date('H:i:s', strtotime($request->start_time)) : null;
        $end_time = $request->end_time ? date('H:i:s', strtotime($request->end_time)) : null;
        // Prepare the data for storage
        $data = [
            'id' => $request->whs_report_id,
            'project_id' => $request->project_id,
            'date' => $request->date,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'swms_id' => $request->swms_id,
            'location' => $request->location,
            'activities' => $request->activities,
        ];
        try {
            // Update or create the WHS meta data
            $whs = WhsReport::updateOrCreate(
                ['id' => $request->whs_report_id],
                $data
            );
            if ($request->additional_attending_inspections_id) {
                WhsAdditionalPerson::where('whs_report_id', $whs->id)->delete();
                $additional_attending_inspections_ids = explode(",", $request->additional_attending_inspections_id);

                foreach ($additional_attending_inspections_ids as $id) {
                    WhsAdditionalPerson::create([
                        'whs_report_id' => $whs->id,
                        'employee_id' => $id,
                    ]);
                }
            }
            if ($request->conducted_by) {
                WhsConductedBy::where('whs_report_id', $whs->id)->delete();
                $conducted_bys = explode(",", $request->conducted_by);

                foreach ($conducted_bys as $id) {
                    WhsConductedBy::create([
                        'whs_report_id' => $whs->id,
                        'employee_id' => $id,
                    ]);
                }
            }
            $data['whs_report_id'] = $request->whs_report_id;
            $message = $request->whs_report_id ? 'Updated Successfully' : 'Saved Successfully';
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 2 ' . $message,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report'
            ];
            storeReportsLogs($log);
            return $this->success($data, $message);
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 2 error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred while saving the data.');
        }
    }

    public function whsStep2Edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 2 edit validation error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            // Get user type and fetch the WHS report
            $userTable = $this->getUserTable();
            if ($userTable === "customer") {
                $auth_id = Auth::user()->id;
                $workspace_id = Auth::user()->current_workspace_id;
            }
            if ($userTable === "emp") {
                $auth_id = auth()->user()->customer_id;
                $workspace_id = auth()->user()->workspace_id;
            }
            $whsReport = WhsReport::where('id', $request->whs_report_id)->first();
            if (!$whsReport) {
                return $this->message('WHS report not found.', 404);
            }
            // Customer and Employee Access Check
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            $data = $whsReport;
            // Fetch additional persons
            $WhsAdditionalPersonIds = WhsAdditionalPerson::where('whs_report_id', $request->whs_report_id)->pluck('employee_id');
            $data['Whs_additional_person'] = EmpCompanyDetails::whereIn('id', $WhsAdditionalPersonIds)->pluck('id');
            // Fetch conducted by
            $WhsConductedByIds = WhsConductedBy::where('whs_report_id', $request->whs_report_id)->pluck('employee_id');
            $data['Whs_conducted_by'] = EmpCompanyDetails::whereIn('id', $WhsConductedByIds)->pluck('id');
            $data['swms'] = Swms::all()->where('customer_id', $auth_id)->where('workspace_id', $workspace_id);
            $data['whs_report_id'] = $request->whs_report_id;
            return $this->success($data, 'Record retrieved successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 2 error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while retrieving data: ' . $e->getMessage(), 500);
        }
    }

    public function whsStep3Store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
            'results' => 'nullable|array',
            'results.*.id' => 'nullable|integer',
            'results.*.response' => 'nullable|string|in:0,1,2', // Only allow valid ENUM values
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 3 store validation error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            // Fetch WHS report and add customer/employee access check
            $userTable = $this->getUserTable();
            $whsReport = WhsReport::where('id', $request->whs_report_id)->first();
            if (!$whsReport) {
                return $this->message('WHS report not found.', 404);
            }
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            // Process the results array
            $results = $request->input('results');
            foreach ($results as $res) {
                WhsReportItem::updateOrCreate(
                    [
                        'whs_report_id' => $request->whs_report_id, // Matching condition (unique fields)
                        'whs_items_id' => $res['id'],              // Matching condition (unique fields)
                    ],
                    [
                        'values' => $res['response'],              // Ensure valid ENUM value
                    ]
                );
            }
            $message = $request->whs_report_id ? 'Updated Successfully' : 'Saved Successfully';
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 3: ' . $message,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
            ]);
            return $this->success([
                'whs_report_id' => $request->whs_report_id,
                'results' => $results
            ], $message);
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 3 error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while processing the data.', 500);
        }
    }

    public function whsStep3Edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 3 edit validation error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            // Get WHS report and check customer/employee access
            $userTable = $this->getUserTable();
            $auth_id = null;
            $workspace_id = null;
            $whsReport = WhsReport::where('id', $request->whs_report_id)->first();
            if (!$whsReport) {
                return $this->message('WHS report not found.', 404);
            }
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                $auth_id = Auth::user()->id;
                $workspace_id = Auth::user()->current_workspace_id;
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                $auth_id = auth()->user()->customer_id;
                $workspace_id = auth()->user()->workspace_id;
                return $this->message('You do not have access to this report.', 403);
            }
            // Fetch WHS report items and map them properly
            $whsReportItems = WhsReportItem::where('whs_report_id', $request->whs_report_id)
                ->get()
                ->keyBy('whs_items_id')
                ->map(function ($item) {
                    return $item->values; // Only return 'values' field
                });
            // Fetch WHS items that are active (status = 1)
            $data = [
                'whs_items' => WhsItem::where('status', '1')->get(),
                'whs_report_items' => $whsReportItems,
            ];
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 3 data retrieved successfully.',
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
            ]);
            return $this->success($data, 'Record retrieved successfully.');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 3 error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while fetching the data.' . $e->getMessage(), 500);
        }
    }

    public function whsStep4Store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
            "sign_off" => 'nullable|array',
            "sign_off.*.emp_id" => 'nullable|integer',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 4 store validation error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        $validatedData = $validator->validated();
        try {
            // Fetch WHS report and add customer/employee access check
            $userTable = $this->getUserTable();
            $whsReport = WhsReport::where('id', $request->whs_report_id)->first();
            if (!$whsReport) {
                return $this->message('WHS report not found.', 404);
            }
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            // Get Input Data
            $whs_report_id = $request->whs_report_id;
            $whsReport->general_notes = $request->input('general_notes', '');
            $whsReport->status = '1';
            $whsReport->save();
            $column_role_ids = $request->input('column_role_id', []);
            $levels = $request->input('column_level', []);
            $hazards = $request->input('column_hazard', []);
            $actions_required = $request->input('column_action_required', []);
            $levels_of_action = $request->input('column_level_of_action', []);
            $dates_completed = $request->input('column_date_completed', []);
            $whsReportIds = $request->input('column_whs_hazard_report_id', []);
            foreach ($column_role_ids as $index => $responsiblePersonId) {
                $level = $levels[$index] ?? null;
                $hazard = $hazards[$index] ?? null;
                $action_required = $actions_required[$index] ?? null;
                $level_of_action = $levels_of_action[$index] ?? null;
                $date_completed = $dates_completed[$index] ?? null;
                $whsReportId = $whsReportIds[$index] ?? null;
                if ($whsReportId) {
                    // Update existing record
                    WhsReportHazards::updateOrCreate(
                        ['id' => $whsReportId, 'whs_report_id' => $whs_report_id],
                        [
                            'role_id' => $responsiblePersonId,
                            'level' => $level,
                            'hazard' => $hazard,
                            'action_required' => $action_required,
                            'level_of_action' => $level_of_action,
                            'date_completed' => $date_completed,
                        ]
                    );
                } else {
                    // Create a new record
                    WhsReportHazards::create([
                        'whs_report_id' => $whs_report_id,
                        'role_id' => $responsiblePersonId,
                        'level' => $level,
                        'hazard' => $hazard,
                        'action_required' => $action_required,
                        'level_of_action' => $level_of_action,
                        'date_completed' => $date_completed,
                    ]);
                }
            }
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 4: Saved Successfully',
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
            ]);
            if (isset($validatedData['sign_off'])) {
                // Get current employee IDs from the request
                $currentEmployeeIds = collect($validatedData['sign_off'])
                    ->pluck('emp_id')
                    ->filter(function($empId) {
                        return !empty($empId);
                    })
                    ->toArray();

                // Get existing employee IDs for this WHS report
                $existingEmployeeIds = DB::table('whs_signatures')
                    ->where('whs_id', $validatedData['whs_report_id'])
                    ->pluck('employee_id')
                    ->toArray();

                // Find employee IDs that need to be removed (exist in database but not in current request)
                $employeesToRemove = array_diff($existingEmployeeIds, $currentEmployeeIds);

                // Delete records for employees that are no longer in the sign-off list
                if (!empty($employeesToRemove)) {
                    DB::table('whs_signatures')
                        ->where('whs_id', $validatedData['whs_report_id'])
                        ->whereIn('employee_id', $employeesToRemove)
                        ->delete();
                }

                // Process current sign-off employees
                foreach ($validatedData['sign_off'] as $whs_signoff) {
                    if (empty($whs_signoff['emp_id']) || empty($validatedData['whs_report_id'])) {
                        // Skip this record if emp_id or whs_report_id is missing
                        continue;
                    }
                    $whs_signoff['whs_report_id'] = $validatedData['whs_report_id'];
                    $whs_signoff['emp_id'] = $whs_signoff['emp_id'] ?? 0;

                    // Use direct DB query to avoid model casting issues
                    $existingRecord = DB::table('whs_signatures')
                        ->where('whs_id', $validatedData['whs_report_id'])
                        ->where('employee_id', $whs_signoff['emp_id'])
                        ->first();

                    if ($existingRecord) {
                        // Update existing record
                        DB::table('whs_signatures')
                            ->where('whs_id', $validatedData['whs_report_id'])
                            ->where('employee_id', $whs_signoff['emp_id'])
                            ->update([
                                'inductance_date' => now()->format('Y-m-d'),  // Store as Y-m-d string only
                                'updated_at' => now(),
                            ]);
                    } else {
                        // Create new record
                        DB::table('whs_signatures')->insert([
                            'whs_id' => $validatedData['whs_report_id'],
                            'employee_id' => $whs_signoff['emp_id'],
                            'inductance_date' => now()->format('Y-m-d'),  // Store as Y-m-d string only
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                    }
                }
            }
            return $this->success($whs_report_id, 'Saved Successfully');
        } catch (\Throwable $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 4 error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while saving WHS data.', 500);
        }
    }

    public function whsStep4Edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 4 edit validation error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            // Fetch WHS report and add customer/employee access check
            $userTable = $this->getUserTable();
            if ($userTable === "customer") {
                $auth_id = Auth::user()->id;
                $workspace_id = Auth::user()->current_workspace_id;
            }
            if ($userTable === "emp") {
                $auth_id = auth()->user()->customer_id;
                $workspace_id = auth()->user()->workspace_id;
            }
            $whsReport = WhsReport::where('id', $request->whs_report_id)->first();
            if (!$whsReport) {
                return $this->message('WHS report not found.', 404);
            }
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            $WhsReportHazards = WhsReportHazards::where('whs_report_id', $request->whs_report_id)->get();
            $general_notes = $whsReport->general_notes;
            
            // Fetch signature data
            $whsSignatures = DB::table('whs_signatures')
                ->where('whs_id', $request->whs_report_id)
                ->pluck('employee_id')
                ->toArray();
            
            // Fetch Data
            $data = [
                'WhsReportHazards'=> $WhsReportHazards,
                'general_notes' => $general_notes,
                'whs_report_id' => $request->whs_report_id,
                'sign_off' => $whsSignatures,
            ];
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Record retrieved successfully',
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
            ]);
            return $this->success($data, 'Record retrieved successfully.');
        } catch (\Throwable $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 4 error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while retrieving WHS data.', 500);
        }
    }

    public function whsPlanSettingRoleList()
    {
        try {
            $userTable = $this->getUserTable();

            if ($userTable === "customer") {
                $auth_id = Auth::user()->id;
                $workspace_id = Auth::user()->current_workspace_id;
            }
            if ($userTable === "emp") {
                $auth_id = auth()->user()->customer_id;
                $workspace_id = auth()->user()->workspace_id;
            }
            $role = Role::where('del', 0)->get();
            $data['role'] = $role;
            if ($role->isEmpty()) {
                return $this->message('No Role found please create.', 404);
            }
            return $this->success($data, 'Records get successfully');
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }

    public function whsStep3HazardsDelete($id)
    {
        $whsReportHazards = WhsReportHazards::find($id);
        if (!$whsReportHazards) {
            return $this->error('Hazard not found.', 404);
        }
        $whsReport = WhsReport::find($whsReportHazards->whs_report_id);
        if (!$whsReport) {
            return $this->error('Associated WHS report not found.', 404);
        }
        $userTable = $this->getUserTable();
        // Customer and Employee Access Check
        if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
            return $this->error('You do not have access to delete this hazard.', 403);
        }
        if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
            return $this->error('You do not have access to delete this hazard.', 403);
        }
        $whsReportHazards->delete();
        return $this->message('Hazard deleted successfully.');
    }

    public function whsStep5Store(Request $request)
    {
        // Validate request
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
            'general_notes' => 'nullable|string|max:255',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 5 Store Validation Error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error($validator->errors()->first(), 422);
        }
        try {
            // Fetch WHS report and check authorization
            $userTable = $this->getUserTable();
            $whsReport = WhsReport::where('id', $request->whs_report_id)->first();
            if (!$whsReport) {
                return $this->error('WHS report not found.', 404);
            }
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->error('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->error('You do not have access to this report.', 403);
            }
            // Update or create WHS record
            $whs = WhsReport::updateOrCreate(
                ['id' => $request->whs_report_id],
                ['general_notes' => $request->general_notes]
            );
            // Log success
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 5 Saved Successfully',
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report'
            ]);
            return $this->success($whs, 'Saved Successfully');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 5 error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while saving WHS data.', 500);
        }
    }

    public function whsStep5Edit(Request $request)
    {
        // Validate request
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 5 Edit Validation Error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error($validator->errors()->first(), 422);
        }
        try {
            // Fetch WHS report and check authorization
            $userTable = $this->getUserTable();
            $whsReport = WhsReport::where('id', $request->whs_report_id)->first();
            if (!$whsReport) {
                return $this->error('WHS report not found.', 404);
            }
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->error('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->error('You do not have access to this report.', 403);
            }
            $data = $whsReport;
            $data['whs_report_id'] = $request->whs_report_id;
            // Log success
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 5 Record Retrieved Successfully',
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report'
            ]);
            return $this->success($data, 'Record retrieved successfully');
        } catch (\Throwable $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 5 error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while retrieving WHS data.', 500);
        }
    }

    public function whsReportListData(Request $request)
    {
        try {
            $auth_id = auth()->user()->id;
            $userTable = $this->getUserTable();
            $query = WhsReport::query()
                ->orderBy('id', 'DESC')
                ->where('del', '0')
                ->with('authorizedBy');
            if ($userTable === 'customer') {
                $query->where('customer_id', $auth_id)
                    ->where('workspace_id', auth()->user()->current_workspace_id);
            } elseif ($userTable === 'emp') {
                $sites = Sites::where('customer_id', auth()->user()->customer_id)
                    ->where('workspace_id', auth()->user()->workspace_id)
                    ->where('sso_id', $auth_id)
                    ->where('active',1)
                    ->where('del',0)
                    ->pluck('id');
                $query->where('customer_id', auth()->user()->customer_id)
                    ->where('workspace_id', auth()->user()->workspace_id)
                    ->whereIn('site_id', $sites);
            } else {
                return $this->error('You do not have permission to access these reports.', 403);
            }

            // Apply single search filter
            if ($request->has('search') && !empty($request->search)) {
                $searchTerm = $request->search;
                $query->where(function ($q) use ($searchTerm) {
                    $q->where('title', 'like', '%' . $searchTerm . '%')
                      ->orWhere('number', 'like', '%' . $searchTerm . '%')
                      ->orWhereHas('authorizedBy', function ($subquery) use ($searchTerm) {
                        $subquery->where(function ($nameQuery) use ($searchTerm) {
                            $nameQuery->where('first_name', 'like', '%' . $searchTerm . '%')
                                      ->orWhere('middle_name', 'like', '%' . $searchTerm . '%')
                                      ->orWhere('last_name', 'like', '%' . $searchTerm . '%');
                        });
                    });
                });
              
            }
            
            $query_result = $query->get();
            foreach ($query_result as $report) {
                $generatedReport = GeneratedPdfReport::where([
                    ['report_type', 'whs_report'],
                    ['report_id', $report->id]
                ])->first();

                $report->generated_report_url = $generatedReport ? $generatedReport->path : null;
            }
            return $this->success($query_result, 'WHS Reports List Retrieved Successfully');
        } catch (\Throwable $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            return $this->error('An error occurred while retrieving WHS reports.', 500);
        }
    }



    public function destroy($id)
    {
        try {
            $auth_id = auth()->user()->id;
            $userTable = $this->getUserTable();
            // Find the WHS report
            $whsReport = WhsReport::find($id);
            if (!$whsReport) {
                return $this->error('WHS Report not found.', 404);
            }
            if ($whsReport->del == 1) {
                return $this->error('You cannot delete this report because it has been deleted.', 403);
            }
            // Customer & Employee Access Check
            if ($userTable === 'customer') {
                if ($whsReport->customer_id !== $auth_id || $whsReport->workspace_id !== auth()->user()->current_workspace_id) {
                    return $this->error('You do not have permission to delete this report.', 403);
                }
            } elseif ($userTable === 'emp') {
                if ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id) {
                    return $this->error('You do not have permission to delete this report.', 403);
                }
            }
            // Log the deletion
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Report Deleted',
                'report_id' => $id,
                'report_type' => 'whs_report'
            ]);
            // Soft delete the WHS report
            $whsReport->del = 1;
            $whsReport->save();
            return $this->message('WHS Report Deleted Successfully');
        } catch (\Throwable $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Report Delete Error: ' . $shortMessage,
                'report_id' => $id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred while deleting the WHS report.', 500);
        }
    }

    private function generateRevisionNumber($whsParentReportId = null)
    {
        if (!$whsParentReportId) {
            return [
                'revision_number' => 'R1',
            ];
        }
        $parentReport = WhsReport::find($whsParentReportId);
        if (!$parentReport) {
            return [
                'revision_number' => 'R1',
            ];
        }
        $number = $parentReport->number;
        $latest = WhsReport::where('number', $number)
        ->orderByRaw("CAST(SUBSTRING(revision_number, 2) AS UNSIGNED) DESC")
        ->first();
        if ($latest && $latest->revision_number) {
            $currentRevision = (int)substr($latest->revision_number, 1); // Remove "R"
            $nextRevision = 'R' . ($currentRevision + 1);
        } else {
            $nextRevision = 'R1';
        }
        return [
            'revision_number' => $nextRevision,
        ];
    }

    public function whsReportDuplicate($old_report_id)
    {
        $wmpsReport = WhsReport::find($old_report_id);
        if (!$wmpsReport) {
            return $this->error('WHS Report not found', 404);
        }
        $customerId = null;
        $workspaceId = null;
        $userTable = $this->getUserTable();
        if ($userTable === 'customer' && ($wmpsReport->customer_id !== auth()->id() || $wmpsReport->workspace_id !== auth()->user()->current_workspace_id)) {
            $customerId = auth()->id();
            $workspaceId = auth()->user()->current_workspace_id;
            return $this->error('You do not have access to this report', 403);
        }
        if ($userTable === 'emp' && ($wmpsReport->customer_id !== auth()->user()->customer_id || $wmpsReport->workspace_id !== auth()->user()->workspace_id)) {
            $customerId = auth()->user()->customer_id;
            $workspaceId = auth()->user()->workspace_id;
            return $this->error('You do not have access to this report', 403);
        }
        try {
            $revisionNumberAndVersionNumber = $this->generateRevisionNumber($old_report_id);
            $newReport = $wmpsReport->replicate()->fill([
                'revision_number'  => $revisionNumberAndVersionNumber['revision_number'],
                'is_published'        => '0', // Use 0 or 'no' based on DB column type
                'created_at'       => now(),
                'updated_at'       => now(),
            ]);
            // Set customer and workspace IDs if needed
            if (!is_null($customerId)) {
                $newReport->customer_id = $customerId;
            }
            if (!is_null($workspaceId)) {
                $newReport->workspace_id = $workspaceId;
            }
            $newReport->save();
            $new_report_id = $newReport->id;
            // Retrieve existing records
            $Whs_responsible_step1 = WhsResponsible::where('whs_report_id', $old_report_id)->get();
            $Whs_additional_person_step2 = WhsAdditionalPerson::where('whs_report_id', $old_report_id)->get();
            $Whs_conducted_by_step2 = WhsConductedBy::where('whs_report_id', $old_report_id)->get();
            $whs_report_item_step3 = WhsReportItem::where('whs_report_id', $old_report_id)->get();
            $Whs_report_hazards_step4 = WhsReportHazards::where('whs_report_id', $old_report_id)->get();
            // Duplicate records with new swms_id
            $this->duplicateRecords($Whs_responsible_step1, $new_report_id);
            $this->duplicateRecords($Whs_additional_person_step2, $new_report_id);
            $this->duplicateRecords($Whs_conducted_by_step2, $new_report_id);
            $this->duplicateRecords($whs_report_item_step3, $new_report_id);
            $this->duplicateRecords($Whs_report_hazards_step4, $new_report_id);
            $newReport->approval_status = 0;
            $newReport->save();
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Report ID' . $old_report_id . ' duplicated successfully',
                'report_id' =>  $new_report_id,
                'report_type' => 'whs_report'
            ];
            storeReportsLogs($log);
            return $this->success([
                'new_report_id' => $new_report_id,
                'old_report_id' => $old_report_id,
            ], 'Report duplicated successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Report duplicated error:' . $shortMessage,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred while duplicating the report: ' . $shortMessage, 500);
        }
    }

    private function duplicateRecords($records, $new_report_id)
    {
        foreach ($records as $record) {
            $recordClone = $record->replicate();
            $recordClone->whs_report_id = $new_report_id;
            $recordClone->save();
        }
    }
    // need to confirm this method use or not
    public function whsReportPdfFilesManager(Request $request)
    {
        $userTable = $this->getUserTable();
        $query = GeneratedPdfReport::where('report_type', 'whs_report');
        if (!$query) {
            return $this->message('No records found.', 404);
        }
        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->message('You do not have permission to access these records.', 403);
        }
        $pdfReports = $query->get();
        if ($pdfReports->isEmpty()) {
            return $this->message('No records found.', 404);
        }
        $reportIds = $pdfReports->pluck('report_id')->toArray();
        $whsReports = WhsReport::whereIn('id', $reportIds)
            ->select('id', 'title')
            ->get()
            ->keyBy('id');
        $pdfReports->transform(function ($report) use ($whsReports) {
            $report->title = $whsReports->get($report->report_id)->title ?? 'N/A';
            return $report;
        });
        return $this->withCount($pdfReports, 'Retrieve all records Successfully');
    }
    // need to confirm this method logic also
    public function fileManagerDownloadWhsPdfFile($id, $filename)
    {
        // Validate request parameters
        if (!$id || !$filename) {
            return $this->error('Report ID and filename are required.', 422);
        }
        try {
            // Ensure the filename has a .pdf extension
            if (!Str::endsWith(strtolower($filename), '.pdf')) {
                $filename .= '.pdf';
            }
            // Check if the report exists and add customer/employee validation
            $userTable = $this->getUserTable();
            $whsReport = WhsReport::find($id);
            if (!$whsReport) {
                return $this->error('WHS report not found.', 404);
            }
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->error('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->error('You do not have access to this report.', 403);
            }
            // Set file path
            $path = public_path("WHSReportPdf/{$filename}");
            // Check if file exists
            if (!file_exists($path)) {
                $cacheKey = 'whs_report_log_' . auth()->user()->id . '_' . $id;
                if (!cache()->has($cacheKey)) {
                    storeReportsLogs([
                        'employee_id' => auth()->user()->id,
                        'message' => 'WHS File not found',
                        'report_id' => $id,
                        'report_type' => 'whs_report'
                    ]);
                    cache()->put($cacheKey, true, now()->addSeconds(15));
                }
                return $this->error('WHS file not found.', 404);
            }
            // Log the download event if not already logged recently
            $cacheKey = 'whs_report_log_' . auth()->user()->id . '_' . $id;
            if (!cache()->has($cacheKey)) {
                storeReportsLogs([
                    'employee_id' => auth()->user()->id,
                    'message' => 'WHS File Successfully Downloaded',
                    'report_id' => $id,
                    'report_type' => 'whs_report'
                ]);
                cache()->put($cacheKey, true, now()->addSeconds(15));
            }
            // Generate a public URL for the file
            $downloadUrl = url("WHSReportPdf/{$filename}");
            return $this->success($downloadUrl, 'WHS file download URL generated successfully.');
        } catch (\Throwable $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS File download error: ' . $shortMessage,
                'report_id' => $id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred while processing the file download.');
        }
    }

    public function imageStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
            'description' => 'nullable|string',
            'image' => 'required|mimes:jpeg,png,jpg,gif,svg|max:10240',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Image Upload Validation Error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error($validator->errors()->first(), 422);
        }
        // Fetch WHS report and add customer/employee access check
        $userTable = $this->getUserTable();
        $whsReport = WhsReport::find($request->whs_report_id);
        if (!$whsReport) {
            return $this->error('WHS report not found.', 404);
        }
        if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
            return $this->error('You do not have access to this report.', 403);
        }
        if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
            return $this->error('You do not have access to this report.', 403);
        }
        try {
            // Check and upload the image
            if ($request->hasFile('image') && $request->file('image')->isValid()) {
                $imagePath = $this->handleFileImageUpload($request, 'WHSReportImages')['path'] ?? null;
                $image = new WhsImages();
                $image->image = $imagePath;
                $image->whs_report_id = $request->whs_report_id;
                $image->description = $request->description ?? '';
                $image->save();
                $images = WhsImages::where('whs_report_id', $request->whs_report_id)->get();
                return $this->success($images, 'Image uploaded successfully');
            }
            return $this->error('Invalid or no image uploaded.', 400);
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Image Upload Error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while uploading the image.', 500);
        }
    }

    public function getImages(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Image Fetch Validation Error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error($validator->errors()->first(), 422);
        }
        try {
            // Fetch WHS report and add customer/employee access check
            $userTable = $this->getUserTable();
            $whsReport = WhsReport::find($request->whs_report_id);
            if (!$whsReport) {
                return $this->error('WHS report not found.', 404);
            }
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->error('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->error('You do not have access to this report.', 403);
            }
            $images = WhsImages::where('whs_report_id', $request->whs_report_id)->get();

            return $this->success($images, 'Images retrieved successfully.');
        } catch (\Throwable $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Image Fetch Error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while fetching images.', 500);
        }
    }

    public function deleteImage($id)
    {
        try {
            // Find the image by ID
            $image = WhsImages::find($id);
            if (!$image) {
                return $this->error('Image not found.', 404);
            }
            // Fetch WHS report associated with the image
            $whsReport = WhsReport::find($image->whs_report_id);
            if (!$whsReport) {
                return $this->error('Associated WHS report not found.', 404);
            }
            // Customer and Employee Access Check
            $userTable = $this->getUserTable();
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->error('You do not have access to this image.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->error('You do not have access to this image.', 403);
            }
            // Delete the image file from storage
            $imagePath = public_path($image->image);
            if (file_exists($imagePath)) {
                unlink($imagePath); // Delete the file
            }
            // Delete the image record from the database
            $image->delete();
            // Log the deletion
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Report Image Deleted',
                'report_id' => $whsReport->id,
                'report_type' => 'whs_report',
            ]);
            // Return success response
            return $this->message('Image deleted successfully.');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Report Image Deletion Error: ' . $shortMessage,
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while deleting the image.', 500);
        }
    }

    public function whsStep6Store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 6 Store Validation Error: ' . $validator->errors()->first(),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            // Fetch WHS report and check access
            $userTable = $this->getUserTable();
            $whsReport = WhsReport::where('id', $request->whs_report_id)->first();
            if (!$whsReport) {
                return $this->error('WHS report not found.', 404);
            }
            if ($userTable === 'customer' && ($whsReport->customer_id !== auth()->id() || $whsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->error('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($whsReport->customer_id !== auth()->user()->customer_id || $whsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->error('You do not have access to this report.', 403);
            }
            // Update or create the WHS report
            $data = ['status' => 1];
            $whs = WhsReport::updateOrCreate(['id' => $request->whs_report_id], $data);
            // Log the action
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 6: ' . ($request->whs_report_id ? 'Updated Successfully' : 'Saved Successfully'),
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
            ]);
            return $this->success($whs, $request->whs_report_id ? 'Updated Successfully' : 'Saved Successfully');
        } catch (\Throwable $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS Step 6 Error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred while saving data.', 500);
        }
    }
    public function whsQuickEntryStore(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'document_title' => 'required|string|max:255',
                'document_number' => 'nullable|string|max:255',
                'authorised_by' => 'required|integer|exists:emp_company_details,id',
                'site_id' => 'required|integer|exists:sites,id',
                'issue_date' => 'nullable|date',
                'revision_date' => 'nullable|date',
                'sign_off' => 'nullable|array',
                'sign_off.*.emp_id' => 'required_with:sign_off|integer|exists:emp_company_details,id',
                'file' => 'required|file|max:20480',
            ],
            [
                'file.required' => 'WHS summary PDF is required.',
            ]
        );

        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS quick entry validation error: ' . $validator->errors()->first(),
                'report_id' => 0,
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error($validator->errors()->first(), 422);
        }

        try {
            DB::beginTransaction();
            
            $userTable = $this->getUserTable();
            $authUser = auth()->user();
            $customerId = null;
            $workspaceId = null;
            
            if ($userTable === 'customer') {
                $customerId = $authUser->id;
                $workspaceId = $authUser->current_workspace_id;
            } elseif ($userTable === 'emp') {
                $customerId = $authUser->customer_id;
                $workspaceId = $authUser->workspace_id;
            } else {
                return $this->error('You do not have permission to create this record.', 403);
            }

            $revisionNumber = $this->generateRevisionNumber()['revision_number'];
            
            $start_time = $request->start_time ? date('H:i:s', strtotime($request->start_time)) : null;
            $end_time = $request->end_time ? date('H:i:s', strtotime($request->end_time)) : null;

            $whsReport = WhsReport::create([
                'title' => $validator->validated()['document_title'],
                'number' => $validator->validated()['document_number'],
                'authorised_by' => $validator->validated()['authorised_by'],
                'revision_number' => $revisionNumber,
                'issue_date' => $validator->validated()['issue_date'],
                'revision_date' => $validator->validated()['revision_date'],
                // 'priority' => $validator->validated()['priority'],
                'site_id' => $validator->validated()['site_id'],
                'created_by' => auth()->user()->id,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'report_method' => 1,
                'status' => 1,
            ]);

            // Handle conducted_by (additional persons)
            if ($request->conducted_by) {
                $conductedByIds = explode(',', $request->conducted_by);
                foreach ($conductedByIds as $empId) {
                    if (!empty(trim($empId))) {
                        WhsConductedBy::create([
                            'whs_report_id' => $whsReport->id,
                            'employee_id' => trim($empId),
                        ]);
                    }
                }
            }

            // Handle sign_off entries
            $signOffEntries = collect($request->input('sign_off', []))->filter(function ($entry) {
                return isset($entry['emp_id']) && !empty($entry['emp_id']);
            });

            foreach ($signOffEntries as $entry) {
                DB::table('whs_signatures')->insert([
                    'whs_id' => $whsReport->id,
                    'employee_id' => $entry['emp_id'],
                    'inductance_date' => now()->format('Y-m-d'),
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            // Upload PDF file
            $fileUrl = $this->handleFileImageUpload($request, 'whs_report')['path'] ?? null;

            GeneratedPdfReport::updateOrCreate(
                [
                    'report_id' => $whsReport->id,
                    'report_type' => 'whs_report',
                ],
                [
                    'path' => $fileUrl,
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                ]
            );

            DB::commit();

            storeReportsLogs([
                'employee_id' => $authUser->id,
                'message' => 'WHS quick entry saved successfully.',
                'report_id' => $whsReport->id,
                'report_type' => 'whs_report'
            ]);

            return $this->success([
                'whs_report_id' => $whsReport->id,
                'pdf_url' => $fileUrl,
            ], 'WHS quick entry saved successfully.');
        } catch (Exception $e) {
            DB::rollBack();
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS quick entry error: ' . $shortMessage,
                'report_id' => 0,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $shortMessage, 500);
        }
    }

    public function whsQuickEntryEdit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'whs_report_id' => 'required|integer|exists:whs_reports,id',
        ]);

        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS quick entry edit validation error: ' . $validator->errors()->first(),
                'report_id' => $request->get('whs_report_id', 0),
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error($validator->errors()->first(), 422);
        }

        try {
            $whsReport = WhsReport::with('siteData')->find($request->whs_report_id);
            if (!$whsReport) {
                return $this->error('WHS record not found.', 404);
            }

            $userTable = $this->getUserTable();
            $authUser = auth()->user();
            $customerId = $userTable === 'customer' ? $authUser->id : $authUser->customer_id;
            $workspaceId = $userTable === 'customer' ? $authUser->current_workspace_id : $authUser->workspace_id;

            if ($whsReport->customer_id !== $customerId || $whsReport->workspace_id !== $workspaceId) {
                return $this->error('You do not have access to this report.', 403);
            }

            // Get conducted_by employee IDs
            $conductedByIds = WhsConductedBy::where('whs_report_id', $whsReport->id)
                ->pluck('employee_id')
                ->toArray();

            // Get sign_off entries
            $signOffEntries = DB::table('whs_signatures')
                ->where('whs_id', $whsReport->id)
                ->get()
                ->map(function ($signature) {
                    return [
                        'emp_id' => $signature->employee_id,
                        'inductance_date' => $signature->inductance_date,
                    ];
                })
                ->toArray();

            // Get generated report
            $generatedReport = GeneratedPdfReport::where('report_type', 'whs_report')
                ->where('report_id', $whsReport->id)
                ->first();

            $responseData = [
                'whs_report_id' => $whsReport->id,
                'document_title' => $whsReport->title,
                'document_number' => $whsReport->number,
                'authorised_by' => $whsReport->authorised_by,
                'site_id' => $whsReport->site_id,
                'issue_date' => $whsReport->issue_date,
                'revision_date' => $whsReport->revision_date,
                'pdf_url' => $generatedReport->path ?? null,
                'sign_off' => $signOffEntries,
            ];

            return $this->success($responseData, 'WHS quick entry fetched successfully.');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS quick entry edit error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error',
            ]);
            return $this->error('An error occurred: ' . $shortMessage, 500);
        }
    }

    public function whsQuickEntryUpdate(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'whs_report_id' => 'required|integer|exists:whs_reports,id',
                'document_title' => 'required|string|max:255',
                'document_number' => 'nullable|string|max:255',
                'authorised_by' => 'required|integer|exists:emp_company_details,id',
                'site_id' => 'required|integer|exists:sites,id',
                'issue_date' => 'nullable|date',
                'revision_date' => 'nullable|date',
                'sign_off' => 'nullable|array',
                'sign_off.*.emp_id' => 'required_with:sign_off|integer|exists:emp_company_details,id',
                'file' => 'nullable|file|max:20480',
            ]
        );

        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS quick entry update validation error: ' . $validator->errors()->first(),
                'report_id' => $request->get('whs_report_id', 0),
                'report_type' => 'whs_report',
                'error_type' => 'Validation error',
            ]);
            return $this->error($validator->errors()->first(), 422);
        }

        try {
            DB::beginTransaction();
            
            $whsReport = WhsReport::find($request->whs_report_id);
            if (!$whsReport) {
                return $this->error('WHS record not found.', 404);
            }

            $userTable = $this->getUserTable();
            $authUser = auth()->user();
            $customerId = $userTable === 'customer' ? $authUser->id : $authUser->customer_id;
            $workspaceId = $userTable === 'customer' ? $authUser->current_workspace_id : $authUser->workspace_id;

            if ($whsReport->customer_id !== $customerId || $whsReport->workspace_id !== $workspaceId) {
                return $this->error('You do not have access to this report.', 403);
            }

            $whsReport->update([
                'title' => $request->document_title,
                'number' => $request->document_number,
                'authorised_by' => $request->authorised_by,
                'site_id' => $request->site_id,
                'issue_date' => $request->issue_date,
                'revision_date' => $request->revision_date,
                'report_method' => 1,
                'status' => 1,
            ]);

            // Update conducted_by (additional persons)
            WhsConductedBy::where('whs_report_id', $whsReport->id)->delete();
            if ($request->conducted_by) {
                $conductedByIds = explode(',', $request->conducted_by);
                foreach ($conductedByIds as $empId) {
                    if (!empty(trim($empId))) {
                        WhsConductedBy::create([
                            'whs_report_id' => $whsReport->id,
                            'employee_id' => trim($empId),
                        ]);
                    }
                }
            }

            // Update sign_off entries
            $currentEmployeeIds = collect($request->input('sign_off', []))
                ->pluck('emp_id')
                ->filter(function($empId) {
                    return !empty($empId);
                })
                ->toArray();

            $existingEmployeeIds = DB::table('whs_signatures')
                ->where('whs_id', $whsReport->id)
                ->pluck('employee_id')
                ->toArray();

            $employeesToRemove = array_diff($existingEmployeeIds, $currentEmployeeIds);

            if (!empty($employeesToRemove)) {
                DB::table('whs_signatures')
                    ->where('whs_id', $whsReport->id)
                    ->whereIn('employee_id', $employeesToRemove)
                    ->delete();
            }

            foreach ($request->input('sign_off', []) as $entry) {
                if (empty($entry['emp_id'])) {
                    continue;
                }

                $existingRecord = DB::table('whs_signatures')
                    ->where('whs_id', $whsReport->id)
                    ->where('employee_id', $entry['emp_id'])
                    ->first();

                if ($existingRecord) {
                    DB::table('whs_signatures')
                        ->where('whs_id', $whsReport->id)
                        ->where('employee_id', $entry['emp_id'])
                        ->update([
                            'inductance_date' => now()->format('Y-m-d'),
                            'updated_at' => now(),
                        ]);
                } else {
                    DB::table('whs_signatures')->insert([
                        'whs_id' => $whsReport->id,
                        'employee_id' => $entry['emp_id'],
                        'inductance_date' => now()->format('Y-m-d'),
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }

            // Handle file upload
            $existingFilePath = GeneratedPdfReport::where('report_type', 'whs_report')
                ->where('report_id', $whsReport->id)
                ->value('path');
            
            $fileUrl = $existingFilePath;

            if ($request->hasFile('file')) {
                $uploadResult = $this->handleFileImageUpload($request, 'whs_report', $existingFilePath);
                $fileUrl = $uploadResult['path'] ?? $fileUrl;
            }

            GeneratedPdfReport::updateOrCreate(
                [
                    'report_id' => $whsReport->id,
                    'report_type' => 'whs_report',
                ],
                [
                    'path' => $fileUrl,
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                ]
            );

            DB::commit();

            storeReportsLogs([
                'employee_id' => $authUser->id,
                'message' => 'WHS quick entry updated successfully.',
                'report_id' => $whsReport->id,
                'report_type' => 'whs_report'
            ]);

            return $this->success([
                'whs_report_id' => $whsReport->id,
                'pdf_url' => $fileUrl,
            ], 'WHS quick entry updated successfully.');
        } catch (Exception $e) {
            DB::rollBack();
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'WHS quick entry update error: ' . $shortMessage,
                'report_id' => $request->whs_report_id,
                'report_type' => 'whs_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $shortMessage, 500);
        }
    }
}
