<?php

namespace App\Http\Controllers;

use PDF;
use Exception;
use App\Models\Role;
use App\Models\Sites;
use App\Models\Project;
use Illuminate\Http\Request;
use App\Models\IncidentReport;
use App\Models\InspectionPlan;
use Illuminate\Support\Facades\Log;
// use Spatie\Browsershot\Browsershot;
use App\Models\InspectionImage;
use App\Models\EmpCompanyDetails;
use App\Models\GeneratedPdfReport;
use App\Models\InspectionPlanMeta;
use Illuminate\Support\Facades\DB;
use App\Models\InspectionPlanTable;
use App\Models\EmpPersonalDetails;
use App\Models\EmpType;
use App\Models\InspectionPlanGeneral;
use App\Models\InspectionPlanChecklist;
use App\Models\InspectionPlanSignature;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Illuminate\Pagination\LengthAwarePaginator;

class InspectionPlanController extends Controller
{

    public function index(Request $request)
    {
        try {
            $userTable = $this->getUserTable();
            $authId = auth()->user()->id;
            $query = InspectionPlan::query();
            $query->orderBy('id', 'desc')
                ->where('del', '0')
                ->with('authorizedBy');
            if ($userTable === 'customer') {
                $customerSites = Sites::where('customer_id', $authId)
                    ->where('active', 1)
                    ->where('del', 0)
                    ->where('workspace_id', auth()->user()->current_workspace_id)
                    ->pluck('id');
                $query->whereIn('site_id', $customerSites);
            }
            if ($userTable === 'emp') {
                $sites = Sites::where('customer_id', auth()->user()->customer_id)
                    ->where('workspace_id', auth()->user()->workspace_id)
                    ->where('sso_id', $authId)
                    ->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);
            }

            // Apply single search filter
            if ($request->has('search') && !empty($request->search)) {
                $searchTerm = $request->search;
                $query->where(function ($q) use ($searchTerm) {
                    // Search in title
                    $q->where('title', 'like', '%' . $searchTerm . '%')
                        // Search in document number
                        ->orWhere('document_number', 'like', '%' . $searchTerm . '%')
                        // Search in authorised by name using applyNameSearch
                        ->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 . '%');
                            });
                        });
                });
            }

            $queryResult = $query->get();
            // Attach generated report URL to each incident report
            foreach ($queryResult as $report) {
                $generatedReport = GeneratedPdfReport::where([
                    ['report_type', 'inspection_report'],
                    ['report_id', $report->id]
                ])->first();
                $report->generated_report_url = $generatedReport ? $generatedReport->path : null;
            }
           
            return $this->withCount($queryResult, 'Get Incident Reports List Successfully');
        } catch (\Exception $e) {
            return $this->error('Error occurred while fetching records: ' . $e->getMessage());
        }
    }



    public function destroy($id)
    {
        $userTable = $this->getUserTable(); // Get user type (customer or emp)
        $inspectionPlan = InspectionPlan::where('id', $id)->where('del', '0')->first();
        if (!$inspectionPlan) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection Plan Delete Failed: ID ' . $id . ' not found',
                'report_id' => $id ?? 0,
                'report_type' => 'inspection_report',
                'error_type' => 'Not found error'
            ];
            storeReportsLogs($log);
            return $this->message('Inspection Plan not found or already deleted', 404);
        }
        if ($userTable === 'customer' && ($inspectionPlan->customer_id != auth()->id() || $inspectionPlan->workspace_id != auth()->user()->current_workspace_id)) {
            return $this->message('Unauthorized access to this inspection plan', 403);
        }
        if ($userTable === 'emp' && ($inspectionPlan->customer_id != auth()->user()->customer_id || $inspectionPlan->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('Unauthorized access to this inspection plan', 403);
        }
        $status = $inspectionPlan->update(['del' => '1']);
        if (!$status) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection Plan Delete Failed: ID ' . $id,
                'report_id' => $id ?? 0,
                'report_type' => 'inspection_report',
                'error_type' => 'Update failed'
            ];
            storeReportsLogs($log);
            return $this->message('Inspection Plan delete failed. Please try again.', 500);
        }
        $log = [
            'employee_id' => auth()->user()->id,
            'message' => 'Inspection Plan Deleted: ID ' . $id . ' successfully',
            'report_id' => $id ?? 0,
            'report_type' => 'inspection_report'
        ];
        storeReportsLogs($log);
        return $this->message('Inspection Plan deleted successfully');
    }

    public function destroySignature($id)
    {
        try {
            $signature = InspectionPlanSignature::where('id', $id)->where('del', '0')->first();
            if (!$signature) {
                $log = [
                    'employee_id' => auth()->user()->id,
                    'message' => 'Inspection Plan Signature Deletion Failed: ID ' . $id . ' not found',
                    'report_id' => $id ?? 0,
                    'report_type' => 'inspection_report',
                    'error_type' => 'Not found error',
                ];
                storeReportsLogs($log);
                return $this->message('Inspection Plan Signature not found or already deleted', 404);
            }
            $userTable = $this->getUserTable();
            $inspectionPlan = InspectionPlan::find($signature->inspection_plan_id);
            if (!$inspectionPlan) {
                return $this->message('Associated Inspection Plan not found', 404);
            }
            if ($userTable === 'customer' && ($inspectionPlan->customer_id != auth()->id() || $inspectionPlan->workspace_id != auth()->user()->current_workspace_id)) {
                return $this->message('Unauthorized access to this inspection plan signature', 403);
            }
            if ($userTable === 'emp' && ($inspectionPlan->customer_id != auth()->user()->customer_id || $inspectionPlan->workspace_id != auth()->user()->workspace_id)) {
                return $this->message('Unauthorized access to this inspection plan signature', 403);
            }
            $status = $signature->update(['del' => '1']);
            if (!$status) {
                $log = [
                    'employee_id' => auth()->user()->id,
                    'message' => 'Inspection Plan Signature Deletion Failed: ID ' . $id,
                    'report_id' => $id ?? 0,
                    'report_type' => 'inspection_report',
                    'error_type' => 'Update failed',
                ];
                storeReportsLogs($log);
                return $this->message('Failed to delete signature. Please try again.', 500);
            }
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection Plan Signature Deleted: ID ' . $id . ' successfully',
                'report_id' => $id ?? 0,
                'report_type' => 'inspection_report',
            ];
            storeReportsLogs($log);
            return $this->message('Signature deleted successfully');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection Signature Deletion error: ' . $shortMessage,
                'report_id' => $id ?? 0,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error',
            ];
            storeReportsLogs($log);
            return $this->message($shortMessage, 422);
        }
    }

    public function copyInspectionPlanReport($old_inspection_plan_report_id)
    {
        $old_inspection_plan_report_id = $old_inspection_plan_report_id;

        try {
            $old_inspection_plan = InspectionPlan::find($old_inspection_plan_report_id);
            if (!$old_inspection_plan) {
                return $this->message('Original inspection plan not found', 422);
            }
            $userTable = $this->getUserTable();
            $customer_id = null;
            $workspace_id = null;
            if ($userTable === 'customer' && ($old_inspection_plan->customer_id !== auth()->id() || $old_inspection_plan->workspace_id !== auth()->user()->current_workspace_id)) {
                $customer_id = auth()->id();
                $workspace_id = auth()->user()->current_workspace_id;
                return $this->message('You do not have access to this report.', 403);
            }
            if ($userTable === 'emp' && ($old_inspection_plan->customer_id !== auth()->user()->customer_id || $old_inspection_plan->workspace_id !== auth()->user()->workspace_id)) {
                $customer_id = auth()->user()->customer_id;
                $workspace_id = auth()->user()->workspace_id;
                return $this->message('You do not have access to this report.', 403);
            }
            $revision_data = $this->generateRevisionNumber($old_inspection_plan_report_id);
            $new_inspection_plan = $old_inspection_plan->replicate();
            $new_inspection_plan->revision_number = $revision_data['revision_number'];
            $new_inspection_plan->parent_number = $old_inspection_plan_report_id;
            $new_inspection_plan->is_published = '0';
            $new_inspection_plan->save();
            $new_inspection_plan_id = $new_inspection_plan->id;
            $copy_result = $this->copyInspectionPlanReportData($old_inspection_plan_report_id, $new_inspection_plan_id);
            $new_inspection_plan->approval_status = 0;
            $new_inspection_plan->save();
            // if (!$copy_result) {
            //     return $this->message('Failed to duplicate inspection plan report data', 422);
            // }
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan copied successfully from ID: ' . $old_inspection_plan_report_id . ' to new ID: ' . $new_inspection_plan_id,
                'report_id' => $new_inspection_plan_id,
                'report_type' => 'inspection_report'
            ];
            storeReportsLogs($log);
            return $this->success([
                'new_inspection_plan_id' => $new_inspection_plan_id,
                'revision_number' => $revision_data['revision_number']
            ], 'Inspection Plan Report duplicated successfully');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan copy error: ' . $shortMessage,
                'report_id' => $old_inspection_plan_report_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error('Failed to duplicate inspection plan: ' . $shortMessage);
        }
    }

    private function copyInspectionPlanReportData($old_inspection_plan_report_id, $new_inspection_plan_id)
    {
        if (!$old_inspection_plan_report_id) {
            return false;
        }
        // Fetch the checklist associated with the old inspection plan
        $inspection_plan_checklist = InspectionPlanChecklist::where('inspection_plan_id', $old_inspection_plan_report_id)->get();
        // Check if there are any checklist items
        // if ($inspection_plan_checklist->isEmpty()) {
        //     return false;
        // }
        // Duplicate each checklist item
        foreach ($inspection_plan_checklist as $checklist) {
            $checklistClone = $checklist->replicate();
            $checklistClone->inspection_plan_id = $new_inspection_plan_id;
            $checklistClone->save();
            $new_checklist_id = $checklistClone->id;
            $inspection_general_data = InspectionPlanGeneral::where('inspection_plan_id', $old_inspection_plan_report_id)
                ->where('iptc_id', $checklist->id) // Use current checklist ID
                ->get();
            foreach ($inspection_general_data as $general) {
                $generalClone = $general->replicate();
                $generalClone->inspection_plan_id = $new_inspection_plan_id;
                $generalClone->iptc_id = $new_checklist_id; // Update with new checklist ID
                $generalClone->save();
            }
            $inspection_plan_meta = InspectionPlanMeta::where('itpc_id', $checklist->id) // Use current checklist ID
                ->where('inspection_plan_id', $old_inspection_plan_report_id)
                ->where('is_table', 0)
                ->get();
            foreach ($inspection_plan_meta as $meta) {
                $metaClone = $meta->replicate();
                $metaClone->inspection_plan_id = $new_inspection_plan_id;
                $metaClone->itpc_id = $new_checklist_id; // Update with new checklist ID
                $metaClone->save();
            }
            $inspection_plan_signatures = InspectionPlanSignature::where('inspection_plan_id', $old_inspection_plan_report_id)
                ->where('itpc_id', $checklist->id)
                ->where('del', 0)
                ->get();
            foreach ($inspection_plan_signatures as $signature) {
                $signatureClone = $signature->replicate();
                $signatureClone->inspection_plan_id = $new_inspection_plan_id;
                $signatureClone->itpc_id = $new_checklist_id; // Update with new checklist ID
                $signatureClone->save();
            }
            return true;
        }
    }

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

    public function saveStep1(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required',
            'title' => 'required|string|max:255',
            'document_number' => 'nullable',
            'authorised_by' => 'required|integer',
            'site_id' => 'required',
        ], [
            'document_number.integer' => 'The document number must be an integer.',
            'site_id.required' => 'Site is required',
        ]);
        if ($request->inspection_plan_id === "0") {
            $validator_date = Validator::make($request->all(), [
                'issue_date' => 'nullable|date|after_or_equal:today',
                'revision_date' => 'nullable|date|after_or_equal:issue_date',
            ]);
            if ($validator_date->fails()) {
                return $this->message($validator_date->errors()->first(), 422);
            }
        }
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection step 1 error: ' . $validator->errors()->first(),
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Validation error'
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $validatedData = $validator->validated();
            $msg = 'Saved Successfully';
            $userTable = $this->getUserTable(); // Get the user type (customer or emp)
            if ($userTable == "customer") {
                $validatedData['customer_id'] = auth()->id();
                $validatedData['workspace_id'] = auth()->user()->current_workspace_id;
            } elseif ($userTable == "emp") {
                $validatedData['customer_id'] = auth()->user()->customer_id;
                $validatedData['workspace_id'] = auth()->user()->workspace_id;
            }
            $inspection_plan_data = [
                'title' => $validatedData['title'],
                'document_number' => $validatedData['document_number'],
                'authorised_by' => $validatedData['authorised_by'] ?? null,
                'revision_number' => $this->generateRevisionNumber()['revision_number'],
                'customer_id' => $validatedData['customer_id'],
                'workspace_id' => $validatedData['workspace_id'],
                'issue_date' => $request->issue_date ?? null,
                'revision_date' => $request->revision_date ?? null,
                'site_id' => $request->site_id ?? 0,
            ];
            if (DB::table('inspection_plans')->where('id', $validatedData['inspection_plan_id'])->count() == 0) {
                $validatedData['inspection_plan_id'] = DB::table('inspection_plans')->insertGetId($inspection_plan_data);
                $msg = 'Saved Successfully';
            } else {
                DB::table('inspection_plans')->where('id', $validatedData['inspection_plan_id'])->update($inspection_plan_data);
            }
            $data['inspection_plan_id'] = $validatedData['inspection_plan_id'];
            if ($validatedData['authorised_by']) {
                $user_authorized_by = EmpCompanyDetails::with(['EmpPersonalDetails', 'accessRole', 'accessTier'])
                    ->find($validatedData['authorised_by']);
                $access_role = $user_authorized_by->accessRole->code ?? null;
                $inspection_isignoff_data = [
                    'inspection_plan_id' => $validatedData['inspection_plan_id'],
                    'employee_type' => $access_role,
                    'employee_id' => $validatedData['authorised_by'],
                ];
                // DB::table('inspection_plan_signatures')->updateOrInsert(
                //     [
                //         'inspection_plan_id' => $validatedData['inspection_plan_id'],
                //         'employee_id' => $validatedData['authorised_by'],
                //         'date' => date('Y-m-d'),
                //         'employee_name' => $user_authorized_by->EmpPersonalDetails->first_name . ' ' . $user_authorized_by->EmpPersonalDetails->middle_name . ' ' . $user_authorized_by->EmpPersonalDetails->last_name,
                //         'created_at' => now(),
                //         'updated_at' => now(),
                //     ],
                //     $inspection_isignoff_data
                // );
            }
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection step 1: ' . $msg,
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report'
            ];
            storeReportsLogs($log);
            return $this->success($data, $msg);
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection step 1 error: ' . $shortMessage,
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->message($shortMessage, 422);
        }
    }

    public function editStep1(Request $request)
    {
        $userTable = $this->getUserTable();
        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required'
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection step 1 edit error: ' . $validator->errors()->first(),
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Validation error'
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        $validatedData = $validator->validated();
        try {
            $userTable = $this->getUserTable();
            if ($userTable === "emp") {
                $employee = EmpCompanyDetails::find(auth()->user()->id);
                $customer_id = $employee->customer_id;
                $workspace_id = $employee->workspace_id;
            } elseif ($userTable === "customer") {
                $employee = User::find(auth()->user()->id);
                $customer_id = $employee->id;
                $workspace_id = $employee->current_workspace_id;
            }
            $inspectionPlans = InspectionPlan::with('siteData')
                ->where('id', $validatedData['inspection_plan_id'])
                ->first();
            if (!$inspectionPlans) {
                return $this->message('Inspection Plan not found', 404);
            }
            if (
                $userTable == "customer" && (
                    $inspectionPlans->workspace_id != auth()->user()->current_workspace_id ||
                    $inspectionPlans->customer_id != auth()->id()
                )
            ) {
                return $this->message('You do not have access to this project', 403);
            }
            if (
                $userTable == "emp" && (
                    $inspectionPlans->customer_id != auth()->user()->customer_id ||
                    $inspectionPlans->workspace_id != auth()->user()->workspace_id
                )
            ) {
                return $this->message('You do not have access to this project', 403);
            }
            $empList = EmpCompanyDetails::where('compeleted', '1')
                ->where('approved', '1')
                ->where('status', '1')
                ->where('customer_id', $customer_id)
                ->where('workspace_id', $workspace_id)
                ->where('del', '0')
                ->with([
                    'empPersonalDetails' => fn($query) => $query->select('emp_id', 'first_name', 'middle_name', 'last_name'),
                    'accessRole' => fn($query) => $query->select('id', 'title', 'code'),
                    'empTier' => fn($query) => $query->select('id', 'title'),
                    'accessTier' => fn($query) => $query->select('id', 'title', 'tier_key'),
                ])
                ->select('id', 'access_role', 'tier_id')
                ->whereIn('tier_id', fn($query) => $query->select('id')
                    ->from('tiers')
                    ->whereIn('tier_key', ['B-1', 'B-2', 'B-3']))
                ->get();
            $authorisedByList = $empList;
            $data = [];
            if ($validatedData['inspection_plan_id'] == 0) {
                $data['sites'] = DB::table('sites')
                    ->where('del', '0')
                    ->where('customer_id', $customer_id)
                    ->where('workspace_id', $workspace_id)
                    ->where('active', '1')
                    ->get(['id', 'title']);
            }
            if ($validatedData['inspection_plan_id'] != 0) {
                $inspectionPlan = InspectionPlan::with('siteData')
                    ->where('id', $validatedData['inspection_plan_id'])
                    ->first();
                $data['sites'] = DB::table('sites')
                    ->where(function ($query) use ($inspectionPlan) {
                        $query->where('active', '1')
                            ->orWhere(function ($subQuery) use ($inspectionPlan) {
                                if ($inspectionPlan && isset($inspectionPlan->site_id)) {
                                    $subQuery->where('id', $inspectionPlan->site_id)
                                        ->where('del', '0');
                                }
                            });
                    })
                    ->get(['id', 'title']);
            }
            $data['inspection_plans'] = $inspectionPlans;
            $data['authorised_by_list'] = $authorisedByList;
            return $this->success($data, 'Get Successfully');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection step 1 error: ' . $shortMessage,
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ]);
            return $this->message($shortMessage, 422);
        }
    }

    public function saveStep2(Request $request)
    {
        // dd($request->all());
        $userTable = $this->getUserTable();
        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required',
            'principal_contractor' => 'nullable',
            'project_name' => 'nullable',
            'itp' => 'nullable',
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection step 2 errors: ' . $validator->errors()->first(),
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Validation error'
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $data = $request->all();
            $inspectionPlanId = $request->inspection_plan_id;
            $inspectionPlan = InspectionPlan::find($inspectionPlanId);
            if (!$inspectionPlan) {
                return $this->message('Inspection Plan not found', 404);
            }
            $customer_id = null;
            $workspace_id = null;
            if ($userTable === 'customer') {
                $customer_id = auth()->id();  // Set customer_id
                $workspace_id = auth()->user()->current_workspace_id;  // Set workspace_id
                if ($inspectionPlan->customer_id !== $customer_id || $inspectionPlan->workspace_id !== $workspace_id) {
                    return $this->message('You do not have access to this project', 403);
                }
            }
            if ($userTable === 'emp') {
                $customer_id = auth()->user()->customer_id;  // Set customer_id
                $workspace_id = auth()->user()->workspace_id;  // Set workspace_id
                if ($inspectionPlan->customer_id !== $customer_id || $inspectionPlan->workspace_id !== $workspace_id) {
                    return $this->message('You do not have access to this project', 403);
                }
            }
            $inspectionPlanData = [
                'principal_contractor' => $request->principal_contractor,
                'principal_contractor_email' => $request->principal_contractor_email,
                'project_name' => $request->project_name,
                'job_number' => $request->job_number,
                'activity' => $request->activity,
                'building' => $request->building,
                'level' => $request->level,
                'to_level' => $request->to_level,
                'zone' => $request->zone,
                'pour' => $request->pour,
                'itp_reference_number' => $request->itp,
                'open_date' => $request->open_date,
                'close_date' => $request->close_date,
            ];
            InspectionPlan::updateOrCreate(['id' => $inspectionPlanId], $inspectionPlanData);
            $checklistItems = [];
            foreach ($data as $key => $value) {
                if (strpos($key, '_status') !== false) {
                    $name = str_replace('_status', '', $key);
                    $itpcKey = $name;
                    $notesKey = $name . '_notes';
                    $checklistItems[] = [
                        'inspection_plan_id' => $inspectionPlanId,
                        'itp_reference_number' => $request->itp ?? 0,
                        'itpc_number' => ($data[$itpcKey]),
                        'name' => $name,
                        'status' => ($value == '1' || $value == '1') ? '1' : '0',
                        'checklist_note' => $data[$notesKey] ?? '',
                        'customer_id' => $customer_id,
                        'workspace_id' => $workspace_id,
                    ];
                }
            }
            $hasChecklistWithStatusOne = collect($checklistItems)->contains('status', '1');
            if (!$hasChecklistWithStatusOne) {
                storeReportsLogs([
                    'employee_id' => auth()->user()->id,
                    'message' => 'Inspection step 2 error: At least one checklist form must have a status of yes to proceed.',
                    'report_id' => $request->inspection_plan_id,
                    'report_type' => 'inspection_report',
                    'error_type' => 'Validation error'
                ]);
                return $this->message('At least one checklist form must have a status of yes to proceed.', 422);
            }
            foreach ($checklistItems as $item) {
                InspectionPlanChecklist::updateOrCreate(
                    [
                        'inspection_plan_id' => $item['inspection_plan_id'],
                        'name' => $item['name'],
                        'customer_id' => $item['customer_id'],
                        'workspace_id' => $item['workspace_id'],
                    ],
                    $item
                );
            }
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan saved successfully',
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report'
            ]);
            return $this->success(['inspection_plan_id' => $inspectionPlanId], 'Inspection plan saved successfully');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection step 2 error: ' . $shortMessage,
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ]);
            return $this->message($shortMessage, 422);
        }
    }

    public function editStep2(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required'
        ]);
        if ($validator->fails()) {
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan step 2 validation error: ' . $validator->errors()->first(),
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Validation error',
            ]);
            return $this->message($validator->errors()->first(), 422);
        }
        $validatedData = $validator->validated();
        try {
            $inspectionPlan = InspectionPlan::find($validatedData['inspection_plan_id']);
            if (!$inspectionPlan) {
                return $this->message('Inspection Plan not found', 404);
            }
            $userTable = $this->getUserTable();
            if (
                $userTable === 'customer' &&
                ($inspectionPlan->customer_id !== auth()->id() || $inspectionPlan->workspace_id !== auth()->user()->current_workspace_id)
            ) {
                return $this->message('You do not have access to this inspection plan', 403);
            }
            if (
                $userTable === 'emp' &&
                ($inspectionPlan->customer_id !== auth()->user()->customer_id || $inspectionPlan->workspace_id !== auth()->user()->workspace_id)
            ) {
                return $this->message('You do not have access to this inspection plan', 403);
            }
            $data = [
                'inspection_plan' => $inspectionPlan,
                'inspection_plan_checklist' => InspectionPlanChecklist::where('inspection_plan_id', $validatedData['inspection_plan_id'])->get(),
                'inspection_plan_signature' => InspectionPlanSignature::where('inspection_plan_id', $validatedData['inspection_plan_id'])->get(),
                'inspection_plan_settings' => InspectionPlanTable::select(['title', 'step_order'])->distinct('title')->orderBy('step_order', 'asc')->get(),
            ];
            if ($data['inspection_plan_settings']->isEmpty()) {
                $message = 'Please create checklist steps to proceed further';
                storeReportsLogs([
                    'employee_id' => auth()->user()->id,
                    'message' => 'Inspection plan step 2: ' . $message,
                    'report_id' => $request->inspection_plan_id,
                    'report_type' => 'inspection_report'
                ]);
                return $this->message($message, 200, $data);
            }
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan step 2 fetched successfully',
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report'
            ]);
            return $this->success($data, 'Inspection Plan Step 2 fetched successfully');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            storeReportsLogs([
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection step 2 error: ' . $shortMessage,
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ]);
            return $this->message($shortMessage, 422);
        }
    }

    public function inspectionReportDownloadPdf(Request $request)
    {
        $id = $request->id;
        if (!$id) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan report PDF download ID is required',
                'report_id' => $id,
                'report_type' => 'inspection_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message('ID of plan is required', 422);
        }
        try {
            $report = InspectionPlan::leftJoin('sites', 'inspection_plans.site_id', '=', 'sites.id')
                ->leftJoin('emp_personal_details as authorised_by_details', 'inspection_plans.authorised_by', '=', 'authorised_by_details.id')
                ->leftJoin('emp_personal_details as emp_personal_supervisor_detail', 'sites.supervisor_id', '=', 'emp_personal_supervisor_detail.id')
                ->leftJoin('emp_personal_details as emp_personal_forman_detail', 'sites.forman_id', '=', 'emp_personal_forman_detail.id')
                ->where('inspection_plans.id', $id)
                ->select(
                    'inspection_plans.*',
                    'sites.title as sites_title',
                    'authorised_by_details.first_name as authorised_by_first_name',
                    'authorised_by_details.last_name as authorised_by_last_name',
                    'emp_personal_supervisor_detail.first_name as emp_personal_supervisor_detail_f_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.last_name as emp_personal_forman_detail_last_name'
                )
                ->first();
            if (!$report) {
                $log = [
                    'employee_id' => auth()->user()->id,
                    'message' => 'Inspection plan to this ID not found',
                    'report_id' => $id,
                    'report_type' => 'inspection_report',
                    'error_type' => 'Validation error',
                ];
                storeReportsLogs($log);
                return $this->message('Inspection plan to this ID not found', 404);
            }
            $userTable = $this->getUserTable();
            if (
                $userTable === "customer" &&
                ($report->customer_id != auth()->id() || $report->workspace_id != auth()->user()->current_workspace_id)
            ) {
                return $this->message('Unauthorized access to this inspection plan', 403);
            }

            if (
                $userTable === "emp" &&
                ($report->customer_id != auth()->user()->customer_id || $report->workspace_id != auth()->user()->workspace_id)
            ) {
                return $this->message('Unauthorized access to this inspection plan', 403);
            }
            $forms = InspectionPlanChecklist::leftJoin('inspection_plan_generals', 'inspection_plan_checklists.id', '=', 'inspection_plan_generals.iptc_id')
                ->leftJoin('inspection_plan_metas', 'inspection_plan_checklists.id', '=', 'inspection_plan_metas.itpc_id')
                ->leftJoin('inspection_plan_signatures', 'inspection_plan_checklists.id', '=', 'inspection_plan_signatures.itpc_id')
                ->leftJoin('emp_personal_details as inspection_plan_signatures_details', 'inspection_plan_signatures.employee_id', '=', 'inspection_plan_signatures_details.emp_id')
                ->where('inspection_plan_checklists.inspection_plan_id', $id)
                ->where('inspection_plan_checklists.status', '=', '1')
                ->select(
                    'inspection_plan_checklists.name as inspection_plan_step_name',
                    'inspection_plan_generals.*',
                    'inspection_plan_metas.title as meta_title',
                    'inspection_plan_metas.value as meta_value',
                    'inspection_plan_metas.is_table',
                    'inspection_plan_signatures.signature as inspection_plan_signature',
                    'inspection_plan_signatures.date as inspection_plan_date',
                    'inspection_plan_signatures.time as inspection_plan_time',
                    'inspection_plan_signatures_details.id as inspection_plan_employee_id',
                    'inspection_plan_signatures_details.first_name as inspection_plan_first_name',
                    'inspection_plan_signatures_details.last_name as inspection_plan_last_name'
                )
                ->get()
                ->groupBy('inspection_plan_step_name');
            $report_images = InspectionImage::where('inspection_plan_id', $id)->get();
            $viewPath = 'InspectionPlanPdf';
            $html = view($viewPath, compact('report', 'forms', 'report_images'))->render();
            $report_title = preg_replace('/[^A-Za-z0-9_]+/', '_', trim(str_replace(' ', '_', $report->title ?? 'No_Title')));
            $report_document_number = preg_replace('/[^A-Za-z0-9_]+/', '', trim(str_replace(' ', '_', $report->document_number ?? 'No_Document_Number')));
            $report_revision_number = preg_replace('/[^A-Za-z0-9_]+/', '', trim(str_replace(' ', '_', $report->revision_number ?? '00')));
            $filename = $report_title . $report_document_number . "R" . $report_revision_number . ".pdf";
            $directory = 'inspectionPlanReport';
            $full_path = public_path("$directory/$filename");
            $file_url = url("$directory/$filename");
            $existingFile = GeneratedPdfReport::where('report_type', 'inspection_report')
                ->where('report_id', $id)
                ->where('path', $file_url)
                ->first();
            if (file_exists($full_path) && $existingFile && $existingFile->path === $file_url) {
                return $this->success($file_url, 'PDF already exists and is available for download');
            }
            if (!file_exists(public_path($directory))) {
                mkdir(public_path($directory), 0777, true);
            }
            $pdf = PDF::loadHTML($html)->setPaper('A4', 'portrait');
            $pdf->save($full_path);
            GeneratedPdfReport::create([
                'report_id' => $id,
                'path' => $file_url,
                'report_type' => 'inspection_report',
            ]);
            return $this->success($file_url, 'PDF generated and uploaded successfully');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan report download error: ' . $shortMessage,
                'report_id' => $id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->message($shortMessage, 422);
        }
    }
    // need to conform this fucniton is needed or not 
    public function inspectionPlanFormPages()
    {
        $emp_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', ['B-1', 'B-2', 'B-3']);
            })
            ->get();
        $employees = $emp_list;
        return view('InspectionPlan.NewInspectionReport.form_index', compact('employees'));
    }

    /**
     * Handle inspection signature image upload
     * 
     * @param \Illuminate\Http\UploadedFile|\Illuminate\Http\Request $file
     * @param string $fieldName
     * @param string|null $oldImagePath
     * @return string|null
     */
    private function handleInspectionSignatureUpload($file, $fieldName = 'signature', $oldImagePath = null)
    {
        try {
            // Create directory if it doesn't exist
            $uploadPath = public_path('inspectionSignature');
            if (!file_exists($uploadPath)) {
                mkdir($uploadPath, 0755, true);
            }

            // Delete old image if it exists
            if ($oldImagePath && file_exists(public_path($oldImagePath))) {
                unlink(public_path($oldImagePath));
            }

            // Handle file upload based on input type
            $uploadedFile = null;
            if ($file instanceof \Illuminate\Http\Request) {
                if ($file->hasFile($fieldName)) {
                    $uploadedFile = $file->file($fieldName);
                }
            } else {
                $uploadedFile = $file;
            }

            if (!$uploadedFile) {
                return null;
            }

            // Generate unique filename
            $extension = $uploadedFile->getClientOriginalExtension();
            $filename = time() . '_' . uniqid() . '.' . $extension;

            // Move file to inspectionSignature directory
            $uploadedFile->move($uploadPath, $filename);

            // Return relative path
            return 'inspectionSignature/' . $filename;
        } catch (\Exception $e) {
            Log::error('Error uploading inspection signature: ' . $e->getMessage());
            return null;
        }
    }

    public function inspectionPlanSaveStep(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required',
            'name' => 'required|string|max:255',
            'level' => 'nullable|string|max:255',
            'table_values' => 'nullable|array',     // Table values
            'row_ids' => 'nullable|array',            // Headers of the table
            'signature' => 'nullable',
            'architectural_drawing_number' => 'nullable',
            'structectural_drawing_number' => 'nullable',
            'Post_Tension_Drawing_Number' => 'nullable',
            'partial_Handover_date' => 'nullable',
            'complete_handover_date' => 'nullable',
            'complete_handover_time' => 'nullable',
            'principal_name' => 'nullable|string|max:255',
            'principal_date' => 'nullable|date',
        ], [
            'partial_Handover_date.after_or_equal' => 'The partial handover date must be today or later.',
            'complete_handover_date.after_or_equal' => 'The complete handover date must be today or later.',
            'complete_handover_time.after_or_equal' => 'The complete handover time must be equal to or later than the current time.',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan step ' . $request->name . 'save error' . $validator->errors()->first(),
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $inspectionPlan = InspectionPlan::find($request->inspection_plan_id);
            if (!$inspectionPlan) {
                return $this->message('Inspection plan not found', 404);
            }
            $userTable = $this->getUserTable();
            $customer_id = null;
            $workspace_id = null;
            if ($userTable === 'customer') {
                $customer_id = auth()->id();  // Set customer_id
                $workspace_id = auth()->user()->current_workspace_id;  // Set workspace_id
                if ($inspectionPlan->customer_id !== $customer_id || $inspectionPlan->workspace_id !== $workspace_id) {
                    return $this->message('You do not have access to this project', 403);
                }
            }
            if ($userTable === 'emp') {
                $customer_id = auth()->user()->customer_id;  // Set customer_id
                $workspace_id = auth()->user()->workspace_id;  // Set workspace_id
                if ($inspectionPlan->customer_id !== $customer_id || $inspectionPlan->workspace_id !== $workspace_id) {
                    return $this->message('You do not have access to this project', 403);
                }
            }
            $message = '';
            $data = [];
            $validatedData = $validator->validated();
            $inspection_plan_id = $validatedData['inspection_plan_id'];
            $name = $validatedData['name'];
            $inspection_plan_checklist_columns = InspectionPlanChecklist::where('inspection_plan_id', $inspection_plan_id)
                ->where('name', $name)
                ->first();
            $inspection_plan_checklist_columns_id = $inspection_plan_checklist_columns->id;
            $inspection_plan_deck_handover = [
                'inspection_plan_id' => $inspection_plan_id,
                'itp_reference_number' => $inspection_plan_checklist_columns->itp_reference_number ?? null,
                'iptc_id' => $inspection_plan_checklist_columns_id ?? null,
                'level' => $request->level,
                'to_level' => $request->to_level,
                'pour' => $request->pour,
                // 'zone' => $request->zone,
                'partial_Handover' => (string)($request->partial_Handover) ? '1' : '0',
                'partial_Handover_date' => $request->partial_Handover_date,
                'partial_Handover_time' => $request->partial_Handover_time,
                'partial_Handover_location' => $request->partial_Handover_location,
                'complete_handover' => (string)($request->complete_handover) ? '1' : '0',
                'complete_handover_date' => $request->complete_handover_date,
                'complete_handover_time' => $request->complete_handover_time,
                'complete_handover_Location' => $request->complete_handover_location,
                'architectural_drawing_number' => $request->architectural_drawing_number,
                'structectural_drawing_number' => $request->structectural_drawing_number,
                'Post_Tension_Drawing_Number' => $request->Post_Tension_Drawing_Number,
                "description_box_for_message" => $request->description_box_for_message,
                'principal_name' => $request->principal_name,
                'principal_date' => $request->principal_date,
                'company_group_name' => $request->company_group_name,
                'company_group_date' => $request->company_group_date,
            ];
            $inspection_general_exist_status = InspectionPlanGeneral::where('inspection_plan_id', $inspection_plan_id)
                ->where('iptc_id', $inspection_plan_checklist_columns->id ?? null)
                ->first();
            if (!$inspection_general_exist_status || $inspection_general_exist_status->partial_Handover_date === null) {
                $validator_date = Validator::make($request->all(), [
                    'partial_Handover_date' => 'nullable|date',
                ]);
                if ($validator_date->fails()) {
                    return $this->message($validator_date->errors()->first(), 422);
                }
            }
            if (!$inspection_general_exist_status || $inspection_general_exist_status->complete_handover_date === null) {
                $validator_date = Validator::make($request->all(), [
                    'complete_handover_date' => 'nullable|date',
                ]);
                if ($validator_date->fails()) {
                    return $this->message($validator_date->errors()->first(), 422);
                }
            }
            if ($inspection_general_exist_status) {
                InspectionPlanGeneral::where('inspection_plan_id', $inspection_plan_id)
                    ->where('iptc_id', $inspection_plan_checklist_columns->id)
                    ->update($inspection_plan_deck_handover);
            } else {
                $data['inspection_plan_general'] = InspectionPlanGeneral::insertGetId($inspection_plan_deck_handover);
            }
            $inspection_plan_complete_status = InspectionPlanChecklist::where('inspection_plan_id', $inspection_plan_id)->where('is_complete', 0)->first();
            if (!$inspection_plan_complete_status) {
                InspectionPlan::where('id', $inspection_plan_id)->update(['process' => 1]);
            }
            // $signature_employee_ids = $request->input('column_employee_id', []);
            $signature_files = $request->file('column_signature', []);
            $signature_dates = $request->input('column_date', []);
            $employee_count = 1;
            if ($request->hasFile('signature')) {
                $companyExistingSignature = InspectionPlanSignature::where('inspection_plan_id', $inspection_plan_id)
                    ->where('itpc_id', $inspection_plan_checklist_columns->id ?? 0)
                    ->where('signature_type', '1')
                    ->where('del', 0)
                    ->first();
                if ($companyExistingSignature) {
                    if ($request->isCompanySignature == "1") {
                        $companyExistingSignature->signature = $this->handleInspectionSignatureUpload($request, 'signature', $companyExistingSignature->signature);
                    }
                    $companyExistingSignature->employee_name = $request->company_group_name;
                    $companyExistingSignature->date = $request->company_group_date ?: date('Y-m-d');
                    // $companyExistingSignature->date = date('Y-m-d');
                    $companyExistingSignature->save();
                } else {
                    $user = auth()->user();
                    $access_role = $user->access_role;
                    $user_id = $user->id;
                    $signature = new InspectionPlanSignature();
                    if ($request->isCompanySignature == "1") {
                        if ($request->signature) {
                            $signature->signature = $this->handleInspectionSignatureUpload($request, 'signature');
                        }
                    }
                    $signature->inspection_plan_id = $inspection_plan_id;
                    $signature->itpc_id = $inspection_plan_checklist_columns->id ?? 0;
                    $signature->employee_id = $user_id;
                    $signature->employee_name = $request->company_group_name;
                    $signature->date = $request->company_group_date ?: date('Y-m-d');
                    $signature->employee_type = $access_role;
                    $signature->signature_type = '1';
                    $signature->save();
                }
            }
            if ($request->thead && $request->table_values) {
                // Get the specific checklist step using the inspection_plan_checklist_columns_id
                $inspection_plan_checklist = InspectionPlanChecklist::where('id', $inspection_plan_checklist_columns_id)
                    ->where('inspection_plan_id', $inspection_plan_id)
                    ->where('customer_id', $customer_id)
                    ->where('workspace_id', $workspace_id)
                    ->first();

                if (!$inspection_plan_checklist) {
                    return $this->message('Checklist step not found.', 404);
                }

                // Delete only the meta data for this specific inspection plan, checklist, and name
                InspectionPlanMeta::where('inspection_plan_id', $inspection_plan_id)
                    ->where('itpc_id', $inspection_plan_checklist->id)
                    ->where('name', $name)
                    ->where('customer_id', $customer_id)
                    ->where('workspace_id', $workspace_id)
                    ->where('is_table', 0)
                    ->delete();

                foreach ($request->table_values as $rowIndex => $values) {
                    if (!is_array($values)) {
                        continue; // Skip if the row is not an array
                    }
                    foreach ($values as $colIndex => $value) {
                        // Ensure the header index exists
                        $title = $request->thead[$colIndex] ?? ''; // Correctly access the 'thead' values from the request
                        $inspection_plan_meta = new InspectionPlanMeta();
                        $inspection_plan_meta->inspection_plan_id = $inspection_plan_id;
                        $inspection_plan_meta->itpc_id = $inspection_plan_checklist->id;
                        $inspection_plan_meta->title = $title;
                        $inspection_plan_meta->value = $value;
                        $inspection_plan_meta->name = $name;
                        $inspection_plan_meta->customer_id = $customer_id;
                        $inspection_plan_meta->workspace_id = $workspace_id;
                        $inspection_plan_meta->save();
                    }
                }
            }
            if ($request->hasFile('principal_signature')) {
                $existingPrincipalSignature = InspectionPlanSignature::where('inspection_plan_id', $inspection_plan_id)
                    ->where('itpc_id', $inspection_plan_checklist_columns->id ?? 0)
                    ->where('signature_type', '2')
                    ->where('del', 0)
                    ->first();
                if ($existingPrincipalSignature) {
                    if ($request->is_principal_signature == "1") {
                        $existingPrincipalSignature->signature = $this->handleInspectionSignatureUpload($request, 'principal_signature', $existingPrincipalSignature->signature);
                    }
                    $existingPrincipalSignature->employee_name = $request->principal_name ?? 'N/A';
                    $existingPrincipalSignature->date = $request->principal_date ?: date('Y-m-d');
                    $existingPrincipalSignature->save();
                } else {
                    $user = auth()->user();
                    $access_role = $user->access_role;
                    $user_id = $user->id;
                    $principalsignature = new InspectionPlanSignature();
                    if ($request->is_principal_signature  == "1") {
                        $principalsignature->signature = $this->handleInspectionSignatureUpload($request, 'principal_signature');
                    }
                    $principalsignature->inspection_plan_id = $inspection_plan_id;
                    $principalsignature->itpc_id = $inspection_plan_checklist_columns->id ?? 0;
                    $principalsignature->employee_id = $user_id;
                    $principalsignature->employee_name = $request->principal_name ?? 'N/A';
                    $principalsignature->date = $request->principal_date ?: date('Y-m-d');
                    $principalsignature->signature_type = '2';
                    $principalsignature->save();
                }
            }
            if ($employee_count > 0 && isset($signature_employee_ids) && is_array($signature_employee_ids)) {
                if ($employee_count >= 1) {
                    for ($i = 0; $i < $employee_count; $i++) {
                        $employee_id = $signature_employee_ids[$i] ?? null;
                        $signature_date = $signature_dates[$i] ?? null;
                        $signature_file = isset($signature_files[$i]) ? $signature_files[$i] : null;
                        if (empty($employee_id)) {
                            continue;
                        }
                        if ($signature_file) {
                            $existingEmployeeSignature = InspectionPlanSignature::where('inspection_plan_id', $inspection_plan_id)
                                ->where('itpc_id', $inspection_plan_checklist_columns->id)
                                ->where('employee_name', $employee_id)
                                ->where('del', 0)
                                ->first();
                            $signature_path = $this->handleInspectionSignatureUpload($signature_file);
                            if ($existingEmployeeSignature) {
                                // Delete old signature if exists
                                if ($existingEmployeeSignature->signature && file_exists(public_path($existingEmployeeSignature->signature))) {
                                    unlink(public_path($existingEmployeeSignature->signature));
                                }
                                $existingEmployeeSignature->signature = $signature_path;
                                $existingEmployeeSignature->date = $signature_date ?? null;
                                $existingEmployeeSignature->save();
                            } else {
                                $employee_type = $employee_id;
                                $signature = new InspectionPlanSignature();
                                $signature->inspection_plan_id = $inspection_plan_id;
                                $signature->itpc_id = $inspection_plan_checklist_columns->id;
                                $signature->employee_name = $employee_type;
                                $signature->employee_type = $employee_type;
                                $signature->signature = $signature_path;
                                $signature->date = $signature_date ?? null;
                                $signature->save();
                            }
                        }
                    }
                }
            } else {
                $log = [
                    'employee_id' => auth()->user()->id,
                    'message' => 'Inspection plan  Invalid input signature format.',
                    'report_id' => $request->inspection_plan_id,
                    'report_type' => 'inspection_report',
                    'error_type' => 'Validation error',
                ];
                storeReportsLogs($log);
            }
            InspectionPlanChecklist::where('id', $inspection_plan_checklist_columns_id)->update(['is_complete' => '1']);
            $inspection_plan_complete_status = InspectionPlanChecklist::where('inspection_plan_id', $inspection_plan_id)->where('is_complete', 0)->first();
            if (!$inspection_plan_complete_status) {
                InspectionPlan::where('id', $inspection_plan_id)->update(['process' => '1']);
            }
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan step ' . $name . ' Saved successfully:',
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report'
            ];
            storeReportsLogs($log);
            return $this->message('Inspection plan step saved successfully');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan step save error:',
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->error($shortMessage);
        }
    }

    public function inspectionPlanFormStepData(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required',
            'name' => 'required'
        ]);
        if ($validator->fails()) {
            return $this->message($validator->errors()->first(), 422);
        }
        try {
            $validatedData =  $validator->validated();
            $inspectionPlan = InspectionPlan::find($validatedData['inspection_plan_id']);

            if (!$inspectionPlan) {
                return $this->message('Inspection plan not found', 404);
            }

            $userTable = $this->getUserTable();
            if (
                $userTable === "customer" &&
                ($inspectionPlan->customer_id != auth()->id() || $inspectionPlan->workspace_id != auth()->user()->current_workspace_id)
            ) {
                return $this->message('Unauthorized access to this inspection plan', 403);
            }
            if (
                $userTable === "emp" &&
                ($inspectionPlan->customer_id != auth()->user()->customer_id || $inspectionPlan->workspace_id != auth()->user()->workspace_id)
            ) {
                return $this->message('Unauthorized access to this inspection plan', 403);
            }

            $data = [];
            $inspection_plan_id = $validatedData['inspection_plan_id'];
            $name = $request->name;

            // Get customer and workspace IDs based on user type
            $customer_id = $userTable === 'customer' ? auth()->id() : auth()->user()->customer_id;
            $workspace_id = $userTable === 'customer' ? auth()->user()->current_workspace_id : auth()->user()->workspace_id;

            $inplection_plan_checklist_columns = InspectionPlanChecklist::where('inspection_plan_id', $inspection_plan_id)
                ->where('name', $name)
                ->where('customer_id', $customer_id)
                ->where('workspace_id', $workspace_id)
                ->first();

            if (!$inplection_plan_checklist_columns) {
                return $this->message('Checklist step not found', 404);
            }

            $data['inspection_plan_step_data'] = InspectionPlanGeneral::where('inspection_plan_id', $inspection_plan_id)
                ->where('iptc_id', $inplection_plan_checklist_columns->id)
                ->first();

            $data['inpection_plan_signature'] = InspectionPlanSignature::where('inspection_plan_id', $inspection_plan_id)
                ->where('itpc_id', $inplection_plan_checklist_columns->id)
                ->where('del', 0)
                ->get();

            // Get meta data specific to this inspection plan and checklist step
            $data['inspection_plan_meta_data'] = InspectionPlanMeta::where('inspection_plan_id', $inspection_plan_id)
                ->where('itpc_id', $inplection_plan_checklist_columns->id)
                ->where('customer_id', $customer_id)
                ->where('workspace_id', $workspace_id)
                ->select('id', 'title', 'value', 'name', 'is_table')
                ->get();

            return $this->success($data, 'fetch data successfully');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan step save error:' .   $shortMessage,
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->message($shortMessage, 500);
        }
    }

    public function inspectionPlanSettingaEmployeeList()
    {
        try {
            $userTable = $this->getUserTable(); // Get user type (customer or employee)
            $emp_list_query = 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', ['B-1', 'B-2', 'B-3']);
                });
            if ($userTable === "customer") {
                $emp_list_query->whereHas('empPersonalDetails', function ($query) {
                    $query->where('customer_id', auth()->id())
                        ->where('workspace_id', auth()->user()->current_workspace_id);
                });
            }
            if ($userTable === "emp") {
                $emp_list_query->whereHas('empPersonalDetails', function ($query) {
                    $query->where('customer_id', auth()->user()->customer_id)
                        ->where('workspace_id', auth()->user()->workspace_id);
                });
            }
            $emp_list = $emp_list_query->get();
            $data['authorised_by_list'] = $emp_list;
            if ($emp_list->isEmpty()) {
                return $this->message('No employees found. Please create.', 422);
            }
            return $this->success($data, 'Records retrieved successfully');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan employee list error: ' . $shortMessage,
                'report_id' => null,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->message($shortMessage, 500);
        }
    }

    public function InspectionReportPdfFiles(Request $request)
    {
        $userTable = $this->getUserTable();
        $query = GeneratedPdfReport::where('report_type', 'inspection_report');
        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);
        }
        // Get the GeneratedPdfReport records
        $pdfReports = $query->get();
        if ($pdfReports->isEmpty()) {
            return $this->message('No records found.', 404);
        }
        // Get all report IDs to fetch titles in one query
        $reportIds = $pdfReports->pluck('report_id')->toArray();
        // Get titles from InspectionPlan
        $inspectionPlans = InspectionPlan::whereIn('id', $reportIds)
            ->select('id', 'title')
            ->get()
            ->keyBy('id');
        // Attach title to each PDF report
        $pdfReports->transform(function ($report) use ($inspectionPlans) {
            $report->title = $inspectionPlans->get($report->report_id)->title ?? 'N/A';
            return $report;
        });
        return $this->withCount($pdfReports, 'Retrieve all records Successfully');
    }

    public function downloadPdfFile($filename)
    {
        if (pathinfo($filename, PATHINFO_EXTENSION) === '') {
            $filename .= '.pdf'; // Default to PDF if no extension provided
        }
        $path = public_path("inspectionPlanReport/");
        $fileUrl = url("inspectionPlanReport/" . $filename);
        if (!file_exists($path . $filename)) {
            return $this->message('File not found. The requested file may have been deleted or is not available.', 404);
        }
        return $this->success($fileUrl, 'File retrieved successfully');
    }

    public function inspectionReportPublishReport($id)
    {
        $inspectionPlan = InspectionPlan::find($id);
        if (!$inspectionPlan) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Report not found. Please try again.',
                'report_id' => $id,
                'report_type' => 'inspection_report',
                'error_type' => 'Not Found error',
            ];
            storeReportsLogs($log);
            return $this->message('Report not found. Please try again.', 404);
        }
        $userTable = $this->getUserTable();
        if ($userTable === "customer" && ($inspectionPlan->customer_id != auth()->id() || $inspectionPlan->workspace_id != auth()->user()->current_workspace_id)) {
            return $this->message('Unauthorized access. You do not have permission to modify this report.', 403);
        }
        if ($userTable === "emp" && ($inspectionPlan->customer_id != auth()->user()->customer_id || $inspectionPlan->workspace_id != auth()->user()->workspace_id)) {
            return $this->message('Unauthorized access. You do not have permission to modify this report.', 403);
        }
        $inspectionPlan->is_published = $inspectionPlan->is_published == '1' ? '0' : '1';
        $inspectionPlan->save();
        $log = [
            'employee_id' => auth()->user()->id,
            'message' => 'Report status updated successfully',
            'report_id' => $id,
            'report_type' => 'inspection_report'
        ];
        storeReportsLogs($log);
        return $this->message('Report status updated successfully.', 200);
    }

    public function inspectionReportDownloadPdfRegenerate($id)
    {
        try {
            $inspectionPlan = DB::table('inspection_plans')
                ->leftJoin('sites', 'inspection_plans.site_id', '=', 'sites.id')
                ->leftJoin('emp_personal_details as authorised_by_details', 'inspection_plans.authorised_by', '=', 'authorised_by_details.emp_id')
                ->leftJoin('emp_personal_details as emp_personal_supervisor_detail', 'sites.supervisor_id', '=', 'emp_personal_supervisor_detail.id')
                ->leftJoin('emp_personal_details as emp_personal_forman_detail', 'sites.forman_id', '=', 'emp_personal_forman_detail.id')
                ->leftJoin('projects', 'inspection_plans.project_name', '=', 'projects.id')
                ->where('inspection_plans.id', $id)
                ->select(
                    'inspection_plans.*',
                    'sites.title as sites_title',
                    'authorised_by_details.first_name as authorised_by_first_name',
                    'authorised_by_details.middle_name as authorised_by_middle_name',
                    'authorised_by_details.last_name as authorised_by_last_name',
                    'projects.id as project_id',
                    'projects.title as project_title',
                    'emp_personal_supervisor_detail.first_name as emp_personal_supervisor_detail_f_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.last_name as emp_personal_forman_detail_last_name'
                )
                ->first();
            unset($inspectionPlan->project_name);
            if (!$inspectionPlan) {
                $log = [
                    'employee_id' => auth()->user()->id,
                    'message' => 'Inspection plan to this ID not found',
                    'report_id' => $id,
                    'report_type' => 'inspection_report'
                ];
                storeReportsLogs($log);
                return $this->message('Inspection plan to this ID not found', 404);
            }
            $userTable = $this->getUserTable();
            if (
                $userTable === "customer" &&
                ($inspectionPlan->customer_id != auth()->id() || $inspectionPlan->workspace_id != auth()->user()->current_workspace_id)
            ) {
                return $this->message('Unauthorized access to this inspection plan', 403);
            }
            if (
                $userTable === "emp" &&
                ($inspectionPlan->customer_id != auth()->user()->customer_id || $inspectionPlan->workspace_id != auth()->user()->workspace_id)
            ) {
                return $this->message('Unauthorized access to this inspection plan', 403);
            }
            // Get customer and workspace IDs based on user type
            $customer_id = $userTable === 'customer' ? auth()->id() : auth()->user()->customer_id;
            $workspace_id = $userTable === 'customer' ? auth()->user()->current_workspace_id : auth()->user()->workspace_id;
            // Get site title (brand title) from settings
            $brandTitleText = DB::table('adminsettings')
                ->where('key', 'brand_title_text')
                ->where('customer_id', $customer_id)
                ->where('workspace', $workspace_id)
                ->value('value');
            // Load inspection plan checklists
            $inspection_plan_checklist = InspectionPlanChecklist::where('inspection_plan_id', $id)
                ->where('status', '1')
                ->with(['metas', 'signatures.employeeDetails', 'general'])
                ->get();
            // Transform the checklist data to include properly structured meta data
            $inspection_plan_checklist->transform(function ($step) use ($customer_id, $workspace_id, $id) {
                $inspection_plan_table_heads = InspectionPlanTable::where('customer_id', $customer_id)
                    ->where('workspace_id', $workspace_id)
                    ->where('title', $step->name)
                    ->select('id', 'title', 'value')
                    ->get();
                $inspection_plan_table_form_data = InspectionPlanMeta::where('inspection_plan_id', $id)
                    ->where('itpc_id', $step->id)
                    ->where('customer_id', $customer_id)
                    ->where('workspace_id', $workspace_id)
                    ->where('is_table', 0)
                    ->select('id', 'title', 'value', 'name', 'is_table')
                    ->get();
                $step->meta_data = [
                    'inspection_plan_table_heads' => $inspection_plan_table_heads,
                    'inspection_plan_table_form_data' => $inspection_plan_table_form_data,
                ];
                return $step;
            });
            // Inject `site_title` inside each signature
            foreach ($inspection_plan_checklist as $step) {
                if ($step->signatures && is_iterable($step->signatures)) {
                    foreach ($step->signatures as $signature) {
                        $signature->site_title = $brandTitleText;
                    }
                }
            }
            // Group forms by step name if needed (currently unused)
            $forms = $inspection_plan_checklist->groupBy('name')->map(function ($steps, $stepName) {
                return $steps->map(function ($step) {
                    return [
                        'inspection_plan_step_name' => $step->name,
                        'general' => $step->general,
                        'metas' => $step->metas,
                        'signatures' => $step->signatures,
                        'images' => $step->images,
                        'meta_data' => $step->meta_data,
                    ];
                });
            });
            $report_images = DB::table('inspection_images')
                ->where('inspection_plan_id', $id)
                ->get();
                if($inspectionPlan->report_method == 1){
                    $inspection_plan_upload_report=GeneratedPdfReport::where('report_type', 'inspection_report')->where('report_id', $id)->first();
                }
                else{
            GeneratedPdfReport::updateOrCreate(
                [
                    'report_id' => $id,
                    'report_type' => 'inspection_report'
                ],
                [
                    'report_id' => $id,
                    'path' => null,
                    'report_type' => 'inspection_report',
                ]
            );
            $inspection_plan_upload_report=null;
            }
            $inspection_plan_signoffs = DB::table('inspection_plan_signatures')
                ->where('inspection_plan_id', $id)
                ->where('itpc_id', null)
                ->select('employee_id', 'signature', 'date')
                ->get();
            $inspection_plan_signoffs_array = [];
            foreach ($inspection_plan_signoffs as $signoff) {
                $emp_company = EmpCompanyDetails::where('id', $signoff->employee_id)->first();
                $emp_personal_details = EmpPersonalDetails::where('emp_id', $signoff->employee_id)->first();
                $role_title = null;
                if ($emp_company && $emp_company->access_role) {
                    $role_title = Role::where('code', $emp_company->access_role)->first();
                }
                $inspection_plan_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,
                    'signature' => $signoff->signature,
                    'date' => $signoff->date,
                ];
            }
            $data = [
                'inspection_plan' => $inspectionPlan,
                'report_images' => $report_images,
                'inspection_plan_checklist' => $inspection_plan_checklist,
                'inspection_plan_signoffs' => $inspection_plan_signoffs_array,
                'uploaded_report' => $inspection_plan_upload_report,
            ];
            return $this->success($data, 'Inspection Report Data Retrieved Successfully.');
        } catch (\Exception $e) {
            $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection plan report download error:' . $shortMessage,
                'report_id' => $id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ];
            storeReportsLogs($log);
            return $this->message($e->getMessage(), 500);
        }
    }

    public function inspectionReportViewSignature($id)
    {
        try {
            $validator = Validator::make(['id' => $id], [
                'id' => 'required|integer',
            ]);

            if ($validator->fails()) {
                $log = [
                    'employee_id' => auth()->user()->id,
                    'message' => 'Inspection report view signature validation error: ' . $validator->errors()->first(),
                    'report_id' => $id,
                    'report_type' => 'inspection_report',
                    'error_type' => 'Validation error',
                ];
                storeReportsLogs($log);
                return $this->message($validator->errors()->first(), 422);
            }

            // Get customer and workspace IDs
            $ids = $this->getCustomerAndWorkspaceIds();
            $customerId = $ids['customer_id'];
            $workspaceId = $ids['workspace_id'];

            // Get inspection plan with access validation
            $inspection_plan = InspectionPlan::find($id);
            if (!$inspection_plan) {
                return $this->message('Inspection plan not found.', 404);
            }

            // Check access permissions
            if ($inspection_plan->customer_id !== $customerId || $inspection_plan->workspace_id !== $workspaceId) {
                return $this->message('You do not have access to this inspection plan.', 403);
            }

            // Use Eloquent model to get formatted dates
            $inspection_plans = InspectionPlan::with(['authorizedBy'])
                ->where('id', $id)
                ->where('customer_id', $customerId)
                ->where('workspace_id', $workspaceId)
                ->first();

            if (!$inspection_plans) {
                return $this->message('Inspection plan not found or access denied.', 404);
            }

            // Get inspection plan signatures with employee details and role information using Eloquent
            $inspection_plan_signatures = InspectionPlanSignature::with(['employeeDetails'])
                ->where('inspection_plan_id', $id)
                ->where('itpc_id', null)
                ->get();

            // Add role information to each signature
            foreach ($inspection_plan_signatures as $signature) {
                if ($signature->employee_type) {
                    // Get role title based on employee_type (role code) and customer/workspace context
                    $role_code = EmpCompanyDetails::where('id', $signature->employee_id)->first()->access_role;
                    $role = Role::where('code', $role_code)
                        ->where('del', '0')
                        ->first();

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

            // Convert to collection for easier manipulation
            $inspectionSignatures = collect($inspection_plan_signatures);

            // Check if authorised_by employee is already in the signature data
            $authorisedByInSignatures = $inspectionSignatures->contains('employee_id', $inspection_plans->authorised_by);

            // If authorised_by is not in signatures table and not 0 (customer), add them with null signature
            if (!$authorisedByInSignatures && $inspection_plans->authorised_by && $inspection_plans->authorised_by != 0) {
                // Fetch authorised_by employee details
                $authorisedByDetails = 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', $inspection_plans->authorised_by)
                    ->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', $inspection_plans->customer_id)
                    ->where('emp_company_details.workspace_id', $inspection_plans->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 ($authorisedByDetails) {
                    // Create complete array structure for authorised_by to match existing signature format
                    $authorisedBySignatureArray = [
                        'id' => null,
                        'inspection_plan_id' => $inspection_plans->id,
                        'itpc_id' => null,
                        'employee_id' => (string) $inspection_plans->authorised_by,
                        'employee_name' => trim(($authorisedByDetails->first_name ?? '') . ' ' .
                            ($authorisedByDetails->middle_name ?? '') . ' ' .
                            ($authorisedByDetails->last_name ?? '')),
                        'employee_type' => $authorisedByDetails->access_role,
                        'signature' => null, // Null indicates signature is required
                        'signature_type' => null,
                        'date' => $inspection_plans->issue_date,
                        'time' => null,
                        'del' => '0',
                        'created_at' => null,
                        'updated_at' => null,
                        'role_title' => $authorisedByDetails->role_title,
                        'employee_details' => [
                            'id' => (int) $authorisedByDetails->emp_id,
                            'emp_id' => (string) $authorisedByDetails->emp_id,
                            'first_name' => $authorisedByDetails->first_name,
                            'middle_name' => $authorisedByDetails->middle_name,
                            'last_name' => $authorisedByDetails->last_name,
                            'mobile' => null,
                            'streat_address' => null,
                            'suburb' => null,
                            'state' => null,
                            'postcode' => null,
                            'image' => 'assets/img/default.png',
                            'date_of_birth' => null,
                            'blood_group' => null,
                            'bank_name' => null,
                            'account_holder_name' => null,
                            'ibn_number' => null,
                            'account_number' => null,
                            'created_by' => null,
                            'del' => '0',
                            'created_at' => null,
                            'updated_at' => null
                        ]
                    ];

                    // Add to signature collection
                    $inspectionSignatures->push((object) $authorisedBySignatureArray);
                }
            }
            $data = [
                'inspection_plan' => $inspection_plans,
                'inspection_plan_signatures' => $inspectionSignatures->values()->toArray(),
            ];

            return $this->success($data, 'Inspection plan signature data retrieved successfully.');
        } catch (\Exception $e) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection report view signature error: ' . $e->getMessage(),
                'report_id' => $id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error',
            ];
            storeReportsLogs($log);
            return $this->message('An error occurred while retrieving signature data: ' . $e->getMessage(), 500);
        }
    }


    public function imageStore(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required',
            'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:5048',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection images store: ' . $validator->errors()->first(),
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        $userTable = $this->getUserTable();
        $inspectionPlan = InspectionPlan::where('id', $request->inspection_plan_id);
        if ($userTable === 'customer') {
            $inspectionPlan->where('customer_id', auth()->id())
                ->where('workspace_id', auth()->user()->current_workspace_id);
        }
        if ($userTable === 'emp') {
            $inspectionPlan->where('customer_id', auth()->user()->customer_id)
                ->where('workspace_id', auth()->user()->workspace_id);
        }
        if (!$inspectionPlan->exists()) {
            return $this->message('You are not authorized to perform this action.', 403);
        }
        if ($request->hasFile('image') && $request->file('image')->isValid()) {
            $imagePath = $this->handleFileImageUpload($request, 'inspectionPlanImages')['path'] ?? null;
            if (!$imagePath) {
                return $this->message('Failed to upload image.', 422);
            }
            $inspectionPlanChecklist = InspectionPlanChecklist::where('inspection_plan_id', $request->inspection_plan_id)
                ->where('name', $request->step_name)
                ->first();
            if (!$inspectionPlanChecklist) {
                return $this->message('Invalid step name or inspection plan ID.', 404);
            }
            $image = new InspectionImage();
            $image->image = $imagePath;
            $image->inspection_plan_id = $request->inspection_plan_id;
            $image->itpc_id = $inspectionPlanChecklist->id;
            $image->save();
            $images = InspectionImage::where('inspection_plan_id', $request->inspection_plan_id)
                ->where('itpc_id', $inspectionPlanChecklist->id)
                ->get();
            return $this->success($images, 'Image uploaded successfully!');
        }
        return $this->message('Invalid or no image uploaded.', 422);
    }

    public function getImages(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required',
            'step_name' => 'required|string',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection images fetch: ' . $validator->errors()->first(),
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        $userTable = $this->getUserTable();
        $inspectionPlanQuery = InspectionPlan::where('id', $request->inspection_plan_id);
        if ($userTable === 'customer') {
            $inspectionPlanQuery->where('customer_id', auth()->id())
                ->where('workspace_id', auth()->user()->current_workspace_id);
        }
        if ($userTable === 'emp') {
            $inspectionPlanQuery->where('customer_id', auth()->user()->customer_id)
                ->where('workspace_id', auth()->user()->workspace_id);
        }
        if (!$inspectionPlanQuery->exists()) {
            return $this->message('You are not authorized to view these images.', 403);
        }
        $inspectionPlanChecklist = InspectionPlanChecklist::where('name', $request->step_name)
            ->where('inspection_plan_id', $request->inspection_plan_id)
            ->first();
        if (!$inspectionPlanChecklist) {
            return $this->message('Invalid step name or inspection plan ID.', 404);
        }
        $images = InspectionImage::where('itpc_id', $inspectionPlanChecklist->id)->get();
        return $this->success($images, 'Images retrieved successfully.');
    }

    public function getDescription(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection  images store:' . $validator->errors()->first(),
                'report_id' =>   $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        $userTable = $this->getUserTable();
        $inspection_plan = InspectionPlan::where('id', $request->inspection_plan_id);
        if ($userTable === 'customer') {
            $inspection_plan->where('customer_id', auth()->id())
                ->where('workspace_id', auth()->user()->current_workspace_id);
        }
        if ($userTable === 'emp') {
            $inspection_plan->where('customer_id', auth()->user()->customer_id)
                ->where('workspace_id', auth()->user()->workspace_id);
        }
        if (!$inspection_plan->exists()) {
            return $this->message('You are not authorized to view these images.', 403);
        }

        $inspection_plan_data = $inspection_plan->first();

        $inspection_plan_signatures = DB::table('inspection_plan_signatures')
            ->where('inspection_plan_id', $request->inspection_plan_id)
            ->pluck('employee_id')
            ->toArray();

        $inspection_plan_data->sign_off = $inspection_plan_signatures;

        return $this->success($inspection_plan_data, 'Data get successfully!');
    }

    public function deleteImage($id)
    {
        $image = InspectionImage::find($id);
        if (!$image) {
            return $this->message('Image not found.', 404);
        }
        $userTable = $this->getUserTable();
        $inspectionPlan = InspectionPlan::where('id', $image->inspection_plan_id);
        if ($userTable === 'customer') {
            $inspectionPlan->where('customer_id', auth()->id())
                ->where('workspace_id', auth()->user()->current_workspace_id);
        }
        if ($userTable === 'emp') {
            $inspectionPlan->where('customer_id', auth()->user()->customer_id)
                ->where('workspace_id', auth()->user()->workspace_id);
        }
        if (!$inspectionPlan->exists()) {
            return $this->message('You are not authorized to delete this image.', 403);
        }
        $imagePath = public_path($image->image);
        if (file_exists($imagePath)) {
            unlink($imagePath);
        }
        $image->delete();
        return $this->message('Image deleted successfully.');
    }

    public function step4Store(Request $request)
    {
        // try {
        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required',
            'description_box_for_message' => 'nullable|string',
            "sign_off" => 'nullable|array',
            "sign_off.*.emp_id" => 'nullable|integer',
        ]);
        if ($validator->fails()) {
            $log = [
                'employee_id' => auth()->user()->id,
                'message' => 'Inspection description store failed: ' . $validator->errors()->first(),
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Validation error',
            ];
            storeReportsLogs($log);
            return $this->message($validator->errors()->first(), 422);
        }
        $validatedData = $validator->validated();
        $userTable = $this->getUserTable();
        $inspectionPlanQuery = InspectionPlan::where('id', $request->inspection_plan_id)->first();
        if (!$inspectionPlanQuery) {
            return $this->message('Inspection plan not found.', 404);
        }
        if (
            $userTable === 'customer' && ($inspectionPlanQuery->customer_id !== auth()->id() ||
                $inspectionPlanQuery->workspace_id !== auth()->user()->current_workspace_id
            )
        ) {
            return $this->message('You are not authorized to access this inspection plan.', 403);
        }
        if (
            $userTable === 'emp' &&  ($inspectionPlanQuery->customer_id !== auth()->user()->customer_id ||
                $inspectionPlanQuery->workspace_id !== auth()->user()->workspace_id
            )
        ) {
            return $this->message('You are not authorized to access this inspection plan.', 403);
        }

        $inspectionPlanQuery->description = $request->description_box_for_message;
        $inspectionPlanQuery->save();
        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 inspection plan
            $existingEmployeeIds = DB::table('inspection_plan_signatures')
                ->where('inspection_plan_id', $validatedData['inspection_plan_id'])
                ->pluck('employee_id')
                ->toArray();

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

            // Delete records for employees that are no longer in the sign-off list
            if (!empty($employeesToRemove)) {
                DB::table('inspection_plan_signatures')
                    ->where('inspection_plan_id', $validatedData['inspection_plan_id'])
                    ->whereIn('employee_id', $employeesToRemove)
                    ->whereNull('signature')
                    ->delete();
            }
            foreach ($validatedData['sign_off'] as $inspection_signoff) {
                if (empty($inspection_signoff['emp_id']) || empty($validatedData['inspection_plan_id'])) {
                    // Skip this record if emp_id or inspection_plan_id is missing
                    continue;
                }
                $inspection_signoff['inspection_plan_id'] = $validatedData['inspection_plan_id'];
                $inspection_signoff['emp_id'] = $inspection_signoff['emp_id'] ?? 0;

                // Get employee company details with null check
                $empCompanyDetails = EmpCompanyDetails::find($inspection_signoff['emp_id']);
                if ($empCompanyDetails && $empCompanyDetails->employment_type) {
                    $employment_type = EmpType::where('id', $empCompanyDetails->employment_type)->first();
                    $inspection_signoff['employee_type'] = $employment_type ? $employment_type->title : null;
                } else {
                    $inspection_signoff['employee_type'] = null;
                }

                // Get employee personal details with null check
                $empPersonalDetails = EmpPersonalDetails::where('emp_id', $inspection_signoff['emp_id'])->first();
                if ($empPersonalDetails) {
                    $firstName = $empPersonalDetails->first_name ?? '';
                    $middleName = $empPersonalDetails->middle_name ? ' ' . $empPersonalDetails->middle_name : '';
                    $lastName = $empPersonalDetails->last_name ?? '';
                    $inspection_signoff['employee_name'] = trim($firstName . $middleName . ' ' . $lastName);
                } else {
                    // If employee not found, skip this record or set default name
                    $inspection_signoff['employee_name'] = 'Unknown Employee (ID: ' . $inspection_signoff['emp_id'] . ')';
                }

                // Initialize variables


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

                if ($existingRecord) {
                    // Update existing record
                    DB::table('inspection_plan_signatures')
                        ->where('inspection_plan_id', $validatedData['inspection_plan_id'])
                        ->where('employee_id', $inspection_signoff['emp_id'])
                        ->update([
                            'employee_type' => $inspection_signoff['employee_type'],
                            'date' => now()->format('Y-m-d'),
                            'time' => now()->format('H:i:s'),
                            'employee_name' => $inspection_signoff['employee_name'],
                            'updated_at' => now(),
                        ]);
                } else {
                    // Create new record
                    DB::table('inspection_plan_signatures')->insert([
                        'inspection_plan_id' => $validatedData['inspection_plan_id'],
                        'employee_id' => $inspection_signoff['emp_id'],
                        'employee_type' => $inspection_signoff['employee_type'],
                        'employee_name' => $inspection_signoff['employee_name'],
                        'date' => now()->format('Y-m-d'),
                        'time' => now()->format('H:i:s'),
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }
        }
        return $this->success($inspectionPlanQuery, 'Data saved successfully!');
        // } catch (\Exception $e) {
        //     $shortMessage = substr($e->getMessage(), 0, 200) . (strlen($e->getMessage()) > 200 ? '...' : '');
        //     $log = [
        //         'employee_id' => auth()->user()->id,
        //         'message' => 'Error storing inspection description: ' . $shortMessage,
        //         'report_id' => $request->inspection_plan_id ?? null,
        //         'report_type' => 'inspection_report',
        //         'error_type' => 'Exception error',
        //     ];
        //     storeReportsLogs($log);
        //     return $this->message('An error occurred while saving the description.', 500);
        // }
    }

    /**
     * Store Inspection Plan Quick Entry
     * Creates a new inspection plan with minimal data and uploaded PDF
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function inspectionPlanQuickEntryStore(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'document_title' => 'required|string|max:255',
                'document_number' => 'nullable|string|max:255',
                'authorised_by' => 'required|integer|exists:emp_company_details,id',
                'site_id' => 'required|integer|exists:sites,id',
                'issue_date' => 'nullable|date',
                'revision_date' => 'nullable|date|after_or_equal:issue_date',
                'sign_off' => 'nullable|array',
                'sign_off.*.emp_id' => 'required_with:sign_off|integer|exists:emp_company_details,id',
                'file' => 'required|file|max:20480',
            ],
            [
                'file.required' => 'Inspection plan summary PDF is required.',
                'revision_date.after_or_equal' => 'The revision date must be equal to or after the issue date.',
            ]
        );

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

            // Validate site access
            $site = Sites::where('id', $request->site_id)
                ->where('customer_id', $customerId)
                ->where('workspace_id', $workspaceId)
                ->where('active', 1)
                ->where('del', 0)
                ->first();

            if (!$site) {
                return $this->error('Site not found or you do not have access to this site.', 404);
            }

            // Generate revision number
            $revisionNumber = $this->generateRevisionNumber()['revision_number'];
            
            // Create inspection plan
            $inspectionPlan = InspectionPlan::create([
                'title' => $validator->validated()['document_title'],
                'document_number' => $validator->validated()['document_number'],
                'authorised_by' => $validator->validated()['authorised_by'],
                'revision_number' => $revisionNumber,
                'issue_date' => $validator->validated()['issue_date'],
                'revision_date' => $validator->validated()['revision_date'],
                'site_id' => $validator->validated()['site_id'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'process' => '1', // Mark as complete for quick entry
                'report_method' => 1,
            ]);

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

            foreach ($signOffEntries as $entry) {
                // Get employee details
                $empCompanyDetails = EmpCompanyDetails::find($entry['emp_id']);
                $empPersonalDetails = EmpPersonalDetails::where('emp_id', $entry['emp_id'])->first();
                
                if (!$empCompanyDetails || !$empPersonalDetails) {
                    continue; // Skip if employee not found
                }

                // Get employee type
                $employeeType = null;
                if ($empCompanyDetails->employment_type) {
                    $employmentType = EmpType::where('id', $empCompanyDetails->employment_type)->first();
                    $employeeType = $employmentType ? $employmentType->title : null;
                }

                // Get employee name
                $firstName = $empPersonalDetails->first_name ?? '';
                $middleName = $empPersonalDetails->middle_name ? ' ' . $empPersonalDetails->middle_name : '';
                $lastName = $empPersonalDetails->last_name ?? '';
                $employeeName = trim($firstName . $middleName . ' ' . $lastName);

                // Get access role if available
                $accessRole = $empCompanyDetails->access_role ?? null;

                DB::table('inspection_plan_signatures')->insert([
                    'inspection_plan_id' => $inspectionPlan->id,
                    'itpc_id' => null, // Null for quick entry (not associated with checklist step)
                    'employee_id' => $entry['emp_id'],
                    'employee_name' => $employeeName,
                    'employee_type' => $accessRole ?? $employeeType,
                    'signature' => null,
                    'date' => now()->format('Y-m-d'),
                    'time' => now()->format('H:i:s'),
                    'signature_type' => null,
                    'del' => 0,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }

            // Ensure directory exists
            $directory = 'inspectionPlanReport';
            if (!file_exists(public_path($directory))) {
                mkdir(public_path($directory), 0777, true);
            }

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

            if (!$fileUrl) {
                DB::rollBack();
                return $this->error('Failed to upload PDF file.', 422);
            }

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

            DB::commit();

            storeReportsLogs([
                'employee_id' => $authUser->id,
                'message' => 'Inspection plan quick entry saved successfully.',
                'report_id' => $inspectionPlan->id,
                'report_type' => 'inspection_report'
            ]);

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

    /**
     * Edit Inspection Plan Quick Entry
     * Fetches existing quick entry data for editing
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function inspectionPlanQuickEntryEdit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'inspection_plan_id' => 'required|integer|exists:inspection_plans,id',
        ]);

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

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

            // Get sign_off entries (signatures with itpc_id = null for quick entry)
            $signOffEntries = DB::table('inspection_plan_signatures')
                ->where('inspection_plan_id', $inspectionPlan->id)
                ->whereNull('itpc_id')
                ->where('del', 0)
                ->get()
                ->map(function ($signature) {
                    return [
                        'emp_id' => $signature->employee_id,
                        'employee_name' => $signature->employee_name,
                        'date' => $signature->date,
                    ];
                })
                ->toArray();

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

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

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

    /**
     * Update Inspection Plan Quick Entry
     * Updates existing quick entry data
     * 
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function inspectionPlanQuickEntryUpdate(Request $request)
    {
        $validator = Validator::make(
            $request->all(),
            [
                'inspection_plan_id' => 'required|integer|exists:inspection_plans,id',
                'document_title' => 'required|string|max:255',
                'document_number' => 'nullable|string|max:255',
                'authorised_by' => 'required|integer|exists:emp_company_details,id',
                'site_id' => 'required|integer|exists:sites,id',
                'issue_date' => 'nullable|date',
                'revision_date' => 'nullable|date|after_or_equal:issue_date',
                'sign_off' => 'nullable|array',
                'sign_off.*.emp_id' => 'required_with:sign_off|integer|exists:emp_company_details,id',
                'file' => 'nullable|file|max:20480',
            ],
            [
                'revision_date.after_or_equal' => 'The revision date must be equal to or after the issue date.',
            ]
        );

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

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

            // Validate site access
            $site = Sites::where('id', $request->site_id)
                ->where('customer_id', $customerId)
                ->where('workspace_id', $workspaceId)
                ->where('active', 1)
                ->where('del', 0)
                ->first();

            if (!$site) {
                return $this->error('Site not found or you do not have access to this site.', 404);
            }

            // Update inspection plan
            $inspectionPlan->update([
                'title' => $request->document_title,
                'document_number' => $request->document_number,
                'authorised_by' => $request->authorised_by,
                'site_id' => $request->site_id,
                'issue_date' => $request->issue_date,
                'revision_date' => $request->revision_date,
                'process' => 1,
            ]);

            // Update sign_off entries (only those with itpc_id = null for quick entry)
            $currentEmployeeIds = collect($request->input('sign_off', []))
                ->pluck('emp_id')
                ->filter(function($empId) {
                    return !empty($empId);
                })
                ->toArray();

            $existingEmployeeIds = DB::table('inspection_plan_signatures')
                ->where('inspection_plan_id', $inspectionPlan->id)
                ->whereNull('itpc_id')
                ->where('del', 0)
                ->pluck('employee_id')
                ->toArray();

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

            // Delete records for employees that are no longer in the sign-off list (only quick entry signatures)
            if (!empty($employeesToRemove)) {
                DB::table('inspection_plan_signatures')
                    ->where('inspection_plan_id', $inspectionPlan->id)
                    ->whereNull('itpc_id')
                    ->whereNull('signature') // Only delete if signature is not provided
                    ->whereIn('employee_id', $employeesToRemove)
                    ->delete();
            }

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

                // Get employee details
                $empCompanyDetails = EmpCompanyDetails::find($entry['emp_id']);
                $empPersonalDetails = EmpPersonalDetails::where('emp_id', $entry['emp_id'])->first();
                
                if (!$empCompanyDetails || !$empPersonalDetails) {
                    continue; // Skip if employee not found
                }

                // Get employee type
                $employeeType = null;
                if ($empCompanyDetails->employment_type) {
                    $employmentType = EmpType::where('id', $empCompanyDetails->employment_type)->first();
                    $employeeType = $employmentType ? $employmentType->title : null;
                }

                // Get employee name
                $firstName = $empPersonalDetails->first_name ?? '';
                $middleName = $empPersonalDetails->middle_name ? ' ' . $empPersonalDetails->middle_name : '';
                $lastName = $empPersonalDetails->last_name ?? '';
                $employeeName = trim($firstName . $middleName . ' ' . $lastName);

                // Get access role if available
                $accessRole = $empCompanyDetails->access_role ?? null;

                $existingRecord = DB::table('inspection_plan_signatures')
                    ->where('inspection_plan_id', $inspectionPlan->id)
                    ->whereNull('itpc_id')
                    ->where('employee_id', $entry['emp_id'])
                    ->where('del', 0)
                    ->first();

                if ($existingRecord) {
                    // Update existing record (don't overwrite signature if it exists)
                    DB::table('inspection_plan_signatures')
                        ->where('inspection_plan_id', $inspectionPlan->id)
                        ->whereNull('itpc_id')
                        ->where('employee_id', $entry['emp_id'])
                        ->update([
                            'employee_name' => $employeeName,
                            'employee_type' => $accessRole ?? $employeeType,
                            'date' => now()->format('Y-m-d'),
                            'time' => now()->format('H:i:s'),
                            'updated_at' => now(),
                        ]);
                } else {
                    // Create new record
                    DB::table('inspection_plan_signatures')->insert([
                        'inspection_plan_id' => $inspectionPlan->id,
                        'itpc_id' => null,
                        'employee_id' => $entry['emp_id'],
                        'employee_name' => $employeeName,
                        'employee_type' => $accessRole ?? $employeeType,
                        'signature' => null,
                        'date' => now()->format('Y-m-d'),
                        'time' => now()->format('H:i:s'),
                        'signature_type' => null,
                        'del' => 0,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }

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

            if ($request->hasFile('file')) {
                // Ensure directory exists
                $directory = 'inspectionPlanReport';
                if (!file_exists(public_path($directory))) {
                    mkdir(public_path($directory), 0777, true);
                }

                $uploadResult = $this->handleFileImageUpload($request, $directory, $existingFilePath);
                $fileUrl = $uploadResult['path'] ?? $fileUrl;
            }

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

            DB::commit();

            storeReportsLogs([
                'employee_id' => $authUser->id,
                'message' => 'Inspection plan quick entry updated successfully.',
                'report_id' => $inspectionPlan->id,
                'report_type' => 'inspection_report'
            ]);

            return $this->success([
                'inspection_plan_id' => $inspectionPlan->id,
                'pdf_url' => $fileUrl,
            ], 'Inspection plan 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' => 'Inspection plan quick entry update error: ' . $shortMessage,
                'report_id' => $request->inspection_plan_id,
                'report_type' => 'inspection_report',
                'error_type' => 'Exception error'
            ]);
            return $this->error('An error occurred: ' . $shortMessage, 500);
        }
    }
}
