<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\Swms;
use App\Models\Sites;
use App\Models\SwmsMeta;
use App\Models\SwmsImage;
use App\Models\HazardRisk;
use App\Models\SwmsAwnswers;
use Illuminate\Http\Request;
use App\Models\SwmsQuestions;
use App\Models\SwmsSignature;
use App\Models\SwmsApprovedBy;
use App\Models\SwmsTaskDetail;
use App\Models\swmsDevelopedBy;
use App\Models\SwmsGeneralNote;
use App\Models\EmpCompanyDetails;
use App\Models\GeneratedPdfReport;
use App\Models\SwmsProtectionTool;
use App\Models\Role;
use Illuminate\Support\Facades\DB;
use App\Models\SwmsHazardRiskPivot;
use App\Models\EmpPersonalDetails;
use Illuminate\Pagination\Paginator;
use App\Models\SwmsGeneralNoteAnswers;
use App\Models\SwmsProtectionToolPivot;
use App\Models\SwmsSafetyPlanningAnswers;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Carbon\Carbon;
use InvalidArgumentException;
use App\Models\SwmsSafetyPlanningQuestion;
use Illuminate\Pagination\LengthAwarePaginator;
class SwmsStepsController extends Controller
{

    public function swmsReportListData(Request $request)
    {
        try {
            $auth_id = auth()->user()->id;
            $userTable = $this->getUserTable();
            $query = Swms::query()
                ->orderBy('id', 'DESC')
                ->where('del', '0')
                ->with('authorizedBy');
            if ($userTable === 'customer') {
                // If user is customer, return all their reports based on customer_id and workspace_id
                $query->where('customer_id', $auth_id)
                    ->where('workspace_id', auth()->user()->current_workspace_id);
            } elseif ($userTable === 'emp') {
                // If user is employee, find sites within their customer_id and workspace_id
                $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.', 500);
            }

            // 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('swms_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 . '%');
                          });
                      });
                });
            }
            
            // Get all records without pagination
            $query_result = $query->orderBy('id', 'desc')->get();
            
            foreach ($query_result as $report) {
                $generatedReport = GeneratedPdfReport::where([
                    ['report_type', 'swms_report'],
                    ['report_id', $report->id]
                ])->first();

                $report->generated_report_url = $generatedReport ? $generatedReport->path : null;
            }
            
            $transformed_data = $query_result->map(function ($swms) {
                $swmsData = $swms->toArray();
                $swmsData['authorizedBy'] = [];
                if (!empty($swms->site_manager_or_forman)) {
                    $formanIds = explode(',', $swms->site_manager_or_forman);
                    $employeeDetails = EmpPersonalDetails::whereIn('emp_id', $formanIds)->get();
                    $swmsData['authorizedBy'] = $employeeDetails;
                }
                return $swmsData;
            });
            
           
            
            return $this->withCount($transformed_data, 'Record retrieved successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Report List Failed to get: ' . $shortMessage,
                'report_id' => 0,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred while retrieving SWMS reports.', 500);
        }
    }

    public function swmsReportRecordDelete($id)
    {
        try {
            if (!$id) {
                return response()->json([
                    'message' => 'Report ID is required',
                ], 422);
            }
            Swms::where('id', $id)->update(['del' => '1']);
            GeneratedPdfReport::where('report_id', $id)->delete();
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Repport ID ' . $id . ' Deleted successfully',
                'report_id' =>  0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => 'Deleted successfully',
            ], 200);
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Report delete Failed . Please retry.',
                'report_id' =>  0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => 'An error occurred : ' . $e->getMessage(),
            ], 500);
        }
    }

    private function generateRevisionNumber($swmsParentReportId = null)
    {
        if (!$swmsParentReportId) {
            return [
                'revision_number' => 'R1',
            ];
        }
        $parentReport = Swms::find($swmsParentReportId);
        if (!$parentReport) {
            return [
                'revision_number' => 'R1',
            ];
        }
        $swmsNumber = $parentReport->swms_number;
        $latest = Swms::where('swms_number', $swmsNumber)
            ->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 swmsStep1Store(Request $request)
    {
        $isUpdate = $request->swms_report_id;
        $rules = [
            'title' => 'required|string|max:255',
            'site_manager_or_forman' => 'required|string|max:255',
            'revision_number' => 'nullable|string|max:255', // Optional since it can be auto-generated
            'version_number' => 'nullable|string|max:255',
            'parent_swms_id' => 'nullable|integer', // For revision generation based on parent
            'company_name' => 'nullable|string|max:255',
            'contact_number' => 'nullable|max:20',
            'company_address' => 'nullable|string|max:255',
            'workplace_location_address' => 'nullable|string|max:255',
            'scope_of_work' => 'nullable|string|max:255',
            'fast_address' => 'nullable|string|max:255',
            'principal_contractor' => 'nullable|string|max:255',
            'site_id' => 'required',
            'start_date' => 'nullable|date',
        ];

        $validator = Validator::make($request->all(), $rules);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 1 error: ' . $validator->errors()->first(),
                'report_id' => $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }

        // Determine the appropriate message
        $message = $isUpdate ? 'Updated Successfully' : 'Saved Successfully';

        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);
            }

            // Generate revision number automatically for new reports or when parent_id is provided
            $revisionData = [];
            if (!$isUpdate) {
                // For new reports, start with R1
                $revisionData = $this->generateRevisionNumber();
            } elseif ($request->has('parent_swms_id') && $request->parent_swms_id) {
                // For duplicated reports, generate next revision number based on parent
                $revisionData = $this->generateRevisionNumber($request->parent_swms_id);
            } else {
                // For regular updates, keep existing revision number or use from request
                $revisionData['revision_number'] = $request->revision_number;
            }

            $data = [
                'swms_number' => $request->swms_number,
                'title' => $request->title,
                'site_manager_or_forman' => $request->site_manager_or_forman,
                'revision_number' => $revisionData['revision_number'],
                'version_number' => $request->version_number,
                'start_date' => $request->start_date ?? null,
                'company_name' => $request->company_name,
                'site_id' => $request->site_id,
                'contact_number' => $request->contact_number,
                'company_address' => $request->company_address,
                'scope_of_work' => $request->scope_of_work,
                'fast_address' => $request->fast_address,
                'principal_contractor' => $request->principal_contractor,
                'principal_contractor_address' => $request->principal_contractor_address,
                'principal_contractor_number' => $request->principal_contractor_number,
                'description' => $request->description,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'workplace_location_address' => $request->workplace_location_address,
            ];

            // Check for revision number conflicts
            if ($isUpdate) {
                $already_report = Swms::where('id', $request->swms_report_id)
                    ->where('swms_number', $request->swms_number)
                    ->where('del', 0)
                    ->first();

                if ($already_report && $already_report->revision_number != $request->revision_number) {
                    $already_report_to_swms_number = Swms::where('id', '!=', $request->swms_report_id)
                        ->where('swms_number', $request->swms_number)
                        ->where('revision_number', $request->revision_number)
                        ->where('del', 0)
                        ->first();

                    if ($already_report_to_swms_number) {
                        return $this->message('This revision number for this SWMS number already exists.', 422);
                    }
                }
            }

            // Simple update or create - no duplication logic here
            $swms = Swms::updateOrCreate(
                ['id' => $request->swms_report_id],
                $data
            );
            $data['swms_report_id'] = $swms->id;

            // Handle signature
            $user_site_forman_by = EmpCompanyDetails::with(['EmpPersonalDetails', 'accessRole', 'accessTier'])
                ->find($request->site_manager_or_forman);
            $accessRoleId = $user_site_forman_by->accessRole->id ?? null;

            // SwmsSignature::updateOrCreate(
            //     [
            //         'swms_id' => $data['swms_report_id'],
            //         'tier_id' => $accessRoleId,
            //     ],
            //     [
            //         'swms_id' => $data['swms_report_id'],
            //         'tier_id' => $accessRoleId,
            //     ]
            // );

            // Enhanced logging to track revision number generation
            $logMessage = 'SWMS Step 1 ' . $message;
            if (!$isUpdate) {
                $logMessage .= ' - Auto-generated revision number: ' . $revisionData['revision_number'];
            } elseif ($request->has('parent_swms_id') && $request->parent_swms_id) {
                $logMessage .= ' - Generated revision number from parent ID ' . $request->parent_swms_id . ': ' . $revisionData['revision_number'];
            }

            $log = [
                'employee_id' => auth()->user()->id,
                'message' => $logMessage,
                'report_id' => $data['swms_report_id'],
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);

            // Enhanced response to include generated revision info
            $responseData = $data;
            $responseData['auto_generated_revision'] = !$isUpdate || ($request->has('parent_swms_id') && $request->parent_swms_id);

            return $this->success($responseData, $message);
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Report Step 1 error: ' . $shortMessage,
                'report_id' => $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $shortMessage);
        }
    }

    private function generateRevisionNumberAndVersion($swmsParentReportId = null)
    {
        if (!$swmsParentReportId) {
            return [
                'revision_number' => 'R1',
                'version_number' => 'V1',
            ];
        }
        $parentReport = Swms::find($swmsParentReportId);
        if (!$parentReport) {
            return [
                'revision_number' => 'R1',
                'version_number' => 'V1',
            ];
        }
        $swmsNumber = $parentReport->swms_number;
        $latest = Swms::where('swms_number', $swmsNumber)
            ->orderByRaw("CAST(SUBSTRING(revision_number, 2) AS UNSIGNED) DESC")
            ->first();
        if ($latest && $latest->revision_number) {
            $currentRevision = (int)substr($latest->revision_number, 1); // Remove "R"
            $currentVersion  = (int)substr($latest->version_number, 1);  // Remove "V"
            $nextRevision = 'R' . ($currentRevision + 1);
            $nextVersion  = 'V' . ($currentVersion + 1);
        } else {
            $nextRevision = 'R1';
            $nextVersion  = 'V1';
        }
        return [
            'revision_number' => $nextRevision,
            'version_number' => $nextVersion,
        ];
    }
    // New separate API endpoint for duplicating SWMS reports
    public function duplicateSwmsReport($id)
    {

        try {
            $old_report_id = $id;
            // Check if revision number already exists
            $swmsReport = Swms::find($old_report_id);
            if (!$swmsReport) {
                return $this->message('Original report not found.', 404);
            }
            $userTable = $this->getUserTable();
            $customerId = null;
            $workspaceId = null;
            if ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                $customerId = auth()->id();
                $workspaceId = auth()->user()->current_workspace_id;
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id)) {
                $customerId = auth()->user()->customer_id;
                $workspaceId = auth()->user()->workspace_id;
                return $this->message('You do not have access to this report.', 403);
            }
            $revisionNumberAndVersionNumber = $this->generateRevisionNumberAndVersion($old_report_id);
            $newReport = $swmsReport->replicate()->fill([
                'revision_number'  => $revisionNumberAndVersionNumber['revision_number'],
                'version_number'   => $revisionNumberAndVersionNumber['version_number'],
                'process'          => $swmsReport->process ?? '0',
                '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
            $swms_meta_step2 = SwmsMeta::where('swms_id', $old_report_id)->get();
            $swms_general_notes_step2 = SwmsGeneralNoteAnswers::where('swms_id', $old_report_id)->get();
            $swms_developed_by_step3 = swmsDevelopedBy::where('swms_id', $old_report_id)->get();
            $swms_approved_by_step3 = SwmsApprovedBy::where('swms_id', $old_report_id)->get();
            $swms_task_details_step4 = SwmsTaskDetail::where('swms_id', $old_report_id)->get();
            $swms_hazard_risk_pivot_step5 = SwmsHazardRiskPivot::where('swms_id', $old_report_id)->get();
            $swms_protection_tool_pivot_step5 = SwmsProtectionToolPivot::where('swms_id', $old_report_id)->get();
            $swms_question_answers_step5 = SwmsAwnswers::where('swms_id', $old_report_id)->get();
            $swms_safety_planning = SwmsSafetyPlanningAnswers::where('swms_id', $old_report_id)->get();
            $swms_signatures = SwmsSignature::where('swms_id', $old_report_id)->get();
            // Duplicate records with new swms_id
            $this->duplicateRecords($swms_meta_step2, $new_report_id);
            $this->duplicateRecords($swms_general_notes_step2, $new_report_id);
            $this->duplicateRecords($swms_developed_by_step3, $new_report_id);
            $this->duplicateRecords($swms_approved_by_step3, $new_report_id);
            $this->duplicateRecords($swms_task_details_step4, $new_report_id);
            $this->duplicateRecords($swms_hazard_risk_pivot_step5, $new_report_id);
            $this->duplicateRecords($swms_protection_tool_pivot_step5, $new_report_id);
            $this->duplicateRecords($swms_question_answers_step5, $new_report_id);
            $this->duplicateRecords($swms_signatures, $new_report_id);
            $this->duplicateRecords($swms_safety_planning, $new_report_id);
            $newReport->approval_status = 0;
            $newReport->save();
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Report duplicated successfully from ID ' . $old_report_id . ' to ID ' . $new_report_id,
                'report_id' => $new_report_id,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return $this->success([
                'new_report_id' => $new_report_id,
                'old_report_id' => $old_report_id,
                'revision_number' => $revisionNumberAndVersionNumber['revision_number'],
                'version_number' => $revisionNumberAndVersionNumber['version_number']
            ], 'Report duplicated successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Report duplicate error: ' . $shortMessage,
                'report_id' => $old_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred while duplicating: ' . $shortMessage);
        }
    }

    private function duplicateRecords($records, $new_report_id)
    {
        foreach ($records as $record) {
            $recordClone = $record->replicate();
            $recordClone->swms_id = $new_report_id;
            // Set current timestamps for cloned records
            $recordClone->created_at = now();
            $recordClone->updated_at = now();
            $recordClone->save();
        }
    }


    public function swmsStep1Edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS  Step 1 edit:' . $validator->errors()->first(),
                'report_id' =>   $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            // $swms_number = rand(99999, 999999);
            $swms = Swms::find($request->swms_report_id);
            if (!$swms) {
                return $this->error('SWMS report not found.', 404);
            }
            $userTable = $this->getUserTable();
            if ($userTable === 'customer' && ($swms->customer_id !== auth()->id() || $swms->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($swms->customer_id !== auth()->user()->customer_id || $swms->workspace_id !== auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            // $emp_list = EmpCompanyDetails::where('compeleted', '1')
            // ->where('approved', '1')
            // ->where('status', '1')
            // ->where('del', '0')
            // ->where('customer_id', $swms->customer_id)
            // ->where('workspace_id', $swms->workspace_id)
            // ->with([
            //     'empPersonalDetails' => function ($query) {
            //         $query->select('emp_id', 'first_name', 'middle_name', 'last_name', 'mobile');
            //     },
            //     'accessRole' => function ($query) {
            //         $query->select('id', 'title', 'code');
            //     },
            //     'empTier' => function ($query) {
            //         $query->select('id', 'title');
            //     },
            //     'accessTier' => function ($query) {
            //         $query->select('id', 'title', 'tier_key');
            //     },
            // ])
            // ->select('id', 'access_role', 'tier_id')
            // ->whereIn('tier_id', function ($query) {
            //     $query->select('id')
            //         ->from('tiers')
            //         ->whereIn('tier_key', ['T-1', 'T-2', 'T-3']);
            // })
            // ->get();
            // $data['authorised_by_list'] = $emp_list;
            // $data['swms_report_id'] = $request->swms_report_id;
            // $data['swms_number'] = $swms_number;

            // if ($request->swms_report_id == 0) {
            //     $data['sites'] = DB::table('sites')
            //         ->where('del', '0')
            //         ->where('active', '1')
            //         ->get(['id', 'title']);
            // } else {
            //     $swms = Swms::with('siteData')
            //     ->where('id', $request->swms_report_id)
            //     ->first();
            //     $data['sites'] = DB::table('sites')
            //         ->where(function ($query) use ($swms) {
            //             $query->where('active', '1')
            //                   ->orWhere(function ($subQuery) use ($swms) {
            //                       if ($swms && isset($swms->site_id)) {
            //                           $subQuery->where('id', $swms->site_id)
            //                                    ->where('del', '0'); 
            //                       }
            //                   });
            //         })
            //         ->get(['id', 'title']);
            // }
            // $data['company_name'] = Company::get(['id','fname','mname','lname']);
            return $this->success($swms->load(['siteData', 'authorizedBy']), 'Reocrd get Successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Report Step 1 error:' . $shortMessage,
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred : ' . $shortMessage);
        }
    }

    // Step 2
    public function swmsStep2Store(Request $request)
    {
        $rules = [
            'swms_report_id' => 'required|exists:swms,id',
            'consultation_method' => 'nullable|string|max:255',
            'review_frequency' => 'nullable|string|max:255',
            'worker_consultation' => 'nullable|string|max:255',
            'hsr_consultation' => 'nullable|string|max:255',
            'is_based_on_risk' => 'nullable|string|max:255',
            'received_date' => 'nullable|date',
            'date_received_by_reviewer' => 'nullable|date',
            'person_responsible_for_ensuring_compliance	' => 'nullable',
            'person_responsible_for_reviewing_swms	' => 'nullable'
        ];
        $messages = [
            'received_date.required' => 'Received date is required.',
            'received_date.date' => 'Received date must be a valid date.',
            'date_received_by_reviewer.required' => 'Date received by reviewer is required.',
            'date_received_by_reviewer.date' => 'Date received by reviewer must be a valid date.',
        ];
        // Validate the request
        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 2 error: ' . $validator->errors()->first(),
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        // Check if SWMS report exists
        $swmsReport = SWMS::findOrFail($request->swms_report_id);
        if (!$swmsReport) {
            return $this->error('No matching record found.', 404);
        }
        $userTable = $this->getUserTable();
        $authUser = auth()->user();
        // Store customer_id & workspace_id for reuse
        $customerId = ($userTable === 'customer') ? $authUser->id : $authUser->customer_id;
        $workspaceId = ($userTable === 'customer') ? $authUser->current_workspace_id : $authUser->workspace_id;
        // Access check for both customer and employee
        if (
            ($userTable === 'customer' && ($swmsReport->customer_id !== $customerId || $swmsReport->workspace_id !== $workspaceId)) ||
            ($userTable === 'emp' && ($swmsReport->customer_id !== $customerId || $swmsReport->workspace_id !== $workspaceId))
        ) {
            return $this->message('You do not have access to this report.', 403);
        }
        // Prepare data for storage
        $data = [
            'swms_id' => $request->swms_report_id,
            'consultation_method' => $request->consultation_method,
            'review_frequency' => $request->review_frequency,
            'recieved_date' => $request->received_date,
            'date_recieved_by_reviewer' => $request->date_received_by_reviewer,
            'is_based_on_risk' => $request->is_based_on_risk,
            'is_worker_consulted' => $request->worker_consultation,
            'is_hsr_consulted' => $request->hsr_consultation,
            'person_responsible_for_reviewing_swms' => $request->person_responsible_for_reviewing_swms,
            'person_responsible_for_ensuring_compliance' => $request->person_responsible_for_ensuring_compliance,
        ];
        try {
            // Update or create SWMS metadata
            SwmsMeta::updateOrCreate(['swms_id' => $request->swms_report_id], $data);
            // Handle InputAnswers JSON data
            if ($request->has('InputAnswers')) {
                $inputAnswers = is_array($request->InputAnswers) ? $request->InputAnswers : json_decode($request->input('InputAnswers'), true);
                if (is_array($inputAnswers)) {
                    foreach ($inputAnswers as $noteId => $answer) {
                        // Check if swms_general_notes_id exists before inserting
                        $noteExists = SwmsGeneralNote::where('id', $noteId)->where('customer_id', $customerId)->where('workspace_id', $workspaceId)->exists();
                        if ($noteExists) {
                            SwmsGeneralNoteAnswers::updateOrCreate(
                                ['swms_id' => $request->swms_report_id, 'swms_general_notes_id' => $noteId],
                                ['answer' => $answer]
                            );
                        } else {
                            return $this->error("Invalid swms_general_notes_id: {$noteId}. No matching record found.", 422);
                        }
                    }
                }
            }
            $data['swms_report_id'] = $request->swms_report_id;
            $message = 'Updated Successfully';
            // Store logs
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 2 ' . $message,
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_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' => 'SWMS Step 2 error: ' . $shortMessage,
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $shortMessage);
        }
    }

    public function swmsStep2Edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 2 edit :' . $validator->errors()->first(),
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $swmsReport = SWMS::find($request->swms_report_id);
            if (!$swmsReport) {
                return $this->error('No matching record found.', 404);
            }
            $userTable = $this->getUserTable();
            $authUser = auth()->user();
            // Store customer_id & workspace_id for reuse
            $customerId = ($userTable === 'customer') ? $authUser->id : $authUser->customer_id;
            $workspaceId = ($userTable === 'customer') ? $authUser->current_workspace_id : $authUser->workspace_id;
            // Access check for both customer and employee
            if (
                ($userTable === 'customer' && ($swmsReport->customer_id !== $customerId || $swmsReport->workspace_id !== $workspaceId)) ||
                ($userTable === 'emp' && ($swmsReport->customer_id !== $customerId || $swmsReport->workspace_id !== $workspaceId))
            ) {
                return $this->message('You do not have access to this report.', 403);
            }
            $data['swms_meta'] = SwmsMeta::where('swms_id', $request->swms_report_id)->first();
            $data['GeneralNotes'] = SwmsGeneralNote::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->get();
            $answers = SwmsGeneralNoteAnswers::where('swms_id', $request->swms_report_id)->get()->keyBy('swms_general_notes_id');
            $data['SwmsGeneralNoteAnswers'] = $answers;
            $data['swms_report_id'] = $request->swms_report_id;
            return $this->success($data, 'Reocrd get Successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 2 error:' . $shortMessage,
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred : ' . $shortMessage,);
        }
    }
    public function swmsStep3Store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required|exists:swms,id',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 3 store :' . $validator->errors()->first(),
                'report_id' => $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error'
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        $swms_report_id = $request->swms_report_id;
        $swmsReport = SWMS::find($swms_report_id);
        if (!$swmsReport) {
            return $this->error('No matching record found.', 404);
        }
        // Retrieve customer and workspace IDs
        $userTable = $this->getUserTable();
        $authUser = auth()->user();
        $customerId = ($userTable === 'customer') ? $authUser->id : $authUser->customer_id;
        $workspaceId = ($userTable === 'customer') ? $authUser->current_workspace_id : $authUser->workspace_id;
        // Validate access permissions
        if ($swmsReport->customer_id !== $customerId || $swmsReport->workspace_id !== $workspaceId) {
            return $this->message('You do not have access to this report.', 403);
        }
        try {
            // Save all signatures using a reusable method
            $signatureData = [
                ['employees' => 'column_employee_id', 'signatures' => 'column_signature', 'dates' => 'column_date', 'model' => swmsDevelopedBy::class],
                ['employees' => 'columns_approved_by_emp_id', 'signatures' => 'columns_approved_by_signature', 'dates' => 'columns_approved_by_date', 'model' => SwmsApprovedBy::class],
            ];
            foreach ($signatureData as $data) {
                $this->saveSignatures(
                    $swms_report_id,
                    $request->input($data['employees'], []),
                    $request->file($data['signatures'], []),
                    $request->input($data['dates'], []),
                    $data['model']
                );
            }
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 3 Saved Successfully.',
                'report_id' => $swms_report_id,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return $this->success(['swms_report_id' => $swms_report_id], 'Saved Successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 3 error:' . $shortMessage,
                'report_id' => $swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $shortMessage);
        }
    }
    public function swmsQuickEntryStore(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'title' => 'required|string|max:255',
                'swms_number' => 'required|string|max:255',
                'description' => 'nullable|string',
                'site_id' => 'required|integer|exists:sites,id',
                'site_manager_or_forman' => 'nullable|string',
                'start_date' => 'nullable|date',
                'senior_management_representative' => 'nullable|string|max:255',
                'consultant_by' => 'nullable|string|max:255',
                'consultant_by_date' => 'nullable|string|max:255',
                'senior_management_representative_date' => 'nullable|string|max:255',
                'sign_off' => 'nullable|array',
                'sign_off.*.emp_id' => 'required_with:sign_off|integer|exists:emp_company_details,id',
                'sign_off.*.job_description' => 'nullable|string|max:255',
                'sign_off.*.inductance_date' => 'nullable|date',
                'file' => 'required|file|max:20480',
            ],
            [
                'file.required' => 'SWMS summary PDF is required.',
            ]
        );
        $validator->after(function ($validator) use ($request) {
            $employeeFieldConfigs = [
                'site_manager_or_forman' => 'site manager or foreman',
                'consultant_by' => 'consultant by',
                'senior_management_representative' => 'senior management representative',
            ];

            foreach ($employeeFieldConfigs as $field => $label) {
                $rawValue = $request->input($field);
                $attributeKey = "parsed_{$field}";

                if (is_null($rawValue) || (is_string($rawValue) && trim($rawValue) === '') || (is_array($rawValue) && empty(array_filter($rawValue)))) {
                    $request->attributes->set($attributeKey, []);
                    continue;
                }

                try {
                    $ids = $this->prepareEmployeeIds($rawValue, $label, true);
                    $request->attributes->set($attributeKey, $ids);
                } catch (InvalidArgumentException $exception) {
                    $validator->errors()->add($field, $exception->getMessage());
                    $request->attributes->set($attributeKey, []);
                }
            }

            $dateFieldConfigs = [
                'consultant_by_date' => [
                    'label' => 'consultant by date',
                    'employee_field' => 'consultant_by',
                ],
                'senior_management_representative_date' => [
                    'label' => 'senior management representative date',
                    'employee_field' => 'senior_management_representative',
                ],
            ];

            foreach ($dateFieldConfigs as $field => $config) {
                $rawValue = $request->input($field);
                $attributeKey = "parsed_{$field}";

                if (is_null($rawValue) || (is_string($rawValue) && trim($rawValue) === '') || (is_array($rawValue) && empty(array_filter($rawValue)))) {
                    $request->attributes->set($attributeKey, []);
                    continue;
                }

                try {
                    $dates = $this->prepareDateValues($rawValue, $config['label']);
                    $request->attributes->set($attributeKey, $dates);
                } catch (InvalidArgumentException $exception) {
                    $validator->errors()->add($field, $exception->getMessage());
                    $request->attributes->set($attributeKey, []);
                }
            }
        });

        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS quick entry validation error: ' . $validator->errors()->first(),
                'report_id' => 0,
                'report_type' => 'swms_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);
            }

            $revisionData = $this->generateRevisionNumberAndVersion();
            $siteManagerIdArray = $request->attributes->get('parsed_site_manager_or_forman', []);
            $consultantByIds = $request->attributes->get('parsed_consultant_by', []);
            $seniorManagementIds = $request->attributes->get('parsed_senior_management_representative', []);
            $consultantByDates = $request->attributes->get('parsed_consultant_by_date', []);
            $seniorManagementDates = $request->attributes->get('parsed_senior_management_representative_date', []);

            $siteManagerIds = !empty($siteManagerIdArray) ? implode(',', $siteManagerIdArray) : null;
            $consultantByIdsString = !empty($consultantByIds) ? implode(',', $consultantByIds) : null;
            $seniorManagementIdsString = !empty($seniorManagementIds) ? implode(',', $seniorManagementIds) : null;

            $swms = Swms::create([
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'title' => $request->title,
                'swms_number' => $request->swms_number,
                'description' => $request->description,
                'site_id' => $request->site_id,
                'site_manager_or_forman' => $siteManagerIds,
                'start_date' => $request->start_date,
                'revision_number' => $revisionData['revision_number'],
                'version_number' => $revisionData['version_number'],
                'report_method' => 1,
                'process' => '1',
            ]);

            SwmsMeta::updateOrCreate(
                ['swms_id' => $swms->id],
                [
                    'person_responsible_for_ensuring_compliance' => $seniorManagementIdsString,
                    'person_responsible_for_reviewing_swms' => $consultantByIdsString,
                ]
            );

            $signOffEntries = collect($request->input('sign_off', []))->filter(function ($entry) {
                return isset($entry['emp_id']) && !empty($entry['emp_id']);
            });
            foreach ($signOffEntries as $entry) {
                $inductanceDate = null;
                if (!empty($entry['inductance_date'])) {
                    try {
                        $inductanceDate = Carbon::parse($entry['inductance_date'])->format('Y-m-d');
                    } catch (Exception $e) {
                        $inductanceDate = null;
                    }
                }
                SwmsSignature::updateOrCreate(
                    [
                        'swms_id' => $swms->id,
                        'emp_id' => $entry['emp_id'],
                    ],
                    [
                        'job_desription' => $entry['job_description'] ?? null,
                        'inductance_date' => $inductanceDate,
                    ]
                );
            }
            $signatureData = [
                [
                    'employees' => $consultantByIds,
                    'signatures' => 'column_signature',
                    'dates' => $consultantByDates,
                    'model' => swmsDevelopedBy::class,
                ],
                [
                    'employees' => $seniorManagementIds,
                    'signatures' => 'columns_approved_by_signature',
                    'dates' => $seniorManagementDates,
                    'model' => SwmsApprovedBy::class,
                ],
            ];
            foreach ($signatureData as $data) {
                $employeeValues = is_array($data['employees']) ? $data['employees'] : [];
                $dateValues = is_array($data['dates']) ? $data['dates'] : [];

                $signatureFiles = $request->file($data['signatures'], []);
                if ($signatureFiles instanceof \Illuminate\Http\UploadedFile) {
                    $signatureFiles = [$signatureFiles];
                } elseif (!is_array($signatureFiles)) {
                    $signatureFiles = [];
                }

                $hasEmployees = count(array_filter($employeeValues, fn ($value) => $value !== null && $value !== '')) > 0;
                $hasFiles = count(array_filter($signatureFiles, fn ($file) => $file instanceof \Illuminate\Http\UploadedFile && $file->isValid())) > 0;
                $hasDates = count(array_filter($dateValues, fn ($value) => $value !== null && $value !== '')) > 0;

                if (!$hasEmployees && !$hasFiles && !$hasDates) {
                    continue;
                }

                $this->saveSignatures(
                    $swms->id,
                    $employeeValues,
                    $signatureFiles,
                    $dateValues,
                    $data['model']
                );
            }
            $pdfFile = $request->file('file');
            $fileUrl = $this->handleFileImageUpload($request, 'swms_report')['path'] ?? null;

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

            DB::commit();

            storeReportsLogs([
                'employee_id' => $authUser->id,
                'message' => 'SWMS quick entry saved successfully.',
                'report_id' => $swms->id,
                'report_type' => 'swms_report'
            ]);

            return $this->success([
                'swms_report_id' => $swms->id,
                'pdf_url' => $fileUrl,
            ], 'SWMS 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' => 'SWMS quick entry error: ' . $shortMessage,
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $shortMessage, 500);
        }
    }

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

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

        try {
            $swms = Swms::with('siteData')->find($request->swms_report_id);
            if (!$swms) {
                return $this->error('SWMS 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 ($swms->customer_id !== $customerId || $swms->workspace_id !== $workspaceId) {
                return $this->error('You do not have access to this report.', 403);
            }

            $siteManagerIds = collect($this->parseDelimitedInput($swms->site_manager_or_forman))
                ->map(fn ($id) => (int) $id)
                ->filter()
                ->values()
                ->all();

            $meta = SwmsMeta::where('swms_id', $swms->id)->first();
            $consultantByIds = collect($this->parseDelimitedInput(optional($meta)->person_responsible_for_reviewing_swms))
                ->map(fn ($id) => (int) $id)
                ->filter()
                ->values()
                ->all();
            $seniorManagementIds = collect($this->parseDelimitedInput(optional($meta)->person_responsible_for_ensuring_compliance))
                ->map(fn ($id) => (int) $id)
                ->filter()
                ->values()
                ->all();

            $developedByRecords = swmsDevelopedBy::where('swms_id', $swms->id)
                ->where('del', '0')
                ->get()
                ->keyBy('employee_id');
            $approvedByRecords = SwmsApprovedBy::where('swms_id', $swms->id)
                ->where('del', '0')
                ->get()
                ->keyBy('employee_id');

            $consultantByDates = collect($consultantByIds)->map(function ($id) use ($developedByRecords) {
                $record = $developedByRecords->get($id);
                if (!$record || empty($record->date)) {
                    return null;
                }
                try {
                    return Carbon::parse($record->date)->format('Y-m-d');
                } catch (Exception $e) {
                    return $record->date;
                }
            })->all();

            $seniorManagementDates = collect($seniorManagementIds)->map(function ($id) use ($approvedByRecords) {
                $record = $approvedByRecords->get($id);
                if (!$record || empty($record->date)) {
                    return null;
                }
                try {
                    return Carbon::parse($record->date)->format('Y-m-d');
                } catch (Exception $e) {
                    return $record->date;
                }
            })->all();

            $signOffEntries = SwmsSignature::where('swms_id', $swms->id)
                ->get(['emp_id', 'job_desription', 'inductance_date'])
                ->map(function ($signature) {
                    $inductanceDate = $signature->inductance_date;
                    if (!empty($inductanceDate)) {
                        try {
                            $inductanceDate = Carbon::parse($inductanceDate)->format('Y-m-d');
                        } catch (Exception $e) {
                            // leave as original value
                        }
                    }
                    return [
                        'emp_id' => $signature->emp_id,
                        'job_description' => $signature->job_desription,
                        'inductance_date' => $inductanceDate,
                    ];
                })
                ->values()
                ->all();

            $generatedReport = GeneratedPdfReport::where('report_type', 'swms_report')
                ->where('report_id', $swms->id)
                ->first();

            $responseData = [
                'swms_report_id' => $swms->id,
                'title' => $swms->title,
                'swms_number' => $swms->swms_number,
                'description' => $swms->description,
                'site_id' => $swms->site_id,
                'start_date' => $swms->start_date,
                'site_manager_or_forman' => $siteManagerIds,
                'consultant_by' => $consultantByIds,
                'consultant_by_date' => $consultantByDates,
                'senior_management_representative' => $seniorManagementIds,
                'senior_management_representative_date' => $seniorManagementDates,
                'sign_off' => $signOffEntries,
                'pdf_url' => $generatedReport->path ?? null,
                'report_method' => $swms->report_method,
            ];

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

    public function swmsQuickEntryUpdate(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'swms_report_id' => 'required|integer|exists:swms,id',
                'title' => 'required|string|max:255',
                'swms_number' => 'required|string|max:255',
                'description' => 'nullable|string',
                'site_id' => 'required|integer|exists:sites,id',
                'site_manager_or_forman' => 'nullable|string',
                'start_date' => 'nullable|date',
                'senior_management_representative' => 'nullable|string|max:255',
                'consultant_by' => 'nullable|string|max:255',
                'consultant_by_date' => 'nullable|string|max:255',
                'senior_management_representative_date' => 'nullable|string|max:255',
                'sign_off' => 'nullable|array',
                'sign_off.*.emp_id' => 'required_with:sign_off|integer|exists:emp_company_details,id',
                'sign_off.*.job_description' => 'nullable|string|max:255',
                'sign_off.*.inductance_date' => 'nullable|date',
                'file' => 'nullable|file|max:20480',
            ]
        );

        $validator->after(function ($validator) use ($request) {
            $employeeFieldConfigs = [
                'site_manager_or_forman' => 'site manager or foreman',
                'consultant_by' => 'consultant by',
                'senior_management_representative' => 'senior management representative',
            ];

            foreach ($employeeFieldConfigs as $field => $label) {
                $rawValue = $request->input($field);
                $attributeKey = "parsed_{$field}";

                if (is_null($rawValue) || (is_string($rawValue) && trim($rawValue) === '') || (is_array($rawValue) && empty(array_filter($rawValue)))) {
                    $request->attributes->set($attributeKey, []);
                    continue;
                }

                try {
                    $ids = $this->prepareEmployeeIds($rawValue, $label, true);
                    $request->attributes->set($attributeKey, $ids);
                } catch (InvalidArgumentException $exception) {
                    $validator->errors()->add($field, $exception->getMessage());
                    $request->attributes->set($attributeKey, []);
                }
            }

            $dateFieldConfigs = [
                'consultant_by_date' => [
                    'label' => 'consultant by date',
                ],
                'senior_management_representative_date' => [
                    'label' => 'senior management representative date',
                ],
            ];

            foreach ($dateFieldConfigs as $field => $config) {
                $rawValue = $request->input($field);
                $attributeKey = "parsed_{$field}";

                if (is_null($rawValue) || (is_string($rawValue) && trim($rawValue) === '') || (is_array($rawValue) && empty(array_filter($rawValue)))) {
                    $request->attributes->set($attributeKey, []);
                    continue;
                }

                try {
                    $dates = $this->prepareDateValues($rawValue, $config['label']);
                    $request->attributes->set($attributeKey, $dates);
                } catch (InvalidArgumentException $exception) {
                    $validator->errors()->add($field, $exception->getMessage());
                    $request->attributes->set($attributeKey, []);
                }
            }
        });

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

        try {
            DB::beginTransaction();
            $swms = Swms::find($request->swms_report_id);
            if (!$swms) {
                return $this->error('SWMS 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 ($swms->customer_id !== $customerId || $swms->workspace_id !== $workspaceId) {
                return $this->error('You do not have access to this report.', 403);
            }

            $siteManagerIdArray = $request->attributes->get('parsed_site_manager_or_forman', []);
            $consultantByIds = $request->attributes->get('parsed_consultant_by', []);
            $seniorManagementIds = $request->attributes->get('parsed_senior_management_representative', []);
            $consultantByDates = $request->attributes->get('parsed_consultant_by_date', []);
            $seniorManagementDates = $request->attributes->get('parsed_senior_management_representative_date', []);

            $siteManagerIds = !empty($siteManagerIdArray) ? implode(',', $siteManagerIdArray) : null;
            $consultantByIdsString = !empty($consultantByIds) ? implode(',', $consultantByIds) : null;
            $seniorManagementIdsString = !empty($seniorManagementIds) ? implode(',', $seniorManagementIds) : null;

            $swms->update([
                'title' => $request->title,
                'swms_number' => $request->swms_number,
                'description' => $request->description,
                'site_id' => $request->site_id,
                'site_manager_or_forman' => $siteManagerIds,
                'start_date' => $request->start_date,
                'report_method' => 1,
                'process' => 1,
            ]);

            SwmsMeta::updateOrCreate(
                ['swms_id' => $swms->id],
                [
                    'person_responsible_for_ensuring_compliance' => $seniorManagementIdsString,
                    'person_responsible_for_reviewing_swms' => $consultantByIdsString,
                ]
            );

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

            $signOffEmployeeIds = [];
            foreach ($signOffEntries as $entry) {
                $inductanceDate = null;
                if (!empty($entry['inductance_date'])) {
                    try {
                        $inductanceDate = Carbon::parse($entry['inductance_date'])->format('Y-m-d');
                    } catch (Exception $e) {
                        $inductanceDate = null;
                    }
                }
                $signOffEmployeeIds[] = $entry['emp_id'];
                SwmsSignature::updateOrCreate(
                    [
                        'swms_id' => $swms->id,
                        'emp_id' => $entry['emp_id'],
                    ],
                    [
                        'job_desription' => $entry['job_description'] ?? null,
                        'inductance_date' => $inductanceDate,
                    ]
                );
            }

            if (empty($signOffEmployeeIds)) {
                SwmsSignature::where('swms_id', $swms->id)->delete();
            } else {
                SwmsSignature::where('swms_id', $swms->id)
                    ->whereNotIn('emp_id', $signOffEmployeeIds)
                    ->delete();
            }

            $signatureData = [
                [
                    'employees' => $consultantByIds,
                    'signatures' => 'column_signature',
                    'dates' => $consultantByDates,
                    'model' => swmsDevelopedBy::class,
                ],
                [
                    'employees' => $seniorManagementIds,
                    'signatures' => 'columns_approved_by_signature',
                    'dates' => $seniorManagementDates,
                    'model' => SwmsApprovedBy::class,
                ],
            ];

            foreach ($signatureData as $data) {
                $employeeValues = is_array($data['employees']) ? $data['employees'] : [];
                $dateValues = is_array($data['dates']) ? $data['dates'] : [];

                $signatureFiles = $request->file($data['signatures'], []);
                if ($signatureFiles instanceof \Illuminate\Http\UploadedFile) {
                    $signatureFiles = [$signatureFiles];
                } elseif (!is_array($signatureFiles)) {
                    $signatureFiles = [];
                }

                $hasEmployees = count(array_filter($employeeValues, fn ($value) => $value !== null && $value !== '')) > 0;
                $hasFiles = count(array_filter($signatureFiles, fn ($file) => $file instanceof \Illuminate\Http\UploadedFile && $file->isValid())) > 0;
                $hasDates = count(array_filter($dateValues, fn ($value) => $value !== null && $value !== '')) > 0;

                if (!$hasEmployees && !$hasFiles && !$hasDates) {
                    continue;
                }

                $this->saveSignatures(
                    $swms->id,
                    $employeeValues,
                    $signatureFiles,
                    $dateValues,
                    $data['model']
                );
            }

            $this->markInactiveSignatures($swms->id, $consultantByIds, swmsDevelopedBy::class);
            $this->markInactiveSignatures($swms->id, $seniorManagementIds, SwmsApprovedBy::class);

            $generatedReport = GeneratedPdfReport::where('report_type', 'swms_report')
                ->where('report_id', $swms->id)
                ->first();
            $existingFilePath = $generatedReport->path ?? null;
            $fileUrl = $existingFilePath;

            if ($request->hasFile('file')) {
                $uploadResult = $this->handleFileImageUpload($request, 'swms_report', $existingFilePath);
                $fileUrl = $this->extractUploadedPath($uploadResult, 'file') ?? $fileUrl;
            }

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

            DB::commit();

            storeReportsLogs([
                'employee_id' => $authUser->id,
                'message' => 'SWMS quick entry updated successfully.',
                'report_id' => $swms->id,
                'report_type' => 'swms_report'
            ]);

            return $this->success([
                'swms_report_id' => $swms->id,
                'pdf_url' => $fileUrl,
            ], 'SWMS 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' => 'SWMS quick entry update error: ' . $shortMessage,
                'report_id' => $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $shortMessage, 500);
        }
    }
    // Generalized function to save signature data
    private function saveSignatures($swms_report_id, $employee_ids, $signature_files, $dates, $modelClass)
    {
        try {
            $employee_count = count($employee_ids);
            for ($i = 0; $i < $employee_count; $i++) {
                $employee_id = $employee_ids[$i];
                $signature_date = isset($dates[$i]) ? $dates[$i] : null;
                $signature_file = isset($signature_files[$i]) ? $signature_files[$i] : null;
                if (empty($employee_id)) {
                    continue;
                }
                $signature_path = null;
                if ($signature_file && $signature_file->isValid()) {
                    $imageName = $employee_id . time() . '.' . $signature_file->getClientOriginalExtension();
                    $signature_file->move(public_path('SWMSReportDocuments'), $imageName);
                    $signature_path = 'SWMSReportDocuments/' . $imageName;
                }
                $signature = $modelClass::where('swms_id', $swms_report_id)
                    ->where('employee_id', $employee_id)
                    ->where('del', '0')
                    ->first();
                // dd($signature);
                if ($signature) {
                    if ($signature_path) {
                        $signature->signature = $signature_path;
                    }
                    if ($signature_date) {
                        $signature->date = $signature_date;
                    }
                    $signature->save();
                } else {
                    $modelClass::create([
                        'swms_id' => $swms_report_id,
                        'employee_id' => $employee_id,
                        'signature' => $signature_path,
                        'date' => $signature_date,
                    ]);
                }
            }
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 3 error:' . $shortMessage,
                'report_id' =>  $swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => 'An error occurred : ' . $shortMessage,
            ], 500);
        }
    }

    private function prepareEmployeeIds($value, string $fieldLabel, bool $allowEmpty = true): array
    {
        $parsedValues = $this->parseDelimitedInput($value);

        if (empty($parsedValues)) {
            if ($allowEmpty) {
                return [];
            }

            throw new InvalidArgumentException(ucfirst($fieldLabel) . ' is required.');
        }

        $invalidValues = collect($parsedValues)->reject(fn ($item) => ctype_digit((string) $item));
        if ($invalidValues->isNotEmpty()) {
            throw new InvalidArgumentException(ucfirst($fieldLabel) . ' must contain only numeric employee IDs.');
        }

        $ids = collect($parsedValues)
            ->map(fn ($id) => (int) $id)
            ->unique()
            ->values();

        if ($ids->isEmpty()) {
            return [];
        }

        $existingCount = EmpCompanyDetails::whereIn('id', $ids)->count();
        if ($existingCount !== $ids->count()) {
            throw new InvalidArgumentException('One or more selected ' . $fieldLabel . ' entries are invalid.');
        }

        return $ids->all();
    }

    private function prepareDateValues($value, string $fieldLabel): array
    {
        $parsedValues = $this->parseDelimitedInput($value);

        return collect($parsedValues)
            ->map(function ($dateValue) use ($fieldLabel) {
                try {
                    return Carbon::parse($dateValue)->format('Y-m-d');
                } catch (Exception $exception) {
                    throw new InvalidArgumentException(ucfirst($fieldLabel) . ' contains an invalid date.');
                }
            })
            ->values()
            ->all();
    }

    private function parseDelimitedInput($value): array
    {
        if (is_null($value)) {
            return [];
        }

        $items = is_array($value) ? $value : explode(',', (string) $value);

        return collect($items)
            ->map(function ($item) {
                if (is_null($item)) {
                    return null;
                }

                if (is_string($item)) {
                    $item = trim($item);
                } elseif (is_numeric($item)) {
                    $item = trim((string) $item);
                } else {
                    $item = trim((string) $item);
                }

                return $item === '' ? null : $item;
            })
            ->filter(fn ($item) => $item !== null && $item !== '')
            ->values()
            ->all();
    }

    private function markInactiveSignatures(int $swmsId, array $activeEmployeeIds, string $modelClass): void
    {
        $inactiveQuery = $modelClass::where('swms_id', $swmsId);

        if (!empty($activeEmployeeIds)) {
            $inactiveQuery->whereNotIn('employee_id', $activeEmployeeIds);
        }

        $inactiveQuery->update(['del' => '1']);

        $modelClass::where('swms_id', $swmsId)
            ->when(!empty($activeEmployeeIds), function ($query) use ($activeEmployeeIds) {
                return $query->whereIn('employee_id', $activeEmployeeIds);
            })
            ->update(['del' => '0']);
    }

    private function extractUploadedPath($uploadResult, string $targetKey): ?string
    {
        if (empty($uploadResult)) {
            return null;
        }

        if (isset($uploadResult['path']) && ($uploadResult['key'] ?? $targetKey) === $targetKey) {
            return $uploadResult['path'];
        }

        if (is_array($uploadResult)) {
            foreach ($uploadResult as $item) {
                if (is_array($item) && ($item['key'] ?? null) === $targetKey && isset($item['path'])) {
                    return $item['path'];
                }
            }
        }

        return null;
    }

    public function swmsStep3Edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 3 error:' . $validator->errors()->first(),
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $swmsReport = SWMS::find($request->swms_report_id);
            if (!$swmsReport) {
                return $this->message('No SWMS report found ', 404);
            }
            $userTable = $this->getUserTable();
            if ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id)) {
                return $this->message('You do not have access to this report.', 403);
            }
            $data['swmsDevelopedBy'] = swmsDevelopedBy::where('swms_id', $request->swms_report_id)->get();
            $data['SwmsApprovedBy'] = SwmsApprovedBy::where('swms_id', $request->swms_report_id)->get();
            // $authorised_by_list = EmpCompanyDetails::where('compeleted', '1')
            //     ->where('approved', '1')
            //     ->where('status', '1')
            //     ->where('del', '0')
            //     ->with([
            //         'empPersonalDetails' => function ($query) {
            //             $query->select('emp_id', 'first_name', 'middle_name', 'last_name');
            //         },
            //         'accessRole' => function ($query) {
            //             $query->select('id', 'title', 'code');
            //         },
            //         'empTier' => function ($query) {
            //             $query->select('id', 'title');
            //         },
            //         'accessTier' => function ($query) {
            //             $query->select('id', 'title', 'tier_key');
            //         },
            //     ])
            //     ->select('id', 'access_role', 'tier_id')
            //     ->whereIn('tier_id', function ($query) {
            //         $query->select('id')
            //             ->from('tiers')
            //             ->whereIn('tier_key', ['T-1', 'T-2', 'T-3']);
            //     })
            //     ->get();
            // $data['authorised_by_list'] = $authorised_by_list;
            $data['swms_report_id'] = $request->swms_report_id;
            return $this->success($data, 'Reocrd get Successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 3 error:' . $shortMessage,
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred : ' . $shortMessage);
        }
    }

    public function swmsStep3DevelopedByDelete($id)
    {
        try {
            $developedBy = SwmsDevelopedBy::with('swms')->find($id);
            if (!$developedBy) {
                return $this->message('Record not found.', 404);
            }
            $swmsReport = $developedBy->swms;
            if (!$swmsReport) {
                return $this->message('SWMS Report not found.', 404);
            }
            $userTable = $this->getUserTable();
            if (
                ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) ||
                ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id))
            ) {
                return $this->message('You do not have permission to delete this record.', 403);
            }
            if ($developedBy->signature && file_exists(public_path($developedBy->signature))) {
                unlink(public_path($developedBy->signature));
            }
            $developedBy->delete();
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 3 Developed By Deleted Successfully.',
                'report_id' => $id,
                '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 Step 3 error: ' . $shortMessage,
                'report_id' => $id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $shortMessage);
        }
    }

    public function swmsStep3ApprovedByDelete($id)
    {
        try {
            $approvedBy = SwmsApprovedBy::with('swms')->find($id);
            if (!$approvedBy) {
                return $this->message('Record not found.', 404);
            }
            $swmsReport = $approvedBy->swms;
            if (!$swmsReport) {
                return $this->message('SWMS Report not found.', 404);
            }
            $userTable = $this->getUserTable();
            if (
                ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) ||
                ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id))
            ) {
                return $this->message('You do not have permission to delete this record.', 403);
            }
            if ($approvedBy->signature && file_exists(public_path($approvedBy->signature))) {
                unlink(public_path($approvedBy->signature));
            }
            $approvedBy->delete();
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 3 Approved by Deleted Successfully.',
                'report_id' => $id,
                '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 Step 3 error: ' . $shortMessage,
                'report_id' => $id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $shortMessage);
        }
    }

    public function swmsStep4Store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required|exists:swms,id',
            'column_job_task' => 'nullable|array',
            'column_job_task.*' => 'nullable|string',
            'column_risk' => 'nullable|array',
            'column_risk.*' => 'nullable|string',
            'column_initial_risk_rating' => 'nullable|array',
            'column_initial_risk_rating.*' => 'nullable|integer',
            'column_hazard' => 'nullable|array',
            'column_hazard.*' => 'nullable|string',
            'column_control_risk_rating' => 'nullable|array',
            'column_control_risk_rating.*' => 'nullable|integer',
            'control_measure' => 'nullable|array',
            'control_measure.*' => 'nullable|string',
            'column_final_risk_rating' => 'nullable|array',
            'column_final_risk_rating.*' => 'nullable|integer',
            'column_task_detail_id' => 'nullable|array',
            'column_task_detail_id.*' => 'nullable|integer',
            'responsible_person_ids' => 'nullable|array',
            'responsible_person_ids.*' => 'nullable|string',
            'column_task_details_image.*' => 'nullable|image|mimes:png,jpeg,jpg|max:2048'
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 4 error: ' . $validator->errors()->first(),
                'report_id' => $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        $swms_report_id = $request->swms_report_id;
        try {
            $swmsReport = Swms::find($swms_report_id);
            if (!$swmsReport) {
                return $this->message('SWMS Report not found.', 404);
            }
            $userTable = $this->getUserTable();
            if (
                ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) ||
                ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id))
            ) {
                return $this->message('You do not have access to this report.', 403);
            }
            $jobTasks = $request->input('column_job_task', []);
            $risks = $request->input('column_risk', []);
            $initialRiskRatings = $request->input('column_initial_risk_rating', []);
            $hazards = $request->input('column_hazard', []);
            $controlRiskRatings = $request->input('column_control_risk_rating', []);
            $controlMeasures = $request->input('control_measure', []);
            $finalRiskRatings = $request->input('column_final_risk_rating', []);
            $taskDetailImages = $request->file('column_task_details_image', []);
            $taskDetailIds = $request->input('column_task_detail_id', []);
            $responsiblePersonIds = $request->input('responsible_person_ids', []);
            foreach ($responsiblePersonIds as $index => $responsiblePersonId) {
                $data = [
                    'swms_id' => $swms_report_id,
                    'responsible_preson_id' => $responsiblePersonId,
                    'job_task' => $jobTasks[$index] ?? null,
                    'risk' => $risks[$index] ?? null,
                    'initial_risk_rating' => $initialRiskRatings[$index] ?? null,
                    'hazard' => $hazards[$index] ?? null,
                    'controle_risk_ratting' => $controlRiskRatings[$index] ?? null,
                    'control_measure' => $controlMeasures[$index] ?? null,
                    'final_risk_ratting' => $finalRiskRatings[$index] ?? null
                ];
                // Handle Image Upload
                if (!empty($taskDetailImages[$index]) && $taskDetailImages[$index]->isValid()) {
                    $imageName = time() . '_' . $taskDetailImages[$index]->getClientOriginalName();
                    $taskDetailImages[$index]->move(public_path('SWMSReportDocuments'), $imageName);
                    $data['image'] = 'SWMSReportDocuments/' . $imageName;
                }
                // Check if updating an existing record
                $taskDetailId = $taskDetailIds[$index] ?? null;
                if ($taskDetailId) {
                    $existingRecord = SwmsTaskDetail::where('swms_id', $swms_report_id)->where('id', $taskDetailId)->first();
                    if ($existingRecord) {
                        $existingRecord->update($data);
                        continue;
                    }
                }
                // Create new record if no existing one
                SwmsTaskDetail::create($data);
            }
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 4 Saved Successfully.',
                'report_id' => $request->swms_report_id,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return $this->success(['swms_report_id' => $swms_report_id], 'Saved Successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 4 error:' . $shortMessage,
                'report_id' => $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $shortMessage);
        }
    }

    public function swmsStep4Edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 4 error:' . $validator->errors()->first(),
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $swmsReport = Swms::find($request->swms_report_id);
            if (!$swmsReport) {
                return $this->message('SWMS Report not found.', 404);
            }
            $userTable = $this->getUserTable();
            if (
                ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) ||
                ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id))
            ) {
                return $this->message('You do not have access to this report.', 403);
            }
            $data = SwmsTaskDetail::where('swms_id', $request->swms_report_id)->get();
            // $authorised_by_list = EmpCompanyDetails::where('compeleted', '1')
            //     ->where('approved', '1')
            //     ->where('status', '1')
            //     ->where('del', '0')
            //     ->with(
            //         [
            //             'empPersonalDetails' => function ($query) {
            //                 $query->select('emp_id', 'first_name', 'middle_name', 'last_name');
            //             },
            //             'accessRole' => function ($query) {
            //                 $query->select('id', 'title', 'code');
            //             },
            //             'empTier' => function ($query) {
            //                 $query->select('id', 'title');
            //             },
            //         ]
            //     )
            //     ->select('id', 'access_role', 'tier_id')
            //     ->get();
            // $data['responsible_person_list'] = $authorised_by_list;
            // $data['swms_report_id'] = $request->swms_report_id;
            return $this->success($data, 'Reocrd get Successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 4 edit error:' . $shortMessage,
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred : ' . $shortMessage);
        }
    }

    public function swmsStep3TaskDetailDelete($id)
    {
        try {
            $taskDetail = SwmsTaskDetail::with('swms')->find($id);
            if (!$taskDetail) {
                return $this->message('Record not found.', 404);
            }
            $swmsReport = $taskDetail->swms;
            if (!$swmsReport) {
                return $this->message('SWMS Report not found.', 404);
            }
            $userTable = $this->getUserTable();
            if (
                ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) ||
                ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id))
            ) {
                return $this->message('You do not have permission to delete this record.', 403);
            }
            if (!empty($taskDetail->image) && file_exists(public_path($taskDetail->image))) {
                unlink(public_path($taskDetail->image)); // Remove the file from storage
            }
            $taskDetail->delete();
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 3 Task Detail Deleted Successfully.',
                'report_id' => $id,
                '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 Step 3 Task Detail Delete error: ' . $shortMessage,
                'report_id' => $id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $shortMessage);
        }
    }

    public function swmsStep5Edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->message($validator->errors()->first(), 422);
        }
        $swmsReport = Swms::find($request->swms_report_id);
        if (!$swmsReport) {
            return $this->message('SWMS Report 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;
        // Validate access permissions
        if ($swmsReport->customer_id !== $customerId || $swmsReport->workspace_id !== $workspaceId) {
            return $this->message('You do not have access to this report.', 403);
        }
        $data['HazardRisk'] = HazardRisk::where('status', '1')->where('customer_id', $customerId)->where('workspace_id', $workspaceId)->get();
        $data['selectedHazardRiskIds'] = SwmsHazardRiskPivot::where('swms_id', $request->swms_report_id)->get();
        $data['SwmsProtectionToolPivotSelectedIds'] = SwmsProtectionToolPivot::where('swms_id', $request->swms_report_id)->get();
        $data['SwmsProtectionTool'] = SwmsProtectionTool::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->get();
        $data['SwmsQuestions'] = SwmsQuestions::where('status', '1')->where('customer_id', $customerId)->where('workspace_id', $workspaceId)->get();
        $answers = SwmsAwnswers::where('swms_id', $request->swms_report_id)->get()->keyBy('swms_question_id');
        $data['SwmsAwnswers'] = $answers;
        $data['swms_report_id'] = $request->swms_report_id;
        return $this->success($data, 'Get Successfully');
    }

    public function swmsStep5Store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required|exists:swms,id',
            'selectedHazards' => 'nullable|array',
            'selectedHazards.*' => 'integer|exists:hazard_risks,id',
            'selectedPivots' => 'nullable|array',
            'selectedPivots.*' => 'integer|exists:swms_protection_tools,id',
            'InputAnswers' => 'nullable|array',
            'InputAnswers.*' => 'string|nullable'
        ], [
            'selectedHazards.required' => 'At least one Hazard risk is required.',
            'selectedPivots.required' => 'At least one Protection tool is required.',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 5 store error: ' . $validator->errors()->first(),
                'report_id' => $request->swms_report_id,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $swms_report_id = $request->input('swms_report_id');
            $swmsReport = Swms::findOrFail($swms_report_id);
            // Validate user access
            $userTable = $this->getUserTable();
            if (
                ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) ||
                ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id))
            ) {
                return $this->message('You do not have access to this report.', 403);
            }
            // Prepare Data
            $data['swms_report_id'] = $swms_report_id;
            // Delete old records
            SwmsHazardRiskPivot::where('swms_id', $swms_report_id)->delete();
            SwmsProtectionToolPivot::where('swms_id', $swms_report_id)->delete();
            SwmsAwnswers::where('swms_id', $swms_report_id)->delete();
            // Insert Hazard Risks
            $selectedHazards = $request->input('selectedHazards', []);
            foreach ($selectedHazards as $hazardId) {
                SwmsHazardRiskPivot::create([
                    'swms_id' => $swms_report_id,
                    'hazard_risks_id' => $hazardId
                ]);
            }
            // Insert Protection Tools
            $selectedPivots = $request->input('selectedPivots', []);
            foreach ($selectedPivots as $protectionToolId) {
                SwmsProtectionToolPivot::create([
                    'swms_id' => $swms_report_id,
                    'protection_tool_id' => $protectionToolId
                ]);
            }
            // Insert Input Answers
            $inputAnswers = $request->input('InputAnswers', []);
            $existingQuestionIds = SwmsQuestions::pluck('id')->toArray(); // Fetch valid question IDs
            foreach ($inputAnswers as $questionId => $answer) {
                if (in_array($questionId, $existingQuestionIds)) { // ✅ Only insert if question exists
                    SwmsAwnswers::updateOrCreate(
                        ['swms_id' => $swms_report_id, 'swms_question_id' => $questionId],
                        ['answer' => $answer]
                    );
                }
            }
            // Logging
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 5 Saved successfully.',
                'report_id' => $swms_report_id,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return $this->success($data, 'Saved successfully.');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 5 store error: ' . $shortMessage,
                'report_id' => $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred: ' . $shortMessage);
        }
    }

    public function SwmsSignature(Request $request)
    {
        try {
            $swms_report_id = $request->input('swms_report_id');

            // Check if a SWMS Signature record already exists for the given SWMS ID
            $swmsSignatureExists = SwmsSignature::where('swms_id', $swms_report_id)->exists();
            $validator = Validator::make($request->all(), [
                'swms_report_id' => 'required|integer',

            ]);
            $inductance_dates = (array) $request->input('inductance_dates', []);
            if ($inductance_dates || $inductance_dates != null) {
                $validator->sometimes('inductance_dates', 'required|array|min:1', function ($input) use ($swmsSignatureExists) {
                    return !$swmsSignatureExists;
                });
                $validator->sometimes('inductance_dates.*', 'required|date|after_or_equal:today', function ($input) use ($swmsSignatureExists) {
                    return !$swmsSignatureExists;
                });
            }
            // if ($validator->fails()) {
            //     return response()->json([
            //         'message' => $validator->errors()->first(),
            //     ], 422);
            // }
            $swms_report_id = $request->swms_report_id;
            $access_role_ids = (array) $request->input('access_role_ids', []);
            $job_descriptions = (array) $request->input('job_descriptions', []);
            $inductance_dates = (array) $request->input('inductance_dates', []);
            $record_ids = (array) $request->input('record_ids', []);
            // Check if the arrays have matching lengths
            // if (count($access_role_ids) !== count($job_descriptions) || count($access_role_ids) !== count($inductance_dates) || count($access_role_ids) !== count($record_ids)) {
            //     return response()->json([
            //         'message' => 'Mismatched input  please complete all inputs.',
            //     ], 422);
            // }
            // // Loop through the input arrays or handle single items
            // foreach ($access_role_ids as $index => $access_role_id) {
            //     $jobDescription = $job_descriptions[$index] ?? null;
            //     $inductanceDate = $inductance_dates[$index] ?? null;
            //     $recordId = $record_ids[$index] ?? null;
            //     if ($recordId) {
            //         // Update existing record
            //         $swmsSignature = SwmsSignature::where('swms_id', $swms_report_id)->find($recordId);
            //         if ($swmsSignature) {
            //             // $swmsSignature->update([
            //             //     'swms_id' => $swms_report_id,
            //             //     'tier_id' => $access_role_id,
            //             //     'job_desription' => $jobDescription,
            //             //     'inductance_date' => $inductanceDate,
            //             // ]);
            //         } else {
            //             // SwmsSignature::create([
            //             //     'swms_id' => $swms_report_id,
            //             //     'tier_id' => $access_role_id,
            //             //     'job_desription' => $jobDescription,
            //             //     'inductance_date' => $inductanceDate,
            //             // ]);
            //         }
            //     } else {
            //         // Create new record
            //         // SwmsSignature::create([
            //         //     'swms_id' => $swms_report_id,
            //         //     'tier_id' => $access_role_id,
            //         //     'job_desription' => $jobDescription,
            //         //     'inductance_date' => $inductanceDate,
            //         // ]);
            //     }
            // }
            $SwmsSafetyPlanningAnswersinputAnswers = json_decode($request->input('InputAnswers', '{}'), true);
            // Loop through each input answer and save or update in the database
            foreach ($SwmsSafetyPlanningAnswersinputAnswers as $noteId => $answer) {
                SwmsSafetyPlanningAnswers::updateOrCreate(
                    [
                        'swms_id' => $request->swms_report_id,
                        'swms_safety_planning_id' => $noteId
                    ],
                    [
                        'answer' => $answer
                    ]
                );
            }
            Swms::where('id', $swms_report_id)->update(['process' => '1']);
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 6 store Data saved successfully.',
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => 'Data saved successfully.',
                'data' => ['swms_report_id' => $swms_report_id],
            ], 200);
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 6 store error: ' . $shortMessage,
                'report_id' => $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $shortMessage);
        }
    }

    public function swmsStep6Store(Request $request)
    {
        // try {
            $swms_report_id = $request->input('swms_report_id');
            $validator = Validator::make($request->all(), [
                "swms_report_id" => 'required|exists:swms,id',
                "sign_off" => 'nullable|array',
                "sign_off.*.emp_id" => 'nullable|integer'
            ]);
            if ($validator->fails()) {
                return $this->error($validator->errors()->first(), 422);
            }
            $validatedData = $validator->validated();
            $swmsReport = Swms::find($swms_report_id);
            if (!$swmsReport) {
                return $this->message('SWMS Report not found.', 404);
            }
            $userTable = $this->getUserTable();
            if (
                ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) ||
                ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id))
            ) {
                return $this->message('You do not have access to this report.', 403);
            }
            // Check if a SWMS Signature record already exists for the given SWMS ID
            $swmsSignatureExists = SwmsSignature::where('swms_id', $swms_report_id)->exists();
            $validator = Validator::make($request->all(), [
                'swms_report_id' => 'required|integer',

            ]);
            $inductance_dates = (array) $request->input('inductance_dates', []);
            if ($inductance_dates || $inductance_dates != null) {
                $validator->sometimes('inductance_dates', 'required|array|min:1', function ($input) use ($swmsSignatureExists) {
                    return !$swmsSignatureExists;
                });

                $validator->sometimes('inductance_dates.*', 'required|date|after_or_equal:today', function ($input) use ($swmsSignatureExists) {
                    return !$swmsSignatureExists;
                });
            }
            $swms_report_id = $request->swms_report_id;
            $inductance_dates = (array) $request->input('inductance_dates', []);

            $SwmsSafetyPlanningAnswersinputAnswers = $request->input('InputAnswers', '{}');
            // Loop through each input answer and save or update in the database
            foreach ($SwmsSafetyPlanningAnswersinputAnswers as $noteId => $answer) {
                SwmsSafetyPlanningAnswers::updateOrCreate(
                    [
                        'swms_id' => $request->swms_report_id,
                        'swms_safety_planning_id' => $noteId
                    ],
                    [
                        'answer' => $answer
                    ]
                );
            }
            Swms::where('id', $swms_report_id)->update(['process' => '1']);
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 6 store Data saved successfully.',
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            if (isset($validatedData['sign_off'])) {
                $currentEmployeeIds = collect($validatedData['sign_off'])
                    ->pluck('emp_id')
                    ->filter(function ($empId) {
                        return !empty($empId);
                    })
                    ->toArray();

                // Get existing employee IDs for this SWMS report
                $existingEmployeeIds = DB::table('swms_signatures')
                    ->where('swms_id', $validatedData['swms_report_id'])
                    ->pluck('emp_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('swms_signatures')
                        ->where('swms_id', $validatedData['swms_report_id'])
                        ->whereIn('emp_id', $employeesToRemove)
                        ->delete();
                }
                foreach ($validatedData['sign_off'] as $swms_signoff) {
                    if (empty($swms_signoff['emp_id']) || empty($validatedData['swms_report_id'])) {
                        // Skip this record if emp_id or swms_report_id is missing
                        continue;
                    }
                    $swms_signoff['swms_id'] = $validatedData['swms_report_id'];
                    $swms_signoff['emp_id'] = $swms_signoff['emp_id'] ?? 0;

                    // Initialize variables

                    $existingRecord = DB::table('swms_signatures')
                        ->where('swms_id', $validatedData['swms_report_id'])
                        ->where('emp_id', $swms_signoff['emp_id'])
                        ->first();

                    if ($existingRecord) {
                        // Update existing record
                        DB::table('swms_signatures')
                            ->where('swms_id', $validatedData['swms_report_id'])
                            ->where('emp_id', $swms_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('swms_signatures')->insert([
                            'swms_id' => $validatedData['swms_report_id'],
                            'emp_id' => $swms_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->message('Data saved successfully.');
        // } catch (Exception $e) {
        //     $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
        //     $log = [
        //         'employee_id' => auth()->user()->id,
        //         'message' => 'SWMS Step 6 store error:' . $shortMessage,
        //         'report_id' =>  $request->swms_report_id,
        //         'report_type' => 'swms_report',
        //         'error_type' => 'Exception error'
        //     ];
        //     storeReportsLogs($log);
        //     return $this->error('An error occurred: ' . $shortMessage);
        // }
    }

    public function swmsStep6Edit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 6 edit error:',
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $swmsReport = Swms::find($request->swms_report_id);
            if (!$swmsReport) {
                return $this->message('SWMS Report not found.', 404);
            }
            $userTable = $this->getUserTable();
            if (
                ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) ||
                ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id))
            ) {
                return $this->message('You do not have access to this report.', 403);
            }
            // Fetch signature data
            $swmsSignatures = DB::table('swms_signatures')
                ->where('swms_id', $request->swms_report_id)
                ->pluck('emp_id')
                ->toArray();
            $data['SwmsSignature'] = SwmsSignature::where('swms_id', $request->swms_report_id)->get();
            $data['SwmsSafetyPlanningAnswers'] = SwmsSafetyPlanningAnswers::where('swms_id', $request->swms_report_id)->get();
            $data['swms_report_id'] = $request->swms_report_id;
            $data['sign_off'] = $swmsSignatures;
            // dd($role);
            return $this->success($data, 'Get Successfully');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 6 store error:' . $shortMessage,
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred : ' . $shortMessage);
        }
    }

    public function swmsStep6SignatureDelete(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'swms_report_id' => 'required|integer',
            ]);
            if ($validator->fails()) {
                $log = [
                    'employee_id' => auth()->user()->id,
                    'message' => 'SWMS Step 6 Signature delete error: ' . $validator->errors()->first(),
                    'report_id' =>  $request->swms_report_id,
                    'report_type' => 'swms_report',
                    'error_type' => 'Validation error',
                ];
                storeReportsLogs($log);
                return $this->message($validator->errors()->first(), 422);
            }
            $swmsReport = Swms::find($request->swms_report_id);
            if (!$swmsReport) {
                return $this->message('SWMS Report not found.', 404);
            }
            $userTable = $this->getUserTable();
            if (
                ($userTable === 'customer' && ($swmsReport->customer_id !== auth()->id() || $swmsReport->workspace_id !== auth()->user()->current_workspace_id)) ||
                ($userTable === 'emp' && ($swmsReport->customer_id !== auth()->user()->customer_id || $swmsReport->workspace_id !== auth()->user()->workspace_id))
            ) {
                return $this->message('You do not have access to this report.', 403);
            }
            // Check if the signature exists
            $signature = SwmsSignature::find($request->signature_id);
            if (!$signature) {
                return $this->message('Signature not found.', 404);
            }
            $swmsSignature = SwmsSignature::where('id', $request->signature_id)->where('swms_id', $request->swms_report_id)->delete();
            if (!$swmsSignature) {
                return $this->message('You do not have access to this report Signature .', 500);
            }
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 6 Signature with ID ' . $request->signature_id . ' deleted:',
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message('Signature deleted successfully.', 200);
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Step 6 store error:' . $shortMessage,
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred : ' . $shortMessage);
        }
    }
    // PDF
    public function swmsReportDownloadPdf($id)
    {
        if (!$id) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Report Download ID is required :',
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => 'Report ID is Required.'
            ], 422);
        }
        try {
            // Get basic data for filename generation
            $swms_basic_data = DB::table('swms')
                ->where('id', $id)
                ->select('title', 'swms_number', 'version_number')
                ->first();
            if (!$swms_basic_data) {
                return response()->json([
                    'message' => 'SWMS record not found.'
                ], 404);
            }
            // Generate filename
            $report_title = isset($swms_basic_data->title)
                ? preg_replace('/[^A-Za-z0-9_]+/', '_', trim(str_replace(' ', '_', $swms_basic_data->title)))
                : 'No_named';
            $report_swms_number = isset($swms_basic_data->swms_number)
                ? preg_replace('/[^A-Za-z0-9_]+/', '', trim(str_replace(' ', '_', $swms_basic_data->swms_number)))
                : 'NO_Swms';
            $report_version_number = isset($swms_basic_data->version_number)
                ? preg_replace('/[^A-Za-z0-9_]+/', '', trim(str_replace(' ', '_', $swms_basic_data->version_number)))
                : 'No_Version';
            $filename = $report_title . "N" . $report_swms_number . "R" . $report_version_number . ".pdf";
            $report_full_path = public_path('Files_manager/swms_reports/' . $filename);
            $file_url = url('Files_manager/swms_reports/' . $filename);
            // Check if file exists and has database record
            $already_file_status = GeneratedPdfReport::where('report_type', 'swms_report')
                ->where('report_id', $id)
                // ->where('path', $file_url)
                ->first();
            if (file_exists($report_full_path) && $already_file_status) {
                // File exists, return the path
                return $this->success($file_url, 'Report already exists.');
            } else {
                // File doesn't exist or no database record, request regeneration
                return $this->error('Please regenerate the report to download it!', 433);
            }
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS step download error:' . $shortMessage,
                'report_id' => $id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('An error occurred : ' . $shortMessage, 500);
        }
    }

    public function swmsReportPdfFilesManager(Request $request)
    {
        $userTable = $this->getUserTable();
        $query = GeneratedPdfReport::where('report_type', 'swms_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();
        $swmsReports = Swms::whereIn('id', $reportIds)
            ->select('id', 'title')
            ->get()
            ->keyBy('id');
        $pdfReports->transform(function ($report) use ($swmsReports) {
            $report->title = $swmsReports->get($report->report_id)->title ?? 'N/A';
            return $report;
        });
        return $this->withCount($pdfReports, 'Retrieve all records Successfully');
    }

    public function downloadSwmsPdfFile($filename)
    {
        $path = public_path("Files_manager/swms_reports/");
        if (!file_exists($path . $filename)) {
            abort(404, 'SWMS File not found.');
        }
        return response()->download($path . $filename);
    }

    public function swmsReportPublishReport($id)
    {
        $swm = Swms::find($id);
        if (!$swm) {
            return $this->error('Report Not Found please try again.', 433);
        }
        // Check if the user has permission to publish the report
        $userTable = $this->getUserTable();
        if (
            ($userTable === 'customer' && ($swm->customer_id !== auth()->id() || $swm->workspace_id !== auth()->user()->current_workspace_id)) ||
            ($userTable === 'emp' && ($swm->customer_id !== auth()->user()->customer_id || $swm->workspace_id !== auth()->user()->workspace_id))
        ) {
            return $this->error('You do not have access to this report.', 403);
        }
        if ($swm) {
            $swm->published = $swm->published == '1' ? '0' : '1';
            
            // Check if the publishing employee is the site_manager_or_forman (authorised_by equivalent) and report is being published
            if ($swm->published == '1' && $swm->site_manager_or_forman == auth()->user()->id) {
                $swm->approval_status = 3;
                
                storeReportsLogs([
                    'employee_id' => auth()->user()->id,
                    'message' => 'SWMS report approved by site manager/foreman during publish (approval_status: 3)',
                    'report_id' => $id,
                    'report_type' => 'swms_report'
                ]);
            }
            
            $swm->save();
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Report status updated successfully',
                'report_id' =>  0,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return $this->message('Report status updated successfully');
        } else {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Report Not Found please try again.',
                'report_id' =>  0,
                'report_type' => 'swms_report',
                'error_type' => 'Not found error',
            ];
            storeReportsLogs($log);
            return $this->error('Report Not Found please try again.');
        }
    }

    public function swmsReportDownloadPdfRegenerate($id)
    {
        if (!$id) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS Report Download ID is required :',
                'report_id' => 0,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => 'Report ID is Required.'
            ], 422);
        }
        try {
            $swms_data = DB::table('swms')
                ->leftJoin('swms_metas', 'swms.id', '=', 'swms_metas.swms_id')
                ->leftJoin('sites', 'swms.site_id', '=', 'sites.id')
                ->leftJoin('companies', 'swms.company_name', '=', 'companies.id')
                ->leftJoin('emp_personal_details as swms_site_manager_or_forman', 'swms.site_manager_or_forman', '=', 'swms_site_manager_or_forman.emp_id')
                ->leftJoin('emp_personal_details as emp_personal_supervisor_detail', 'sites.supervisor_id', '=', 'emp_personal_supervisor_detail.emp_id')
                ->leftJoin('emp_personal_details as emp_personal_forman_detail', 'sites.forman_id', '=', 'emp_personal_forman_detail.emp_id')
                ->where('swms.id', "=", $id)
                ->select(
                    'swms.*',
                    'sites.title as sites_title',
                    'swms_metas.*',
                    'sites.supervisor_id as site_supervisor_id',
                    'swms_site_manager_or_forman.first_name as swms_site_manager_or_forman_first_name',
                    'swms_site_manager_or_forman.middle_name as swms_site_manager_or_forman_middle_name',
                    'swms_site_manager_or_forman.last_name as swms_site_manager_or_forman_last_name',
                    'companies.name as company.name',
                    'emp_personal_supervisor_detail.first_name as emp_personal_supervisor_detail_f_name',
                    'emp_personal_supervisor_detail.middle_name as emp_personal_supervisor_detail_middle_name',
                    'emp_personal_supervisor_detail.last_name as emp_personal_supervisor_detail_last_name',
                    'emp_personal_forman_detail.first_name as emp_personal_forman_detail_f_name',
                    'emp_personal_forman_detail.middle_name as emp_personal_forman_detail_middle_name',
                    'emp_personal_forman_detail.last_name as emp_personal_forman_detail_last_name',
                )
                ->first();
            $swms_data_forman = DB::table('swms')
                ->leftJoin('swms_metas', 'swms.id', '=', 'swms_metas.swms_id')
                ->leftJoin('companies', 'swms.company_name', '=', 'companies.id')
                ->leftJoin('emp_personal_details as swms_site_manager_or_forman', function ($join) {
                    $join->on(DB::raw("FIND_IN_SET(swms_site_manager_or_forman.emp_id, swms.site_manager_or_forman)"), '>', DB::raw('0'));
                })
                ->where('swms.id', "=", $id)
                ->select(
                    'swms.*',
                    'swms_metas.*',
                    'swms_site_manager_or_forman.first_name as swms_site_manager_or_forman_first_name',
                    'swms_site_manager_or_forman.middle_name as swms_site_manager_or_forman_middle_name',
                    'swms_site_manager_or_forman.last_name as swms_site_manager_or_forman_last_name',
                    'companies.name as name',
                )
                ->get();
                foreach ($swms_data_forman as $forman_item) {
                    $emp_company = EmpCompanyDetails::where('id', $forman_item->site_manager_or_forman)->first();
                    $emp_personal_details = EmpPersonalDetails::where('emp_id', $forman_item->site_manager_or_forman)->first();
                    $role_title = null;
                    if ($emp_company && $emp_company->access_role) {
                        $role_title = Role::where('code', $emp_company->access_role)->first();
                    }
                    // Append role_title to the forman object
                    $forman_item->role_title = $role_title ? $role_title->title : null;
                }
            $swms_developed_bies_data = DB::table('swms_developed_bies')
                ->leftJoin('emp_personal_details as emp_personal_details_developed_bies', 'swms_developed_bies.employee_id', '=', 'emp_personal_details_developed_bies.emp_id')
                ->where('swms_developed_bies.swms_id', "=", $id)
                ->select(
                    'swms_developed_bies.signature as swms_developed_bies_signature',
                    'swms_developed_bies.date as swms_developed_bies_date',
                    'emp_personal_details_developed_bies.first_name as emp_personal_details_developed_bies_first_name',
                    'emp_personal_details_developed_bies.middle_name as emp_personal_details_developed_bies_middle_name',
                    'emp_personal_details_developed_bies.last_name as emp_personal_details_developed_bies_last_name',

                )
                ->get();
            // $swms_approved_bies_data = DB::table('swms_approved_bies')
            //     ->leftJoin('emp_personal_details as emp_personal_details_approved_bies', 'swms_approved_bies.employee_id', '=', 'emp_personal_details_approved_bies.emp_id')
            //     ->where('swms_approved_bies.swms_id', "=", $id)
            //     ->select(
            //         'swms_approved_bies.signature as swms_approved_bies_signature',
            //         'swms_approved_bies.date as swms_approved_bies_date',
            //         'emp_personal_details_approved_bies.first_name as emp_personal_details_approved_bies_first_name',
            //         'emp_personal_details_approved_bies.middle_name as emp_personal_details_approved_bies_middle_name',
            //         'emp_personal_details_approved_bies.last_name as emp_personal_details_approved_bies_last_name',

            //     )
            //     ->get();
            $swms_approved_bies_data = DB::table('swms_approved_bies')
                ->leftJoin('emp_personal_details as emp_personal_details_approved_bies', 'swms_approved_bies.employee_id', '=', 'emp_personal_details_approved_bies.emp_id')
                ->where('swms_approved_bies.swms_id', "=", $id)
                ->select(
                    'swms_approved_bies.signature as swms_approved_bies_signature',
                    'swms_approved_bies.date as swms_approved_bies_date',
                    'emp_personal_details_approved_bies.first_name as emp_personal_details_approved_bies_first_name',
                    'emp_personal_details_approved_bies.middle_name as emp_personal_details_approved_bies_middle_name',
                    'emp_personal_details_approved_bies.last_name as emp_personal_details_approved_bies_last_name',

                )
                ->get();
            $swms_review_responsibles_data = DB::table('swms_review_responsibles')
                ->leftJoin('emp_personal_details as emp_personal_details_review_responsibles', 'swms_review_responsibles.employee_id', '=', 'emp_personal_details_review_responsibles.emp_id')
                ->where('swms_review_responsibles.swms_id', "=", $id)
                ->select(
                    'swms_review_responsibles.signature as swms_review_responsibles_signature',
                    'swms_review_responsibles.date as swms_review_responsibles_date',
                    'emp_personal_details_review_responsibles.first_name as emp_personal_details_review_responsibles_first_name',
                    'emp_personal_details_review_responsibles.middle_name as emp_personal_details_review_responsibles_middle_name',
                    'emp_personal_details_review_responsibles.last_name as emp_personal_details_review_responsibles_last_name',
                )
                ->get();
            $swms_monitoring_data = DB::table('swms_monitoring_responsibles')
                ->leftJoin('emp_personal_details as emp_personal_details_monitoring_responsibles', 'swms_monitoring_responsibles.employee_id', '=', 'emp_personal_details_monitoring_responsibles.emp_id')
                ->where('swms_monitoring_responsibles.swms_id', "=", $id)
                ->select(
                    'swms_monitoring_responsibles.signature as swms_monitoring_responsibles_signature',
                    'swms_monitoring_responsibles.date as swms_monitoring_responsibles_date',
                    'emp_personal_details_monitoring_responsibles.first_name as emp_personal_details_monitoring_responsibles_first_name',
                    'emp_personal_details_monitoring_responsibles.middle_name as emp_personal_details_monitoring_responsibles_middle_name',
                    'emp_personal_details_monitoring_responsibles.last_name as emp_personal_details_monitoring_responsibles_last_name',

                )
                ->get();
            $swms_review_responsibles_data = DB::table('swms_review_responsibles')
                ->leftJoin('emp_personal_details as emp_personal_details_review_responsibles', 'swms_review_responsibles.employee_id', '=', 'emp_personal_details_review_responsibles.emp_id')

                ->where('swms_review_responsibles.swms_id', "=", $id)
                ->select(
                    'swms_review_responsibles.signature as swms_review_responsibles_signature',
                    'swms_review_responsibles.date as swms_review_responsibles_date',

                    'emp_personal_details_review_responsibles.first_name as emp_personal_details_review_responsibles_first_name',
                    'emp_personal_details_review_responsibles.middle_name as emp_personal_details_review_responsibles_middle_name',
                    'emp_personal_details_review_responsibles.last_name as emp_personal_details_review_responsibles_last_name',

                )
                ->get();
            $swms_compliance_responsibles_data = DB::table('swms_compliance_responsibles')
                ->leftJoin('emp_personal_details as emp_personal_details_compliance_responsibles', 'swms_compliance_responsibles.employee_id', '=', 'emp_personal_details_compliance_responsibles.emp_id')

                ->where('swms_compliance_responsibles.swms_id', "=", $id)
                ->select(
                    'swms_compliance_responsibles.signature as swms_compliance_responsibles_signature',
                    'swms_compliance_responsibles.date as swms_compliance_responsibles_date',
                    'emp_personal_details_compliance_responsibles.first_name as emp_personal_details_compliance_responsibles_first_name',
                    'emp_personal_details_compliance_responsibles.middle_name as emp_personal_details_compliance_responsibles_middle_name',
                    'emp_personal_details_compliance_responsibles.last_name as emp_personal_details_compliance_responsibles_last_name',

                )
                ->get();
            $hazard_risks_data = DB::table('swms_hazard_risk_pivots')
                ->leftJoin('hazard_risks as hazard_risks', 'swms_hazard_risk_pivots.hazard_risks_id', '=', 'hazard_risks.id')
                ->where('swms_hazard_risk_pivots.swms_id', "=", $id)
                ->select(
                    'hazard_risks.title as hazard_risks_title',
                    'hazard_risks.description as hazard_risks_description',

                )
                ->get();
            $swms_task_details_data = DB::table('swms_task_details')
                ->leftJoin('emp_personal_details as swms_task_details_personal_details', 'swms_task_details.responsible_preson_id', '=', 'swms_task_details_personal_details.emp_id')

                ->where('swms_task_details.swms_id', "=", $id)
                ->select(
                    'swms_task_details.*',
                    'swms_task_details_personal_details.first_name as swms_task_details_personal_details_first_name',
                    'swms_task_details_personal_details.middle_name as swms_task_details_personal_details_middle_name',
                    'swms_task_details_personal_details.last_name as swms_task_details_personal_details_last_name',

                )
                ->get();
            $swms_protection_tool_pivots_data = DB::table('swms_protection_tool_pivots')
                ->leftJoin('swms_protection_tools', 'swms_protection_tool_pivots.protection_tool_id', '=', 'swms_protection_tools.id')
                ->where('swms_protection_tool_pivots.swms_id', "=", $id)
                ->select(
                    'swms_protection_tools.*',
                )
                ->get();
            $swms_safety_planning_answers_data = DB::table('swms_safety_planning_answers')
                ->leftJoin('swms_safety_planning_questions', 'swms_safety_planning_answers.swms_safety_planning_id', '=', 'swms_safety_planning_questions.id')
                ->where('swms_safety_planning_answers.swms_id', "=", $id)
                ->select(
                    'swms_safety_planning_questions.*',
                    'swms_safety_planning_answers.answer as swms_safety_planning_answers_answer'
                )
                ->get();
            $swms_questions_answers_data = DB::table('swms_awnswers')
                ->leftJoin('swms_questions', 'swms_awnswers.swms_question_id', '=', 'swms_questions.id')
                ->where('swms_awnswers.swms_id', "=", $id)
                ->select(
                    'swms_questions.*',
                    'swms_awnswers.*'
                )
                ->get();

            $swms_general_notes_data = DB::table('swms_general_note_answers')
                ->leftJoin('swms_general_notes', 'swms_general_note_answers.swms_general_notes_id', '=', 'swms_general_notes.id')
                ->where('swms_general_note_answers.swms_id', "=", $id)
                ->select(
                    'swms_general_notes.*',
                    'swms_general_note_answers.*'

                )
                ->get();
            
            // Format dates using BaseModel's date formatting methods
            // Get user's preferred date format using BaseModel
            $baseModel = new Swms();
            $userDateFormat = $baseModel->getUserDateFormat();
            
            // Format date fields in swms_data
            // Format start_date
            if (isset($swms_data->start_date) && $swms_data->start_date) {
                try {
                    $parsedDate = $baseModel->safeDateParse($swms_data->start_date, 'start_date');
                    if ($parsedDate instanceof \Carbon\Carbon) {
                        $swms_data->start_date = $parsedDate->format($userDateFormat);
                    }
                } catch (\Exception $e) {
                    // Keep original value if parsing fails
                }
            }
            
            // Format swms_approved_bies_date
            foreach ($swms_approved_bies_data as $item) {
                if (isset($item->swms_approved_bies_date) && $item->swms_approved_bies_date) {
                    try {
                        $parsedDate = $baseModel->safeDateParse($item->swms_approved_bies_date, 'swms_approved_bies_date');
                        if ($parsedDate instanceof \Carbon\Carbon) {
                            $item->swms_approved_bies_date = $parsedDate->format($userDateFormat);
                        }
                    } catch (\Exception $e) {
                        // Keep original value if parsing fails
                    }
                }
            }
            
            // Format swms_developed_bies_date
            foreach ($swms_developed_bies_data as $item) {
                if (isset($item->swms_developed_bies_date) && $item->swms_developed_bies_date) {
                    try {
                        $parsedDate = $baseModel->safeDateParse($item->swms_developed_bies_date, 'swms_developed_bies_date');
                        if ($parsedDate instanceof \Carbon\Carbon) {
                            $item->swms_developed_bies_date = $parsedDate->format($userDateFormat);
                        }
                    } catch (\Exception $e) {
                        // Keep original value if parsing fails
                    }
                }
            }
            
            // Format swms_review_responsibles_date
            foreach ($swms_review_responsibles_data as $item) {
                if (isset($item->swms_review_responsibles_date) && $item->swms_review_responsibles_date) {
                    try {
                        $parsedDate = $baseModel->safeDateParse($item->swms_review_responsibles_date, 'swms_review_responsibles_date');
                        if ($parsedDate instanceof \Carbon\Carbon) {
                            $item->swms_review_responsibles_date = $parsedDate->format($userDateFormat);
                        }
                    } catch (\Exception $e) {
                        // Keep original value if parsing fails
                    }
                }
            }
            
            // Format swms_monitoring_responsibles_date
            foreach ($swms_monitoring_data as $item) {
                if (isset($item->swms_monitoring_responsibles_date) && $item->swms_monitoring_responsibles_date) {
                    try {
                        $parsedDate = $baseModel->safeDateParse($item->swms_monitoring_responsibles_date, 'swms_monitoring_responsibles_date');
                        if ($parsedDate instanceof \Carbon\Carbon) {
                            $item->swms_monitoring_responsibles_date = $parsedDate->format($userDateFormat);
                        }
                    } catch (\Exception $e) {
                        // Keep original value if parsing fails
                    }
                }
            }
            
            // Format swms_compliance_responsibles_date
            foreach ($swms_compliance_responsibles_data as $item) {
                if (isset($item->swms_compliance_responsibles_date) && $item->swms_compliance_responsibles_date) {
                    try {
                        $parsedDate = $baseModel->safeDateParse($item->swms_compliance_responsibles_date, 'swms_compliance_responsibles_date');
                        if ($parsedDate instanceof \Carbon\Carbon) {
                            $item->swms_compliance_responsibles_date = $parsedDate->format($userDateFormat);
                        }
                    } catch (\Exception $e) {
                        // Keep original value if parsing fails
                    }
                }
            }
            
            $supervisorIds = explode(',', $swms_data->site_supervisor_id);
            $supervisors = DB::table('emp_personal_details')->whereIn('emp_id', $supervisorIds)
                ->select(
                    'emp_personal_details.first_name as emp_personal_supervisor_detail_f_name',
                    'emp_personal_details.last_name as emp_personal_supervisor_detail_last_name'
                )
                ->get();
            // Generate filename for reference (optional)
            $report_title = isset($swms_data->title)
                ? preg_replace('/[^A-Za-z0-9_]+/', '_', trim(str_replace(' ', '_', $swms_data->title)))
                : 'No_named';
            $report_swms_number = isset($swms_data->swms_number)
                ? preg_replace('/[^A-Za-z0-9_]+/', '', trim(str_replace(' ', '_', $swms_data->swms_number)))
                : 'NO_Swms';
            $report_version_number = isset($swms_data->version_number)
                ? preg_replace('/[^A-Za-z0-9_]+/', '', trim(str_replace(' ', '_', $swms_data->version_number)))
                : 'No_Version';
            $filename = $report_title . "N" . $report_swms_number . "R" . $report_version_number . ".pdf";
            if($swms_data->report_method == 1){
                $swms_upload_report=GeneratedPdfReport::where('report_id', $id)->where('report_type', 'swms_report')->first();
            }
            else{
                GeneratedPdfReport::updateOrCreate(
                    [
                        'report_id' => $id,
                        'report_type' => 'swms_report'
                    ],
                    [
                        'report_id' => $id,
                        'path' => null,
                        'report_type' => 'swms_report',
                    ]
                );
                $swms_upload_report=null;
            }
            $swms_signoffs = DB::table('swms_signatures')
            ->where('swms_id', $id)
            ->select('emp_id', 'signatures', 'inductance_date')
            ->get();
        $swms_signoffs_array = [];
        foreach ($swms_signoffs as $signoff) {
            $emp_company = EmpCompanyDetails::where('id', $signoff->emp_id)->first();
            $emp_personal_details = EmpPersonalDetails::where('emp_id', $signoff->emp_id)->first();
            $role_title = null;
            if ($emp_company && $emp_company->access_role) {
                $role_title = Role::where('code', $emp_company->access_role)->first();
            }
            $swms_signoffs_array[] = [
                'employee_name' => ($emp_personal_details ? ($emp_personal_details->first_name ?? '') . ' ' . 
                ($emp_personal_details->middle_name ?? '') . ' ' . 
                ($emp_personal_details->last_name ?? '') : 'Unknown Employee'),
                'role_title' => $role_title ? $role_title->title : null,
                'signatures' => $signoff->signatures,
                'inductance_date' => $signoff->inductance_date,
            ];
        }
            $data = [
                'swms_data' => $swms_data,
                'report_info' => [
                    'title' => $swms_data->title ?? 'No Title',
                    'swms_number' => $swms_data->swms_number ?? 'No SWMS Number',
                    'version_number' => $swms_data->version_number ?? 'No Version',
                    'suggested_filename' => $filename
                ],
                'swms_developed_bies_data' => $swms_developed_bies_data,
                'swms_approved_bies_data' => $swms_approved_bies_data,
                'swms_review_responsibles_data' => $swms_review_responsibles_data,
                'swms_monitoring_data' => $swms_monitoring_data,
                'swms_compliance_responsibles_data' => $swms_compliance_responsibles_data,
                'hazard_risks_data' => $hazard_risks_data,
                'swms_task_details_data' => $swms_task_details_data,
                'swms_protection_tool_pivots_data' => $swms_protection_tool_pivots_data,
                'swms_safety_planning_answers_data' => $swms_safety_planning_answers_data,
                'swms_data_forman' => $swms_data_forman,
                'swms_questions_answers_data' => $swms_questions_answers_data,
                'swms_general_notes_data' => $swms_general_notes_data,
                'supervisors' => $supervisors,
                'swms_upload_report' => $swms_upload_report,
                'swms_signoffs' => $swms_signoffs_array
            ];
            return $this->success($data, 'SWMS Report Data Retrieved Successfully.');
        } catch (Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'SWMS step download error:' . $shortMessage,
                'report_id' =>  $id,
                'report_type' => 'swms_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => 'An error occurred : ' . $shortMessage,
            ], 500);
        }
    }

    public function swmsReportViewSignature($id)
    {

        $swms = Swms::find($id);
        if (!$swms) {
            return $this->error('Report Not Found please try again.', 433);
        }
        // Check if the user has permission to view the report
        $userTable = $this->getUserTable();
        if (
            ($userTable === 'customer' && ($swms->customer_id !== auth()->id() || $swms->workspace_id !== auth()->user()->current_workspace_id)) ||
            ($userTable === 'emp' && ($swms->customer_id !== auth()->user()->customer_id || $swms->workspace_id !== auth()->user()->workspace_id))
        ) {
            return $this->error('You do not have access to this report.', 403);
        }

        // Use Eloquent model to get formatted dates
        $swms_data = Swms::find($id);

        // Get foreman data using raw query but convert to array for consistency
        $swms_data_forman = DB::table('swms')
            ->leftJoin('emp_personal_details as authorised_by', function ($join) {
                $join->on(DB::raw("FIND_IN_SET(authorised_by.emp_id, swms.site_manager_or_forman)"), '>', DB::raw('0'));
            })
            ->where('swms.id', "=", $id)
            ->select(
                'swms.*',
                'authorised_by.first_name as first_name',
                'authorised_by.last_name as last_name'
            )
            ->first();


        // 1. Get signatures from SwmsSignature table
        $swms_signatures = SwmsSignature::where('swms_id', $id)
            ->with('employee', 'empPersonalDetails')
            ->get()
            ->map(function ($signature) use ($swms_data) {
                // Add role title based on employee's access_role code
                if ($signature->emp_id) {
                    // First get the employee to find their access_role (role code)
                    $employee = EmpCompanyDetails::where('id', $signature->emp_id)
                        ->where('customer_id', $swms_data->customer_id)
                        ->where('workspace_id', $swms_data->workspace_id)
                        ->first();

                    if ($employee && $employee->access_role) {
                        // Now find the role using the role code
                        $role = Role::where('code', $employee->access_role)
                            ->where('del', '0')
                            ->first();

                        $signature->setAttribute('role', $employee->access_role);
                        $signature->setAttribute('role_title', $role ? $role->title : null);
                    } else {
                        $signature->setAttribute('role', null);
                        $signature->setAttribute('role_title', null);
                    }
                } else {
                    $signature->setAttribute('role', null);
                    $signature->setAttribute('role_title', null);
                }

                // Format inductance date
                if (isset($signature->inductance_date) && $signature->inductance_date) {
                    try {
                        $carbonDate = \Carbon\Carbon::parse($signature->inductance_date);
                        $signature->inductance_date = $carbonDate->format($swms_data->getUserDateFormat());
                    } catch (\Exception $e) {
                        // Keep original value if parsing fails
                    }
                }

                // Add source identifier
                $signature->setAttribute('signature_source', 'swms_signatures');
                $signature->setAttribute('employee_id', $signature->emp_id);

                return $signature;
            });

        // Convert to collection for easier manipulation
        $swmsSignatures = collect($swms_signatures);

        // Check if site_manager_or_forman employees are already in the signoff data
        $siteManagerIds = [];
        if ($swms_data->site_manager_or_forman) {
            $siteManagerIds = explode(',', $swms_data->site_manager_or_forman);
        }
        
        $siteManagerInSignoffs = false;
        foreach ($siteManagerIds as $siteManagerId) {
            $siteManagerId = trim($siteManagerId);
            if ($siteManagerId && $siteManagerId != '0' && $swmsSignatures->contains('emp_id', $siteManagerId)) {
                $siteManagerInSignoffs = true;
                break;
            }
        }

        // If site_manager_or_forman employees are not in signoffs table, add them with null signature
        if (!$siteManagerInSignoffs && !empty($siteManagerIds)) {
            foreach ($siteManagerIds as $siteManagerId) {
                $siteManagerId = trim($siteManagerId);
                if (!$siteManagerId || $siteManagerId == '0') {
                    continue;
                }
                
                // Check if this specific site manager is already in signatures
                if ($swmsSignatures->contains('emp_id', $siteManagerId)) {
                    continue;
                }
                
                // Fetch site_manager_or_forman employee details
                $siteManagerDetails = DB::table('emp_personal_details')
                    ->leftJoin('emp_company_details', 'emp_personal_details.emp_id', '=', 'emp_company_details.id')
                    ->leftJoin('roles', 'emp_company_details.access_role', '=', 'roles.code')
                    ->where('emp_personal_details.emp_id', $siteManagerId)
                    ->where('emp_personal_details.del', '0')
                    ->where('emp_company_details.status', '1')
                    ->where('emp_company_details.approved', '1')
                    ->where('emp_company_details.compeleted', '1')
                    ->where('emp_company_details.customer_id', $swms_data->customer_id)
                    ->where('emp_company_details.workspace_id', $swms_data->workspace_id)
                    ->where('roles.del', '0')
                    ->select(
                        'emp_personal_details.emp_id',
                        'emp_personal_details.first_name',
                        'emp_personal_details.middle_name',
                        'emp_personal_details.last_name',
                        'emp_company_details.access_role',
                        'roles.title as role_title'
                    )->first();

            if ($siteManagerDetails) {
                // Create complete array structure for site_manager_or_forman to match existing signoff format
                $siteManagerSignoffArray = [
                    'id' => null,
                    'swms_id' => $swms_data->id,
                    'role_code' => $siteManagerDetails->access_role,
                    'emp_id' => $siteManagerId,
                    'name' => trim(($siteManagerDetails->first_name ?? '') . ' ' . 
                             ($siteManagerDetails->middle_name ?? '') . ' ' . 
                             ($siteManagerDetails->last_name ?? '')),
                    'signatures' => null, // Null indicates signature is required
                    'inductance_date' => $swms_data->issue_date,
                    'created_at' => null,
                    'updated_at' => null,
                    'role' => $siteManagerDetails->access_role,
                    'role_title' => $siteManagerDetails->role_title,
                    'signature_source' => 'swms_signatures',
                    'employee_id' => $siteManagerId,
                    'employee' => [
                        'emp_id' => (string) $siteManagerDetails->emp_id,
                        'first_name' => $siteManagerDetails->first_name,
                        'middle_name' => $siteManagerDetails->middle_name,
                        'last_name' => $siteManagerDetails->last_name,
                        'laravel_through_key' => $siteManagerDetails->emp_id
                    ],
                    'emp_personal_details' => [
                        'emp_id' => (string) $siteManagerDetails->emp_id,
                        'first_name' => $siteManagerDetails->first_name,
                        'middle_name' => $siteManagerDetails->middle_name,
                        'last_name' => $siteManagerDetails->last_name,
                        'laravel_through_key' => $siteManagerDetails->emp_id
                    ]
                ];

                // Add to signoff collection
                $swmsSignatures->push((object) $siteManagerSignoffArray);
            }
            }
        }




        $swms_data->forman_list = $swms_data_forman;

        // Apply pagination to signatures if requested
        $page = (int) request()->get('page', 1);
        $perPage = (int) request()->get('per_page', 10);
        
        $total = $swmsSignatures->count();
        $paginatedSignatures = $swmsSignatures->values()->forPage($page, $perPage);
        $lastPage = ceil($total / $perPage);
        
        // Build pagination metadata
        $currentParams = request()->query();
        $nextPageUrl = $page < $lastPage ? 
            request()->fullUrlWithQuery(array_merge($currentParams, ['page' => $page + 1])) : null;
        $prevPageUrl = $page > 1 ? 
            request()->fullUrlWithQuery(array_merge($currentParams, ['page' => $page - 1])) : null;
        
        $paginationMeta = [
            'total' => $total,
            'per_page' => $perPage,
            'current_page' => $page,
            'last_page' => $lastPage,
            'has_more_pages' => $page < $lastPage ? true : false,
            'from' => $total > 0 ? (($page - 1) * $perPage + 1) : null,
            'to' => $total > 0 ? min($page * $perPage, $total) : null
        ];

        $data = [
            'swms_data' => $swms_data,
            'swms_signatures' => array_values($paginatedSignatures->toArray()),
            'pagination' => $paginationMeta,
        ];
        return $this->success($data, 'Signatures retrieved successfully.');
    }

    public function swmsStep7Store(Request $request)
    {
        $isUpdate = $request->swms_report_id;
        $message = $isUpdate ? 'Updated Successfully' : 'Saved Successfully';
        try {
            $data = [
                'status' => 1,
            ];
            // Update or create the SWMS record
            Swms::where('id', $request->swms_report_id)->update(['process' => '1']);

            $data['swms_report_id'] = "";
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Swms  Step 5 :' . $message,
                'report_id' =>   $request->swms_report_id,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => $message,
                'data' => $data,
            ], 200);
        } catch (\Exception $e) {
            // Handle exceptions and return an error response
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Swms Step 5 error:' . $shortMessage,
                'report_id' =>  $request->swms_report_id,
                'report_type' => 'swms_report'
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => 'An error occurred while saving  data: ' . $e->getMessage(),
            ], 500);
        }
    }

    public function getImages(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS  Step 3 store:' . $validator->errors()->first(),
                'report_id' =>   $request->swms_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => $validator->errors()->first()
            ], 422);
        }
        $images = SwmsImage::where('swms_id', $request->swms_report_id)->get();
        return response()->json([
            'success' => 'Image uploaded successfully!',
            'images' => $images  // List of all images
        ]);
    }

    public function imageStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'swms_report_id' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',

        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'WHS  Step 3 store:' . $validator->errors()->first(),
                'report_id' =>   $request->whs_report_id,
                'report_type' => 'swms_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return response()->json([
                'message' => $validator->errors()->first()
            ], 422);
        }
        $imagePath = $request->file('image')->store('images', 'public');
        // Save the image path in the database
        $image = new SwmsImage();
        $image->image = $imagePath;
        $image->swms_id = $request->swms_report_id;
        $image->save();
        // Fetch all images from the database to return the updated list
        $images = SwmsImage::where('swms_id', $request->swms_report_id)->get();
        // Return a JSON response with the uploaded image URL and the updated image list
        return response()->json([
            'success' => 'Image uploaded successfully!',
            'image_url' => asset('storage/' . $imagePath),
            'images' => $images  // List of all images
        ]);
    }

    public function deleteImage($id)
    {
        $image = SwmsImage::find($id);
        if (!$image) {
            return response()->json(['success' => false, 'message' => 'Image not found.']);
        }
        $imagePath = storage_path('app/public/' . $image->image);
        if (file_exists($imagePath)) {
            unlink($imagePath);  // Delete the file
        }
        $image->delete();
        return response()->json(['success' => true]);
    }
}
