<?php

namespace App\Http\Controllers;

use App\Models\Adminsettings;
use App\Models\Company;
use App\Models\CompanyContactPerson;
use App\Models\EmpAccess;
use App\Models\EmpCompanyDetails;
use App\Models\EmpDocuments;
use App\Models\EmpEmergencyContacts;
use App\Models\EmployeeAttendance;
use App\Models\EmployeeBreak;
use App\Models\EmpPermit;
use App\Models\EmpPersonalDetails;
use App\Models\EmpTeam;
use App\Models\EmpTeamsMember;
use App\Models\EmpType;
use App\Models\EmpWorkerType;
use App\Models\EmpWorkExperience;
use App\Models\Fine;
use App\Models\Fund;
use App\Models\HazardRisk;
use App\Models\HelpdeskTicket;
use App\Models\HelpdeskTicketCategories;
use App\Models\LeavePackage;
use App\Models\LeaveRequest;
use App\Models\LeaveType;
use App\Models\LinkManagement;
use App\Models\Defect;
use App\Models\DefectHistory;
use App\Models\DefectImage;
use App\Models\Project;
use App\Models\ProjectSite;
use App\Models\PublicHoliday;
use App\Models\RequiredDocument;
use App\Models\RequiredDocumentField;
use App\Models\Role;
use App\Models\RosterAssign;
use App\Models\RosterTemplate;
use App\Models\SafetyDataSheet;
use App\Models\Salary;
use App\Models\Sites;
use App\Models\Swms;
use App\Models\SwmsApprovedBy;
use App\Models\SwmsAwnswers;
use App\Models\swmsDevelopedBy;
use App\Models\SwmsGeneralNote;
use App\Models\SwmsGeneralNoteAnswers;
use App\Models\SwmsHazardRiskPivot;
use App\Models\SwmsMeta;
use App\Models\SwmsProtectionTool;
use App\Models\MeetingNoteDocumentsPdf;
use App\Models\Overtime;
use App\Models\Payroll;
use App\Models\ProjectMeta;
use App\Models\SwmsProtectionToolPivot;
use App\Models\SwmsQuestions;
use App\Models\SwmsSafetyPlanningAnswers;
use App\Models\SwmsSafetyPlanningQuestion;
use App\Models\SwmsSignature;
use App\Models\SwmsTaskDetail;
use App\Models\Tier;
use App\Models\User;
use App\Models\WhsAdditionalPerson;
use App\Models\WhsConductedBy;
use App\Models\WhsItem;
use App\Models\WhsReport;
use App\Models\WhsReportHazards;
use App\Models\WhsReportItem;
use App\Models\Workspace;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Database\Seeders\CustomerConstructionRolesSeeder;
use Carbon\Carbon;
use App\Models\InspectionPlan;
use App\Models\InspectionPlanTable;
use App\Models\InspectionPlanMeta;
use App\Models\InspectionPlanGeneral;
use App\Models\InspectionPlanSignature;
use App\Models\InspectionPlanChecklist;
use App\Models\InspectionImage;
use Faker\Factory as Faker;
use App\Models\IncidentReport;
use App\Models\IncidentClassificationReport;
use App\Models\IncidentDocument;
use App\Models\IncidentInvolvedPersonDetail;
use App\Models\IncidentEmployerDetail;
use App\Models\IncidentReportMeta;
use App\Models\IncidentReportQuestionAnswer;
use App\Models\IncidentInjuryManagement;
use App\Models\IncidentFinalClassification;
use App\Models\IncidentRiskCategoryDetail;
use App\Models\IncidentWitnes;
use App\Models\IncidentSignoff;
use App\Models\IncidentInjuryClassification;
use App\Models\IncidentReportQuestion;
use App\Models\IncidentRiskCategory;
use App\Models\IncidentReportedBy;
use App\Models\IncidentReportedTo;
use App\Models\IncidentNotifiedTo;
use App\Models\IncidentReportNotifiableClassification;
use App\Models\IncidentInvolvedPersonTraining;
use App\Models\IncidentEmployeeInjuryType;
use App\Models\IncidentInjuryType;
use App\Models\IncidentNotifiableClassification;
use App\Models\IncidentImage; // Make sure this is imported at the top
use App\Models\Meeting;
use App\Models\MeetingDocument;
use App\Models\MeetingDocumentNote;
use App\Models\MeetingDocumentSetting;
use App\Models\MeetingHistory;
use App\Models\MeetingNoteTable;
use App\Models\MeetingOrganiser;
use App\Models\MeetingUser;
use App\Models\MeetingGuestUser;
use App\Models\Training;
use App\Models\WhsqReport;
use App\Models\WHSQE_TableOfContent;
use App\Models\WHSQE_TableOfContentChild;
use App\Models\WHSQE_TableOfContentGrandChild;
use App\Models\WHSQETableOfContentMeta;
use App\Models\WHSQECustomerSelectedSettings;
use App\Models\WHSQEContentOption;
use App\Models\WHSQEContentDate;
use App\Models\WhsqSignature;
use App\Models\Asset;
use App\Http\Controllers\Traits\AdminAuthTrait;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Traits\AdminGeneralSettingTrait;
use App\Http\Controllers\Traits\HelperTrait;
class DemoController extends Controller
{
    use AdminAuthTrait;
    
    public function createDemoCustomer($user)
    {
        $customer = User::find($user->id);
        //  if demo_data is 1, if so, skip creation
        if ($customer->demo_data == 1) {
            return $this->message('Demo data already created for this user.', 403);
        }

        $workspace = Workspace::where('customer_id', $customer->id)->first();

        DB::beginTransaction();
        // try {
            $clients = $this->createDemoClients($customer->id, $workspace->id);

            $employees = $this->createDemoEmployees($customer->id, $workspace->id);

            $sites = $this->createDemoSites($customer->id, $workspace->id, $employees['specialEmployees']);

            $projects = $this->createDemoProjects($customer->id, $workspace->id, $clients,$sites);

            $allEmployees = array_merge($employees['employees'], EmpCompanyDetails::where('customer_id', $customer->id)->where('workspace_id', $workspace->id)->get()->all());
            $this->createDemoRosters($customer->id, $workspace->id, ['employees' => $allEmployees]);

            $this->storeDemoRosterSettings($customer->id, $workspace->id);
            $this->storeDemoWhsReportSettings($customer->id, $workspace->id, $customer->id);
            $this->storeDemoInspectionPlanSettings($customer->id, $workspace->id);
            $this->storeDemoSwmsSettings($customer->id, $workspace->id, $customer->id);
            $this->storeDemoIncidentSettings($customer->id, $workspace->id, $customer->id);
            $this->storeDemoSafetyDataSheets($customer->id, $workspace->id, $customer->id);
            $this->storeDemoHelpdeskTickets($customer->id, $workspace->id, $customer->id);
            $this->storeDemoAdminSettings($customer->id, $workspace->id);
            $this->storeDemoInvitedEmployee($customer->id, $workspace->id);
            $this->markDemoAttendanceAccordingToRoster($customer->id, $workspace->id);
            $this->createDemoLeaveData($customer->id, $workspace->id);
            $this->createDemoSuperFunds($customer->id, $workspace->id);
            $this->createDemoSwmsReport($customer->id, $workspace->id);
            $this->createDemoWhsReports($customer->id, $workspace->id);
            $this->createDemoWhsqReports($customer->id, $workspace->id);
            $this->createDemoInspectionPlan($customer->id, $workspace->id);
            $this->createDemoIncidentReport($customer->id, $workspace->id);
            $this->createDemoMeeting($customer->id, $workspace->id);
            $this->createDemoDefects($customer->id, $workspace->id);
            $this->createDemoSiteDiaries($customer->id, $workspace->id);
            $this->createDemoAssets($customer->id, $workspace->id);
            $this->createDemoOvertime($customer->id, $workspace->id);

            // Update demo_data to 1 after successful creation
            $customer->demo_data = 1;
            $customer->save();

            DB::commit();

            return $this->success(
                [
                    'customer' => $customer,
                    'workspace' => $workspace,
                    'sites' => $sites,
                    'employees' => $employees,
                    'clients' => $clients,
                    'projects' => $projects
                ],
                'Demo customer created successfully with all related data'
            );
        // } catch (\Exception $e) {
        //     DB::rollBack();
        //     return $this->message1('Error creating demo data: ' . $e->getMessage(), 500);
        // }
    }

    public function generateSecretKey()
    {
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $length = 20;
    
        do {
            $secretKey = substr(str_shuffle(str_repeat($characters, ceil($length / strlen($characters)))), 0, $length);
        } while (LinkManagement::where('secret_key', $secretKey)->exists());
    
        return $secretKey;
    }
    private function createDemoSites($customerId, $workspaceId, $specialEmployees)
    {
        $supervisorId = $specialEmployees['SPV']->id;
        $formanId = $specialEmployees['FM']->id;
        $ssoId = $specialEmployees['SSO']->id;

        $sites = [];
        $siteNames = [
            'Headquarters',
            'Downtown Office',
            'Manufacturing Plant',
            'Distribution Center',
            'Research Facility'
        ];
        
        $addresses = [
            '123 Main Street, New York, NY 10001',
            '456 Market St, San Francisco, CA 94103',
            '789 Industrial Blvd, Chicago, IL 60607',
            '101 Logistics Way, Atlanta, GA 30303',
            '555 Innovation Dr, Boston, MA 02110'
        ];
        
        $coordinates = [
            ['latitude' => 40.7128, 'longitude' => -74.0060],  // New York
            ['latitude' => 37.7749, 'longitude' => -122.4194], // San Francisco
            ['latitude' => 41.8781, 'longitude' => -87.6298],  // Chicago
            ['latitude' => 33.7490, 'longitude' => -84.3880],  // Atlanta
            ['latitude' => 42.3601, 'longitude' => -71.0589]   // Boston
        ];
        
        $companyClients = Company::where('customer_id', $customerId)
                                ->where('workspace_id', $workspaceId)
                                ->take(5)
                                ->get()
                                ->pluck('id')
                                ->toArray();
        while (count($companyClients) < 5) {
            $companyClients[] = 1; 
        }
        
        $supervisors = EmpCompanyDetails::where('access_role', 'supervisor')
                          ->where('customer_id', $customerId)
                          ->where('workspace_id', $workspaceId)
                          ->take(5)
                          ->get()
                          ->pluck('id')
                          ->toArray();
        
        while (count($supervisors) < 5) {
            $supervisors[] = 1; 
        }
    
        foreach ($siteNames as $index => $siteName) {
            $streetAddress = explode(',', $addresses[$index])[0];
            
            $site = Sites::create([
                'title' => $siteName,
                'address' => $addresses[$index],
                'street_address' => $streetAddress,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'latitude' => $coordinates[$index]['latitude'],
                'longitude' => $coordinates[$index]['longitude'],
                'area_radius' => rand(1, 5), 
                'company_client' => $companyClients[$index],
                'supervisor_id' => $supervisorId,
                'forman_id' => $formanId,
                'sso_id' => $ssoId,
                'site_state' => rand(1, 3),
                'contact_person' => 'Contact Person ' . ($index + 1),
                'contact_email' => 'site' . ($index + 1) . '@example.com',
                'contact_phone' => '555-' . str_pad($index + 1, 3, '0', STR_PAD_LEFT),
                'created_by' => $supervisorId,
            ]);
            
            $sites[] = $site;
        }
        
        return $sites;
    }

    private function createDemoEmployees($customerId, $workspaceId)
    {
        $seeder = new CustomerConstructionRolesSeeder();
        // createConstructionRoles now only creates default team (roles are global)
        $seeder->createConstructionRoles($customerId, $workspaceId, $customerId);
        
        // Fetch global roles instead of creating them per customer
        $roles = Role::where('del', '0')->get();
        $workPermits = $this->getOrCreateWorkPermits($customerId, $workspaceId, $roles);
        $tier = Tier::where('workspace_id', $workspaceId)->where('customer_id', $customerId)->first();
        $requiredDocumentFields = $this->createRequiredDocuments($customerId, $workspaceId);
        $names = $this->generateEmployeeNames();
        $employees = $this->createEmployees($customerId, $workspaceId, $names, $roles, $workPermits, $tier, $requiredDocumentFields);
        $this->createTeamAndLink($customerId, $workspaceId, $employees, $roles, $tier, $workPermits, $requiredDocumentFields);
        return $employees;
    }



    private function getOrCreateWorkPermits($customerId, $workspaceId, $roles)
    {
        $workPermits = EmpPermit::where('workspace_id', $workspaceId)->get();
        if ($workPermits->isEmpty()) {
            $workPermits = [
                EmpPermit::create([
                    'title' => 'Standard Access',
                    'role_id' => $roles[0]->id,
                    'created_by' => $customerId,
                    'workspace_id' => $workspaceId,
                    'customer_id' => $customerId,
                ])
            ];
        }
        return $workPermits;
    }

    private function createRequiredDocuments($customerId, $workspaceId)
    {
        $docId = RequiredDocument::insertGetId([
            'title' => 'Identity Verification',
            'for_who' => 'both',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => '0',
        ]);
        $fields = [
            ['field_type' => 'file', 'field_name' => 'Identity Card', 'doc_id' => $docId, 'field_required' => '1', 'priority' => '1', 'status' => '1'],
            ['field_type' => 'date', 'field_name' => 'Date of Birth', 'doc_id' => $docId, 'field_required' => '1', 'priority' => '2', 'status' => '1'],
            ['field_type' => 'text', 'field_name' => 'Full Name', 'doc_id' => $docId, 'field_required' => '1', 'priority' => '3', 'status' => '1']
        ];
        RequiredDocumentField::insert($fields);
        return RequiredDocumentField::where('doc_id', $docId)->get();
    }

    private function generateEmployeeNames()
    {
        $faker = Faker::create();
        $names = [];
        $maxAttempts = 100;
        $attempts = 0;

        while (count($names) < 5 && $attempts < $maxAttempts) {
            $firstName = $faker->firstName;
            $middleName = $faker->firstName;
            $lastName = $faker->lastName;
            $fullName = $firstName . ($middleName ? ' ' . $middleName : '') . ' ' . $lastName;

            if (!in_array($fullName, array_column($names, 'full'))) {
                $names[] = [
                    'full' => $fullName,
                    'first' => $firstName,
                    'middle' => $middleName,
                    'last' => $lastName
                ];
            }
            $attempts++;
        }

        // Fallback if we couldn't generate enough unique names
        while (count($names) < 5) {
            $firstName = $faker->firstName;
            $lastName = $faker->lastName;
            $fullName = $firstName . ' ' . $lastName;
            $names[] = [
                'full' => $fullName,
                'first' => $firstName,
                'middle' => null,
                'last' => $lastName
            ];
        }

        return $names;
    }

    private function createEmployees($customerId, $workspaceId, $names, $roles, $workPermits, $tier, $createdFields)
    {
        $faker = Faker::create();
        $roles = collect($roles); // <-- Add this line
        $workExperience = EmpWorkExperience::create([
            'title' => 'Game Development',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'created_by' => $customerId,
        ]);

        $workType = EmpWorkerType::create([
            'title' => 'Permanent',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'created_by' => $customerId,
        ]);
        $employees = [];
        $empType = EmpType::create(['title' => 'Part-time', 'customer_id' => $customerId, 'workspace_id' => $workspaceId, 'created_by' => $customerId]);

        // Find required roles
        $roleForeman = $roles->firstWhere('code', 'FM');
        $roleSSO = $roles->firstWhere('code', 'SSO');
        $roleSupervisor = $roles->firstWhere('code', 'SPV');

        // 1. Create 3 special employees
        $requiredRoles = [
            ['role' => $roleForeman, 'job_title' => 'Foreman', 'department' => 'Operations'],
            ['role' => $roleSSO, 'job_title' => 'Site Safety Officer', 'department' => 'Safety'],
            ['role' => $roleSupervisor, 'job_title' => 'Supervisor', 'department' => 'Management'],
        ];
        $specialEmployees = [];
        for ($i = 0; $i < 3; $i++) {
            $nameArr = $names[$i];
            $employee = $this->createSingleEmployee($customerId, $workspaceId, $nameArr, $empType, $workPermits, $tier, $createdFields, $requiredRoles[$i]['role'], $requiredRoles[$i]['job_title'], $requiredRoles[$i]['department']);
            $specialEmployees[$requiredRoles[$i]['role']->code] = $employee;
            $employees[] = $employee;
        }

        // 2. Create 2 more employees with any other roles (not FM, SSO, SPV)
        $otherRoles = $roles->filter(function($role) {
            return !in_array($role->code, ['FM', 'SSO', 'SPV']);
        })->values();

        for ($i = 3; $i < 5; $i++) {
            $nameArr = $names[$i];
            $role = $otherRoles[($i-3) % $otherRoles->count()];
            $employee = $this->createSingleEmployee($customerId, $workspaceId, $nameArr, $empType, $workPermits, $tier, $createdFields, $role, $role->title, 'General');
            $employees[] = $employee;
        }

        // Return both for use in site creation
        return [
            'employees' => $employees,
            'specialEmployees' => $specialEmployees
        ];
    }

    private function createSingleEmployee($customerId, $workspaceId, $nameArr, $empType, $workPermits, $tier, $createdFields, $role, $jobTitle, $department)
    {
        $faker = Faker::create();
        $email = $faker->unique()->email;
        $taxFileNo = 'TFN' . rand(100000, 999999) . strtoupper(Str::random(2));
        $attendanceEffectiveFrom = now()->subDays(rand(1, 30))->toDateString();
        $dateOfBirth = now()->subYears(rand(20, 40))->subDays(rand(1, 365))->toDateString();

        $employee = EmpCompanyDetails::create([
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'employee_email' => $email,
            'employment_type' => $empType->id,
            'work_permit_type' => $workPermits[0]->id,
            'access_role' => $role->code,
            'tier_id' => $tier->id,
            'start_date' => now()->subDays(rand(10, 60)),
            'end_date' => now()->addDays(rand(90, 180)),
            'plan_expire_date' => now()->addMonths(rand(3, 12)),
            'plan_effective_from' => now()->subDays(rand(10, 30)),
            'employment_start_date' => now()->subMonths(rand(1, 24))->toDateString(),
            'employment_end_date' => now()->addYears(rand(1, 5))->toDateString(),
            'compeleted' => 1,
            'status' => 1,
            'created_by' => $customerId,
            'updated_by' => $customerId,
            'employee_id' => 'EMP' . strtoupper(Str::random(4)),
            'job_title' => $jobTitle,
            'department' => $department,
            'tax_file_no' => $taxFileNo,
            'attendance_effective_from' => $attendanceEffectiveFrom,
            'approved' => '1',
            'approved_by' => $customerId,
            'approved_status' => 0,
            'approved_at' => date('d-m-Y'),
        ]);
        $bloodGroups = ['A+', 'A-', 'B+', 'B-', 'O+', 'O-', 'AB+', 'AB-'];
        EmpPersonalDetails::create([
            'emp_id' => $employee->id,
            'first_name' => $nameArr['first'],
            'middle_name' => $nameArr['middle'],
            'last_name' => $nameArr['last'],
            'mobile' => '04' . rand(10000000, 99999999),
            'streat_address' => rand(1, 999) . ' Main St',
            'suburb' => 'Suburb' . chr(rand(65, 90)),
            'state' => 'State' . chr(rand(65, 90)),
            'postcode' => rand(2000, 2999),
            'image' => 'assets/img/default.png',
            'account_holder_name' => $faker->name,
            'account_number' => $faker->randomNumber(3, true),
            'bank_name' => $faker->company,
            'ibn_number' => $faker->randomNumber(3, true),
            'date_of_birth' => $dateOfBirth,
            'blood_group' => $bloodGroups[array_rand($bloodGroups)],
            'created_by' => $customerId,
            'del' => 0,
        ]);
        DB::table('user_meta')->insert([
            'emp_id' => $employee->id,
            'option' => 'employee_payroll_or_external_id',
            'value' => 'PAY' . rand(10000, 99999),
            'del' => 0,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        $this->createEmergencyContact($employee->id, $customerId);
        $this->populateRequiredDocumentFields($employee->id, $createdFields, $nameArr['full'], $dateOfBirth);
        EmpAccess::create([
            'emp_id' => $employee->id,
            'web_app' => 1,
            'mobile_app' => 1,
            'attendance' => 1,
            'timesheet_reminders' => 1,
            'email' => 1,
            'timesheet' => 1,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        return $employee;
    }

    private function createEmergencyContact($empId, $customerId)
    {
        $faker = Faker::create();
        $relationships = ['Mother', 'Father', 'Spouse', 'Sister', 'Brother', 'Friend', 'Colleague'];
        EmpEmergencyContacts::create([
            'emp_id' => $empId,
            'name' => $faker->name,
            'relation' => $relationships[array_rand($relationships)],
            'phone' => '04' . rand(10000000, 99999999),
            'address' => rand(1, 999) . ' Emergency St, City ' . chr(rand(65, 90)),
            'del' => '0',
            'created_by' => $customerId,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function populateRequiredDocumentFields($empId, $createdFields, $fullName, $dateOfBirth)
    {
        foreach ($createdFields as $field) {
            $empDocumentData = [
                'emp_id' => $empId,
                'required_document' => $field->doc_id,
                'required_document_field' => $field->id,
            ];
            switch ($field->field_name) {
                case 'Identity Card':
                    $empDocumentData['value'] = 'assets/img/default.png';
                    break;
                case 'Date of Birth':
                    $empDocumentData['value'] = $dateOfBirth;
                    break;
                case 'Full Name':
                    $empDocumentData['value'] = $fullName;
                    break;
            }
            EmpDocuments::create($empDocumentData);
        }
    }

    private function createTeamAndLink($customerId, $workspaceId, $employees, $roles, $tier, $workPermits, $createdFields)
    {
        $specialEmployees = $employees['specialEmployees'];
        $team = EmpTeam::create([
            'title' => 'Main Team',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'supervisor' => $specialEmployees['SPV']->id, // Use the actual supervisor
            'description' => 'Main operational team',
            'created_by' => $customerId,
        ]);
        foreach ($employees['employees'] as $employee) {
            EmpTeamsMember::create([
                'team_id' => $team->id,
                'emp_id' => $employee->id,
                'workspace_id' => $workspaceId,
                'customer_id' => $customerId,
                'created_by' => $customerId,
            ]);
        }
        $unique = uniqid();
        $key = $this->generateSecretKey();
        $faker = Faker::create();
        LinkManagement::create([
            'name' => 'Demo Link ' . $unique,
            'email' => $faker->email,
            'phone' => $faker->phoneNumber,
            'address' => $faker->address,   
            'title' => 'Demo Link ' . $unique,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'description' => 'This is a demo link for testing. ID: ' . $unique,
            'role_id' => $roles[2]->id,
            'tier_id' => $tier->id,
            'working_days' => 'Monday,Tuesday,Wednesday,Thursday,Friday',
            'number_of_days' => 5,
            'start_time' => '09:00:00',
            'end_time' => '17:00:00',
            'paid_break' => 60,
            'color_code' => '#' . substr(md5(mt_rand()), 0, 6),
            'secret_key' => $key,
            'created_by' => $customerId,
            'status' => '1',
            'team_ids' => $team->id,
        ]);
        // Add this line to create the extra employees for the link:
        $this->createLinkDemoEmployees($customerId, $workspaceId, $team, $roles, $tier, $workPermits, $createdFields, $key);
    }

    private function createLinkDemoEmployees($customerId, $workspaceId, $team, $roles, $tier, $workPermits, $createdFields, $key)
    {
        $faker = Faker::create();
        $empType = EmpType::create([
            'title' => 'Permanent',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'created_by' => $customerId,
        ]);
        
        $linkEmployees = [];
        
        for ($i = 1; $i <= 2; $i++) {
            $attendanceEffectiveFrom = now()->subDays(rand(1, 30))->toDateString();
            $empUnique = uniqid("emp{$i}_");
            $email = $faker->unique()->email;
            $firstName = $faker->firstName;
            $lastName = $faker->lastName;
            $jobTitle = $i === 1 ? 'Developer' : 'Designer';
            $department = $i === 1 ? 'IT' : 'Design';
            $dateOfBirth = $i === 1 ? '1990-01-01' : '1992-02-02';

            $employee = EmpCompanyDetails::create([
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'employee_email' => $email,
                'employment_type' => $empType->id,
                'work_permit_type' => $workPermits[0]->id,
                'link_key' => $key,
                'access_role' => $roles[2]->code,
                'tier_id' => $tier->id,
                'start_date' => now(),
                'end_date' => now()->addYear(),
                'employment_start_date' => now()->subMonths(rand(1, 24))->toDateString(),
                'employment_end_date' => now()->addYears(rand(1, 5))->toDateString(),
                'attendance_effective_from' => $attendanceEffectiveFrom,
                'plan_expire_date' => now()->addYear(),
                'plan_effective_from' => now(),
                'compeleted' => 1,
                'status' => 1,
                'created_by' => $customerId,
                'updated_by' => $customerId,
                'employee_id' => strtoupper($empUnique),
                'job_title' => $jobTitle,
                'department' => $department,
                'tax_file_no' => 'TFN' . rand(100000, 999999),
                'invited' => 0,
                'approved' => 1,
                'approved_by' => $customerId,
                'approved_status' => 1,
                'approved_at' => now()->format('d-m-Y'),
            ]);

            EmpPersonalDetails::create([
                'emp_id' => $employee->id,
                'first_name' => $firstName,
                'middle_name' => $faker->lastName,
                'last_name' => $lastName,
                'mobile' => '04' . rand(10000000, 99999999),
                'streat_address' => rand(1, 999) . ' Main St',
                'suburb' => 'Suburb' . chr(rand(65, 90)),
                'state' => 'State' . chr(rand(65, 90)),
                'postcode' => rand(2000, 2999),
                'image' => 'assets/img/default.png',
                'account_holder_name' => $faker->name,
                'account_number' => $faker->randomNumber(3, true),
                'bank_name' => $faker->company,
                'ibn_number' => $faker->randomNumber(3, true),
                'date_of_birth' => $dateOfBirth,
                'blood_group' => $i === 1 ? 'A+' : 'B+',
                'created_by' => $customerId,
                'del' => 0,
            ]);
            foreach ($createdFields as $field) {
                $empDocumentData = [
                    'emp_id' => $employee->id,
                    'required_document' => $field->doc_id,
                    'required_document_field' => $field->id,
                ];
                switch ($field->field_name) {
                    case 'Identity Card':
                        $empDocumentData['value'] = 'assets/img/default.png';
                        break;
                    case 'Date of Birth':
                        $empDocumentData['value'] = $dateOfBirth;
                        break;
                    case 'Full Name':
                        $empDocumentData['value'] = $firstName . ' ' . $lastName;
                        break;
                }
                EmpDocuments::create($empDocumentData);
            }
            
            // Add to linkEmployees array for roster assignment
            $linkEmployees[] = $employee;
            
            EmpTeamsMember::create([
                'team_id' => $team->id,
                'emp_id' => $employee->id,
                'workspace_id' => $workspaceId,
                'customer_id' => $customerId,
                'created_by' => $customerId,
            ]);
            EmpAccess::create([
                'emp_id' => $employee->id,
                'web_app' => 1,
                'mobile_app' => 1,
                'attendance' => 1,
                'timesheet_reminders' => 1,
                'email' => 1,
                'timesheet' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
            EmpEmergencyContacts::create([
                'emp_id' => $employee->id,
                'name' => 'Emergency Contact',
                'relation' => 'Friend',
                'phone' => '04' . rand(10000000, 99999999),
                'address' => rand(1, 999) . ' Emergency St, City ' . chr(rand(65, 90)),
                'del' => '0',
                'created_by' => $customerId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
            DB::table('user_meta')->insert([
                'emp_id' => $employee->id,
                'option' => 'employee_payroll_or_external_id',
                'value' => 'PAY' . rand(10000, 99999),
                'del' => 0,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
        
        // Create roster template based on link management settings
        $linkManagement = LinkManagement::where('secret_key', $key)->first();
        if ($linkManagement && !empty($linkEmployees)) {
            $this->createLinkBasedRosters($customerId, $workspaceId, $linkEmployees, $linkManagement);
        }
    }

    private function createLinkBasedRosters($customerId, $workspaceId, $linkEmployees, $linkManagement)
    {
        // Create a roster template based on link management settings
        $rosterTemplate = RosterTemplate::create([
            'start_time' => $linkManagement->start_time,
            'end_time' => $linkManagement->end_time,
            'color_code' => $linkManagement->color_code ?: '#4CAF50',
            'break_minutes' => $linkManagement->paid_break ?: 60,
            'shift_notes' => 'Roster based on Link Management: ' . $linkManagement->title,
            'repeat_shift' => 0,
            'repeat_every' => null,
            'end_date' => now()->addWeek()->toDateString(),
            'is_saved' => 1,
            'status' => 1,
            'working_hours' => $this->calculateWorkingHours($linkManagement->start_time, $linkManagement->end_time, $linkManagement->paid_break),
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'created_by' => $customerId,
        ]);

        // Parse working days from link management
        $workingDays = explode(',', $linkManagement->working_days ?: 'Monday,Tuesday,Wednesday,Thursday,Friday');
        $dayMapping = [
            'Monday' => 1, 'Tuesday' => 2, 'Wednesday' => 3, 'Thursday' => 4, 
            'Friday' => 5, 'Saturday' => 6, 'Sunday' => 0
        ];
        
        $workingDayNumbers = array_map(function($day) use ($dayMapping) {
            return $dayMapping[trim($day)] ?? null;
        }, $workingDays);
        $workingDayNumbers = array_filter($workingDayNumbers, function($day) {
            return $day !== null;
        });

        // Create roster assignments for the next number_of_days based on working days
        $startDate = now()->startOfDay();
        $numberOfDays = $linkManagement->number_of_days ?: 7;
        $scheduledDays = 0;
        $currentDate = clone $startDate;

        // Loop until we've scheduled the required number of working days
        while ($scheduledDays < $numberOfDays && $currentDate->diffInDays($startDate) < 30) { // safety limit
            $dayOfWeek = $currentDate->dayOfWeek;
            
            // Check if current day is in working days
            if (in_array($dayOfWeek, $workingDayNumbers)) {
                foreach ($linkEmployees as $employee) {
                    // Check if roster assignment already exists for this employee on this date
                    $existingAssignment = RosterAssign::where('assign_to', $employee->id)
                        ->where('schedule_date', $currentDate->toDateString())
                        ->where('customer_id', $customerId)
                        ->where('workspace_id', $workspaceId)
                        ->first();
                    
                    // Only create if assignment doesn't exist
                    if (!$existingAssignment) {
                        RosterAssign::create([
                            'assign_to' => $employee->id,
                            'roster_template_id' => $rosterTemplate->id,
                            'schedule_date' => $currentDate->toDateString(),
                            'customer_id' => $customerId,
                            'workspace_id' => $workspaceId,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                    }
                }
                $scheduledDays++;
            }
            $currentDate->addDay();
        }
        
        return $rosterTemplate;
    }

    private function calculateWorkingHours($startTime, $endTime, $breakMinutes = 0)
    {
        if (!$startTime || !$endTime) {
            return 8; // default 8 hours
        }
        
        $start = new \DateTime($startTime);
        $end = new \DateTime($endTime);
        $diff = $start->diff($end);
        
        $totalMinutes = $diff->h * 60 + $diff->i;
        $workingMinutes = $totalMinutes - ($breakMinutes ?: 0);
        
        return round($workingMinutes / 60, 1);
    }

    private function createDemoClients($customerId, $workspaceId)
    {
        $clients = [];
        $demoClients = [
            [
                'name' => 'Acme Corporation',
                'phone' => '555-200',
                'email' => 'michael@acmecorp.com',
                'address' => '123 Main St, Cityville',
                'abn_number' => '12345678901',
                'logo_img' => 'assets/img/default.png',
                'contact_persons' => [
                    [
                        'name' => 'Michael Scott',
                        'email' => 'michael@acmecorp.com',
                        'phone' => '555-100',
                        'role' => 'Manager'
                    ]
                ]
            ],
            [
                'name' => 'GlobalTech Solutions',
                'phone' => '555-201',
                'email' => 'david@globaltech.com',
                'address' => '456 Tech Ave, Metropolis',
                'abn_number' => '23456789012',
                'logo_img' => 'assets/img/default.png',
                'contact_persons' => [
                    [
                        'name' => 'David R Jones',
                        'email' => 'david@globaltech.com',
                        'phone' => '555-101',
                        'role' => 'Director'
                    ]
                ]
            ],
            [
                'name' => 'Pinnacle Industries',
                'phone' => '555-202',
                'email' => 'sarah@pinnacle.com',
                'address' => '789 Industry Rd, Capital City',
                'abn_number' => '34567890123',
                'logo_img' => 'assets/img/default.png',
                'contact_persons' => [
                    [
                        'name' => 'Sarah J Miller',
                        'email' => 'sarah@pinnacle.com',
                        'phone' => '555-102',
                        'role' => 'Supervisor'
                    ]
                ]
            ],
            [
                'name' => 'Horizon Services',
                'phone' => '555-203',
                'email' => 'thomas@horizon.com',
                'address' => '1010 Horizon Blvd, Springfield',
                'abn_number' => '45678901234',
                'logo_img' => 'assets/img/default.png',
                'contact_persons' => [
                    [
                        'name' => 'Thomas White',
                        'email' => 'thomas@horizon.com',
                        'phone' => '555-103',
                        'role' => 'Lead'
                    ]
                ]
            ],
            [
                'name' => 'Elite Enterprises',
                'phone' => '555-204',
                'email' => 'jennifer@elite.com',
                'address' => '2020 Elite St, Shelbyville',
                'abn_number' => '56789012345',
                'logo_img' => 'assets/img/default.png',
                'contact_persons' => [
                    [
                        'name' => 'Jennifer L Lee',
                        'email' => 'jennifer@elite.com',
                        'phone' => '555-104',
                        'role' => 'Owner'
                    ]
                ]
            ]
        ];
        
        foreach ($demoClients as $demoClient) {
            $clientData = [
                'name' => $demoClient['name'],
                'phone' => $demoClient['phone'],
                'email' => $demoClient['email'],
                'address' => $demoClient['address'],
                'abn_number' => $demoClient['abn_number'],
                'logo_img' => $demoClient['logo_img'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_by' => $customerId
            ];

            $client = Company::create($clientData);

            // Save contact persons if provided
            if (isset($demoClient['contact_persons']) && is_array($demoClient['contact_persons'])) {
                foreach ($demoClient['contact_persons'] as $contactPerson) {
                    CompanyContactPerson::create([
                        'company_id' => $client->id,
                        'name' => $contactPerson['name'],
                        'email' => $contactPerson['email'],
                        'phone' => $contactPerson['phone'],
                        'role' => $contactPerson['role'] ?? null,
                    ]);
                }
            }
            
            $clients[] = $client;
        }
        
        return $clients;
    }

    private function createDemoProjects($customerId, $workspaceId, $clients, $sites)
    {
        $projects = [];
        $projectNames = [
            'Website Redesign',
            'Mobile App Development',
            'ERP Implementation',
            'Marketing Campaign',
            'Infrastructure Upgrade'
        ];
        
        $projectTypes = [
            'Web Development',
            'Mobile Development',
            'Software Implementation',
            'Marketing',
            'IT Infrastructure'
        ];
        
        foreach ($projectNames as $index => $projectName) {
            $client = $clients[$index];
            // Demo values for geo and revenue
            $longitudes = ['-74.0060', '-122.4194', '-87.6298', '-84.3880', '-71.0589'];
            $latitudes = ['40.7128', '37.7749', '41.8781', '33.7490', '42.3601'];
            $areaRadii = ['0.1', '0.2', '0.2', '0.3', '0.3'];
            $revenues = [10000, 20000, 15000, 25000, 18000];
            $project = Project::create([
                'title' => $projectName,
                'client_id' => $client->id,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'state' => 'State' . chr(rand(65, 90)),
                'address' => 'Project site for ' . strtolower($projectName) . ', client: ' . trim($client->fname . ' ' . ($client->mname ? $client->mname . ' ' : '') . $client->lname),
                'description' => 'A project to ' . strtolower($projectName) . ' for ' . ($client->name ?? trim($client->fname . ' ' . $client->lname)),
                'status' => ['active', 'pending', 'planning', 'active', 'pending'][$index],
                'type' => $projectTypes[$index],
                'thumbnail' => 'assets/img/default.png',
                'start_date' => now()->subDays(rand(5, 30))->format('Y-m-d'),
                'end_date'   => now()->addDays(rand(30, 90))->format('Y-m-d'),
                'budget' => rand(5000, 50000),
                'priority' => ['high', 'medium', 'low', 'high', 'medium'][$index],
                'longitude' => $longitudes[$index],
                'latitude' => $latitudes[$index],
                'area_radius' => $areaRadii[$index],
                'revenue' => $revenues[$index], // Will be ignored if not in DB
                'created_by' => $customerId,
            ]);

            // Add revenue to project meta
            DB::table('projects_meta')->insert([
                'project_id' => $project->id,
                'option' => 'revenue',
                'value' => $revenues[$index],
            ]);

            $projects[] = $project;

            // Assign a site to this project (e.g., one-to-one mapping)
            $site = $sites[$index] ?? null;
            if ($site) {
                ProjectSite::create([
                    'project_id' => $project->id,
                    'site_id' => $site->id,
                    'user_id' => $customerId, // or whoever is the creator
                ]);
            }
        }
        
        return $projects;
    }
    private function createDemoRosters($customerId, $workspaceId, $employees)
    {
        // Create a single 9-to-5 roster template
        $rosterTemplate = RosterTemplate::create([
            'start_time' => '09:00:00',
            'end_time' => '17:00:00',
            'color_code' => '#4CAF50', // Green color
            'break_minutes' => 60, // 1 hour lunch break
            'shift_notes' => 'Standard 9-to-5 work schedule',
            'repeat_shift' => 0,
            'repeat_every' => null,
            'end_date' => now()->addWeek()->toDateString(),
            'is_saved' => 1,
            'status' => 1,
            'working_hours' => 7, // 8 working hours (9-5 with 1hr break)
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'created_by' => $customerId,
        ]);

        // Filter out employees that have a link_key (linked employees)
        $nonLinkedEmployees = array_filter($employees['employees'], function($employee) {
            return empty($employee->link_key);
        });

        // Create date range for next 7 weekdays (excluding weekends)
        $startDate = now()->startOfDay();
        $daysToSchedule = 7;
        $scheduledDays = 0;
        $currentDate = clone $startDate;

        // Loop until we've scheduled 7 weekdays
        while ($scheduledDays < $daysToSchedule) {
            // Skip weekends (Saturday = 6, Sunday = 7)
            if (!$currentDate->isWeekend()) {
                // Only assign rosters to non-linked employees
                foreach ($nonLinkedEmployees as $employee) {
                    // Check if roster assignment already exists for this employee on this date
                    $existingAssignment = RosterAssign::where('assign_to', $employee->id)
                        ->where('schedule_date', $currentDate->toDateString())
                        ->where('customer_id', $customerId)
                        ->where('workspace_id', $workspaceId)
                        ->first();
                    
                    // Only create if assignment doesn't exist
                    if (!$existingAssignment) {
                        RosterAssign::create([
                            'assign_to' => $employee->id,
                            'roster_template_id' => $rosterTemplate->id,
                            'schedule_date' => $currentDate->toDateString(),
                            'customer_id' => $customerId,
                            'workspace_id' => $workspaceId,
                            'created_at' => now(),
                            'updated_at' => now(),
                        ]);
                    }
                }
                $scheduledDays++;
            }
            $currentDate->addDay();
        }
        
        return true;
    }
    
    private function storeDemoRosterSettings($customerId, $workspaceId)
    {
        // Define the 9-to-5 roster settings
        $meta = [
            'title' => 'Standard 9-to-5',
            'paid_break' => 60,
            'color_code' => '#4CAF50',
            'start_time' => '09:00:00',
            'end_time' => '17:00:00',
            'description' => 'Standard 9-to-5 work schedule',
            'working_days' => 'Monday,Tuesday,Wednesday,Thursday,Friday',
            'working_hours' => 8,
            'number_of_days' => 5,
        ];

        // Delete any existing roster settings for this customer/workspace
        DB::table('settings')
            ->where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->whereIn('option', [
                'roster_setting_title',
                'roster_setting_paid_break',
                'roster_setting_color_code',
                'roster_setting_start_time',
                'roster_setting_end_time',
                'roster_setting_description',
                'roster_setting_working_hours',
                'roster_setting_working_days',
                'roster_setting_number_of_days',
            ])
            ->delete();

        // Prepare the settings for insertion
        $settingsMeta = [];
        foreach ($meta as $option => $value) {
            $settingsMeta[] = [
                'option' => "roster_setting_" . $option,
                'value' => $value,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
            ];
        }

        // Insert the new settings
        DB::table('settings')->insert($settingsMeta);

        // (Optional) return the settings for confirmation
        return $settingsMeta;
    }

    private function storeDemoWhsReportSettings($customerId, $workspaceId, $createdBy = 1)
    {
        // Example demo WHS items
        $demoItems = [
            ['title' => 'Prestart conducted / communicated (ensure relevant section(s) in SWMS has been communicated)', 'status' => 1],
            ['title' => 'Toolbox conducted / communicated (ensure relevant areas of HRCW)', 'status' => 1],
            ['title' => 'Workplace Health and Safety Policy displayed', 'status' => 1],
            ['title' => 'Mandatory PPE worn by ALL Workers', 'status' => 1],
            ['title' => 'Task Specific PPE worn by ALL Workers', 'status' => 1],
            ['title' => 'First Aid Box stocked', 'status' => 1],
            ['title' => 'Site Shed clean and tidy', 'status' => 1],
            ['title' => 'Lunchroom clean and tidy', 'status' => 1],
            ['title' => 'General work areas clean and tidy', 'status' => 1],
            ['title' => 'General work area(s) have adequate lighting', 'status' => 1],
            ['title' => 'Task specific lighting adequate', 'status' => 1],
            ['title' => 'Proper use of ladders', 'status' => 1],
            ['title' => 'Tools - clean and in good condition', 'status' => 1],
            ['title' => 'Tools - Correct type for work being carried out', 'status' => 1],
            ['title' => 'Tools - Machinery guards fitted', 'status' => 1],
            ['title' => 'Tools - Electrical tools inspected', 'status' => 1],
            ['title' => 'Tools - Lead stands / Hooks used', 'status' => 1],
            ['title' => 'Tools - Leads and Tools tested / tagged', 'status' => 1],
            ['title' => 'Tools - Adequate earth leakage supplied', 'status' => 1],
            ['title' => 'Materials - Container clean and tidy', 'status' => 1],
            ['title' => 'Materials - Neatly and correctly stacked', 'status' => 1],
            ['title' => 'Materials - Materials Handling', 'status' => 1],
            ['title' => 'Materials - Correct Manual Handling techniques', 'status' => 1],
            ['title' => 'Materials - Access in and around and to materials maintained', 'status' => 1],
            ['title' => 'Materials - Close to area of usage', 'status' => 1],
            ['title' => 'Materials - Stored safely', 'status' => 1],
            ['title' => 'SDS - on site for all substances / chemicals being used', 'status' => 1],
            ['title' => 'Mobile Powered Plant - Documentation in Folder and Registered', 'status' => 1],
            ['title' => 'Mobile Powered Plant - Operator ticketed / competent', 'status' => 1],
        ];


        foreach ($demoItems as $item) {
            // You may need to adjust the model name if it's not WhsItem
            DB::table('whs_items')->insert([
                'title' => $item['title'],
                'status' => $item['status'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_by' => $createdBy,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    private function storeDemoInspectionPlanSettings($customerId, $workspaceId)
    {
        // Example demo steps and table titles
        $demoSteps = [
            [
                'step_name' => 'Column',
                'step_order' => 2,
                'table_title' => ['Height Set k', 'Column Size k', 'Clean of Loose Debris', 'Fillets ked', 'Z bars ked', 'Bracing & Location', 'Date column closed']
            ],
            [
                'step_name' => 'Wall',
                'step_order' => 4,
                'table_title' => ['Wall No', 'Height Set k', 'Wall Size k', 'Peno\'s k', 'Fillets ked', 'Toby Bars Caste-ins k', 'Bracing & Location', 'Date Wall closed']
            ],
            [
                'step_name' => 'Stair',
                'step_order' => 5,
                'table_title' => ['Stair No', 'Landing RL Set k', 'Stair Width & Throat k', 'Goings & Risers Setout k', 'Soffits clean of sawdust & rubbish', 'Date poured']
            ],
            [
                'step_name' => 'Deck-Pre-Pour',
                'step_order' => 6,
                'table_title' => ['Work Items/activities to be verified', 'Reference', 'Initialed / OK / NA', 'Comments']
            ],
            [
                'step_name' => 'Stripping-klist-and-Order',
                'step_order' => 7,
                'table_title' => ['Work Items/activities to be verified', 'FFGA Initialed or NA', 'Builders / Initialed or NA', 'Comments']
            ],
            [
                'step_name' => 'Concrete-Machine',
                'step_order' => 9,
                'table_title' => ['Number', 'Initial Risk', 'Final Risk', 'Control Risk']
            ],
        ];
        

        foreach ($demoSteps as $step) {
            $updated_name = str_replace(' ', '_', $step['step_name']);
            if (!empty($step['table_title'])) {
                foreach ($step['table_title'] as $title) {
                    // Insert into inspection_plan_tables
                    DB::table('inspection_plan_tables')->insert([
                        'title' => $updated_name,
                        'step_order' => $step['step_order'],
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                        'value' => $title,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                    // Insert into inspection_plan_meta
                    DB::table('inspection_plan_metas')->insert([
                        'name' => $updated_name,
                        'title' => $title,
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                        'is_table' => 1,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            } else {
                // Insert step without table titles
                DB::table('inspection_plan_tables')->insert([
                    'title' => $updated_name,
                    'step_order' => $step['step_order'],
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
                DB::table('inspection_plan_metas')->insert([
                    'name' => $updated_name,
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                    'is_table' => 1,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);
            }
        }
    }

    private function storeDemoSwmsSettings($customerId, $workspaceId, $createdBy = 1)
    {
        // 1. SWMS Hazard/Risk
        $hazardRisks = [
            ['title' => 'Electrical equipment', 'description' => 'Risk of electrical hazards', 'type' => 'hazard', 'status' => '1'],
            ['title' => 'Elevated levels', 'description' => 'Risk of working at heights or elevated levels', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Slips, trips and falls', 'description' => 'Risk of slips, trips and falls on site', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Hazardous substances', 'description' => 'Risk of exposure to hazardous substances', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'HRCW - Confined spaces', 'description' => 'Risk of working in confined spaces', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'HRCW - Mobile plant movement', 'description' => 'Risk from mobile plant and vehicle movement', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'HRCW - Demolition of a load-bearing structure', 'description' => 'Risk from demolition of load-bearing structures', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'HRCW - Asbestos disturbance', 'description' => 'Risk from asbestos disturbance', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'HRCW - Diving work', 'description' => 'Risk from diving work', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Hot Work', 'description' => 'Risk from performing hot work (e.g. welding, cutting)', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Hazardous manual tasks', 'description' => 'Risk of musculoskeletal injuries from manual handling', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Outdoor work', 'description' => 'Risk from exposure to outdoor environmental conditions', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Remotely &/or isolated work', 'description' => 'Risk of working in remote or isolated locations', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Noise and vibration', 'description' => 'Risk of hearing damage and vibration-related injuries', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Native vegetation & weeds', 'description' => 'Risk from exposure to hazardous plants and weeds', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Air quality', 'description' => 'Risk from poor air quality and airborne contaminants', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Waste', 'description' => 'Risk from waste materials on site', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Vehicle movement', 'description' => 'Risk of accidents from vehicle movement', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Fuels, oils & chemicals', 'description' => 'Risk from exposure to fuels, oils, and chemicals', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Terrestrial fauna', 'description' => 'Risk from encounters with wildlife', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Waterways & soils', 'description' => 'Risk from contamination of waterways and soils', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Cultural heritage', 'description' => 'Risk to cultural heritage sites and materials', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'HRCW - Artificial extremes of temperature', 'description' => 'Risk from extreme temperature conditions', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'HRCW - Tilt-up or pre-cast concrete', 'description' => 'Risk from tilt-up or pre-cast concrete work', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Pressurised gas distribution mains or piping chemical, fuel or refrigerant lines energised electrical installations or services', 'description' => 'Risk from pressurised gas or electrical systems', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Structures or buildings involving structural alterations or repairs that require temporary support to prevent collapse', 'description' => 'Risk from structural alterations requiring temporary support', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Involves a risk of a person falling from 2m or more, including work on telecommunications towers', 'description' => 'Risk of falls from heights greater than 2 meters', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Working at depths greater than 1.5 Metres, including tunnels or mines', 'description' => 'Risk from working at depths greater than 1.5 meters', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Work in an area that may have a contaminated or flammable atmosphere', 'description' => 'Risk from working in contaminated or flammable atmospheres', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Work carried out adjacent to a road, railway or shipping lane, traffic corridor', 'description' => 'Risk from working near traffic corridors', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'In or near water or other liquid that involves the risk of drowning', 'description' => 'Risk of drowning from working near water', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'HRCW - Using of explosives', 'description' => 'Risk from using explosives on site', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Involves a risk of a person or object falling more than 2 metres', 'description' => 'Risk of falling from heights greater than 2 meters', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out in an area at a workplace in which there is any movement of powered mobile plant', 'description' => 'Risk from powered mobile plant movement', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out on a telecommunication tower', 'description' => 'Risk of working on telecommunication towers', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out on or near pressurised gas distribution mains or piping', 'description' => 'Risk of working near pressurised gas systems', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out in an area in which there are artificial extremes of temperature', 'description' => 'Risk from extreme temperature conditions', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Involves demolition of an element of a structure that is load bearing or otherwise related to the physical integrity of the structure', 'description' => 'Risk from structural demolition', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out on or near chemical, fuel or refrigerant lines', 'description' => 'Risk from working near hazardous lines', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out in or near water or other liquid that involves a risk of drowning', 'description' => 'Risk from working near water or liquids', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Involves, or is likely to involve, the disturbance of asbestos', 'description' => 'Risk from asbestos disturbance', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out on or near energised electrical installations or services', 'description' => 'Risk from working near energised electrical systems', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Involves diving work', 'description' => 'Risk from diving work', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Involves structural alterations or repairs that require temporary support to prevent collapse', 'description' => 'Risk from structural alterations', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out in an area that may have a contaminated or flammable atmosphere', 'description' => 'Risk from contaminated or flammable atmosphere', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Other (Please Specify)', 'description' => 'Other hazards not listed', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out in or near a confined space', 'description' => 'Risk from confined space work', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Involves tilt-up or precast concrete', 'description' => 'Risk from tilt-up or precast concrete work', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out in or near: a shaft or trench with an excavated depth greater than 1.5 metres, or a tunnel', 'description' => 'Risk from working in deep shafts, trenches, or tunnels', 'type' => 'hazard', 'status' => '0'],
            ['title' => 'Is carried out on, in or adjacent to a road, railway, shipping lane or other traffic corridor that is in use by traffic other than pedestrians', 'description' => 'Risk from working near traffic corridors', 'type' => 'hazard', 'status' => '0'],
        ];

        foreach ($hazardRisks as $item) {
            DB::table('hazard_risks')->insert([
                'title' => $item['title'],
                'description' => $item['description'],
                'type' => $item['type'],
                'status' => '1', // Always string '1'
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // 2. SWMS Safety Planning Questions
        $safetyQuestions = [
            ['question' => 'Key Legislation/codes/standards that must be complied with', 'description' => 'Key Legislation', 'type' => 'hazard'],
            ['question' => 'Hold Points', 'description' => 'Hold Points', 'type' => 'hazard'],
            ['question' => "Principal Contractor's requirements/standards that must be complied with?", 'description' => "Principal Contractor's requirements/standards that must be complied with?", 'type' => 'hazard'],
            ['question' => 'Competency and Training required to complete the work?', 'description' => 'Competency and Training required to complete the work?', 'type' => 'hazard'],
            ['question' => 'Worker duties and responsibilities', 'description' => 'Worker duties and responsibilities', 'type' => 'hazard'],
            ['question' => 'Monitor/Review', 'description' => 'Monitor/Review', 'type' => 'hazard'],
            ['question' => '"Permit to Work" required for this work?', 'description' => '"Permit to Work" required for this work?', 'type' => 'hazard'],
            ['question' => 'Plant & Equipment to be used?', 'description' => 'Plant & Equipment to be used?', 'type' => 'hazard'],
            ['question' => 'Details of inspections / Maintenance?', 'description' => 'Details of inspections / Maintenance?', 'type' => 'hazard'],
            ['question' => 'klist to be submitted?', 'description' => 'klist to be submitted?', 'type' => 'hazard'],
            ['question' => 'Planning / Preparation', 'description' => 'Planning / Preparation', 'type' => 'hazard'],
        ];
        foreach ($safetyQuestions as $item) {
            DB::table('swms_safety_planning_questions')->insert([
                'question' => $item['question'],
                'description' => $item['description'],
                'type' => $item['type'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // 3. SWMS General Notes
        $generalNotes = [
            ['title' => 'Notes', 'description' => 'Test NOTE: Work must be performed in accordance with this SWMS. Circumstances at the workplace that may affect the way in which the High Risk Construction Work is carried out will be addressed with the Principal Contractor (e.g. Toolbox Talk, Prestart, Other agreed arrangements). This SWMS must be kept and be available for inspection until the high-risk construction work to which this SWMS relates is completed. If the SWMS is revised, all versions should be kept. If a notifiable incident occurs in relation to the high-risk construction work in this SWMS, the SWMS must be kept for at least 2 years from the date of the notifiable incident. This SWMS is to be read in conjunction with other parts of the Safe System of work for the company (Safe Work Procedures, Job Safety Analysis, etc.).', 'type' => 'risk'],
            ['title' => 'SWMS Notes', 'description' => 'Test NOTE: Work must be performed in accordance with this SWMS. Circumstances at the workplace that may affect the way in which the High Risk Construction Work is carried out will be addressed with the Principal Contractor (e.g. Toolbox Talk, Prestart, Other agreed arrangements). This SWMS must be kept and be available for inspection until the high-risk construction work to which this SWMS relates is completed. If the SWMS is revised, all versions should be kept. If a notifiable incident occurs in relation to the high-risk construction work in this SWMS, the SWMS must be kept for at least 2 years from the date of the notifiable incident. This SWMS is to be read in conjunction with other parts of the Safe System of work for the company (Safe Work Procedures, Job Safety Analysis, etc.).', 'type' => 'risk'],
            ['title' => 'General Notes List', 'description' => 'General Notes List : NOTE: Work must be performed in accordance with this SWMS. Circumstances at the workplace that may affect the way in which the High Risk Construction Work is carried out will be addressed with the Principal Contractor (e.g. Toolbox Talk, Prestart, Other agreed arrangements). This SWMS must be kept and be available for inspection until the high-risk construction work to which this SWMS relates is completed. If the SWMS is revised, all versions should be kept. If a notifiable incident occurs in relation to the high-risk construction work in this SWMS, the SWMS must be kept for at least 2 years from the date of the notifiable incident. This SWMS is to be read in conjunction with other parts of the Safe System of work for the company (Safe Work Procedures, Job Safety Analysis, etc.).', 'type' => 'hazard'],
        ];
        foreach ($generalNotes as $item) {
            DB::table('swms_general_notes')->insert([
                'title' => $item['title'],
                'description' => $item['description'],
                'type' => $item['type'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // 4. SWMS Protection Tools (no image for demo)
        $protectionTools = [
            ['title' => 'Foot Protection', 'description' => 'Foot Protection'],
            ['title' => 'Eye Protection', 'description' => 'Eye Protection'],
            ['title' => 'Face Protection', 'description' => 'Face Protection'],
            ['title' => 'Disposable Hand Protection', 'description' => 'Disposable Hand Protection'],
            ['title' => 'Protective Clothing', 'description' => 'Protective Clothing'],
            ['title' => 'Half-face respirators (P1 / P2 / disposable / cartridge)', 'description' => 'Half-face respirators (P1 / P2 / disposable / cartridge)'],
            ['title' => 'Hearing Protection', 'description' => 'Hearing Protection'],
            ['title' => 'Safety Harness', 'description' => 'Safety Harness'],
            ['title' => 'Sun Protection', 'description' => 'Sun Protection'],
            ['title' => 'High Visibility', 'description' => 'High Visibility'],
        ];
        foreach ($protectionTools as $item) {
            DB::table('swms_protection_tools')->insert([
                'title' => $item['title'],
                'description' => $item['description'],
                'image' => 'assets/img/default.png', // No image for demo
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    private function storeDemoIncidentSettings($customerId, $workspaceId, $createdBy = 1)
    {
        // 1. Incident Injury Classifications
        $injuryClassifications = [
            ['title' => 'First Aid – No Investigation', 'description' => 'First aid', 'status' => 1],
            ['title' => 'First Aid - Investigation', 'description' => 'First aid', 'status' => 1],
            ['title' => 'Near Miss', 'description' => 'Description', 'status' => 1],
            ['title' => 'Medical Treatment', 'description' => 'Medical Treatment', 'status' => 1],
            ['title' => 'Medical treatment', 'description' => 'Medical treatment', 'status' => 1],
            ['title' => 'Lost Time', 'description' => 'Lost Time', 'status' => 1],
            ['title' => 'Other (Specify Below)', 'description' => 'Other', 'status' => 1],
        ];
        

        foreach ($injuryClassifications as $item) {
            DB::table('incident_injury_classifications')->insert([
                'title' => $item['title'],
                'description' => $item['description'],
                'status' => $item['status'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // 2. Incident Notifiable Classifications
        $notifiableClassifications = [
            ['title' => 'Serious Injury Illness of a person', 'description' => '(Refer to section 36 of the WHS Act for a definition of Serious Injury Illness of a person)', 'status' => 1],
            ['title' => 'Dangerous Incident', 'description' => '(Refer to section 37 of the WHS Act for a definition of Dangerous Incident)', 'status' => 1],
            ['title' => 'Death', 'description' => 'Death', 'status' => 1],
        ];
        

        foreach ($notifiableClassifications as $item) {
            DB::table('incident_notifiable_classifications')->insert([
                'title' => $item['title'],
                'description' => $item['description'],
                'status' => $item['status'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // 3. Incident Risk Categories
        $riskCategories = [
            ['title' => 'Involves a risk of a person falling more than 2 metres', 'description' => 'Involves a risk of a person falling more than 2 metres', 'status' => 1],
            ['title' => 'Is carried out on or near chemical, fuel or refrigerant lines', 'description' => 'Is carried out on or near chemical, fuel or refrigerant lines', 'status' => 1],
            ['title' => 'Is carried out on a telecommunication tower', 'description' => 'Is carried out on a telecommunication tower', 'status' => 1],
            ['title' => 'Is carried out on or near energised electrical installations or services', 'description' => 'Is carried out on or near energised electrical installations or services', 'status' => 1],
            ['title' => 'Involves demolition of an element of a structure that is load-bearing or otherwise related to the physical integrity of the structure', 'description' => 'Involves demolition of an element of a structure that is load-bearing or otherwise related to the physical integrity of the structure', 'status' => 1],
            ['title' => 'Is carried out in an area that may have a contaminated or flammable atmosphere', 'description' => 'Is carried out in an area that may have a contaminated or flammable atmosphere', 'status' => 1],
            ['title' => 'Involves, or is likely to involve, the disturbance of asbestos', 'description' => 'Involves, or is likely to involve, the disturbance of asbestos', 'status' => 1],
            ['title' => 'Involves tilt-up or precast concrete', 'description' => 'Involves tilt-up or precast concrete', 'status' => 1],
            ['title' => 'Involves structural alterations or repairs that require temporary support to prevent collapse', 'description' => 'Involves structural alterations or repairs that require temporary support to prevent collapse', 'status' => 1],
            ['title' => 'Is carried out on, in or adjacent to a road, railway, shipping lane or other traffic corridor that is in use by traffic other than pedestrians', 'description' => 'Is carried out on, in or adjacent to a road, railway, shipping lane or other traffic corridor that is in use by traffic other than pedestrians', 'status' => 1],
            ['title' => 'Is carried out in or near a confined space', 'description' => 'Is carried out in or near a confined space', 'status' => 1],
            ['title' => 'Is carried out in an area at a workplace in which there is any movement of powered mobile plant', 'description' => 'Is carried out in an area at a workplace in which there is any movement of powered mobile plant', 'status' => 1],
            ['title' => 'Is carried out in or near a shaft or trench with an excavated depth greater than 1.5 metres, or a tunnel', 'description' => 'Is carried out in or near a shaft or trench with an excavated depth greater than 1.5 metres, or a tunnel', 'status' => 1],
            ['title' => 'Is carried out in an area in which there are artificial extremes of temperature', 'description' => 'Is carried out in an area in which there are artificial extremes of temperature', 'status' => 1],
            ['title' => 'Involves the use of explosives', 'description' => 'Involves the use of explosives', 'status' => 1],
            ['title' => 'Is carried out in or near water or other liquid that involves a risk of drowning', 'description' => 'Is carried out in or near water or other liquid that involves a risk of drowning', 'status' => 1],
            ['title' => 'Is carried out on or near pressurised gas distribution mains or piping', 'description' => 'Is carried out on or near pressurised gas distribution mains or piping', 'status' => 1],
            ['title' => 'Involves diving work', 'description' => 'Involves diving work', 'status' => 1],
            ['title' => 'Other', 'description' => 'Other', 'status' => 1],
        ];
        

        foreach ($riskCategories as $item) {
            DB::table('incident_risk_categories')->insert([
                'title' => $item['title'],
                'description' => $item['description'],
                'status' => $item['status'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // 4. Incident Report Questions
        $reportQuestions = [
            ['question' => 'Work Location / Area?', 'description' => 'Work Location / Area', 'status' => 1],
            ['question' => 'What was being done at the time?', 'description' => 'What was being done at the time.', 'status' => 1],
            ['question' => 'What happened unexpectedly?', 'description' => 'What happened unexpectedly?', 'status' => 1],
            ['question' => 'How exactly was the injury sustained.', 'description' => 'How exactly was the injury sustained.', 'status' => 1],
            ['question' => 'Immediate action taken (to prevent further occurrence).', 'description' => 'Immediate action taken (to prevent further occurrence).', 'status' => 1],
            ['question' => 'Previous Incident Investigation Report Number', 'description' => 'Previous Incident Investigation Report Number', 'status' => 1],
            ['question' => 'Was there more than one person injured / Involved?', 'description' => 'Was there more than one person injured / Involved?', 'status' => 1],
            ['question' => 'Notifiable Incident Classification?', 'description' => 'Notifiable Incident Classification?', 'status' => 1],
        ];
        

        foreach ($reportQuestions as $item) {
            DB::table('incident_report_questions')->insert([
                'question' => $item['question'],
                'description' => $item['description'],
                'status' => $item['status'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // 5. Incident Injury Types (with hierarchy)
        $injuryTypeParents = [
            'Fractures (excluding of vertebral column)',
            'Fracture of vertebral column with or without mention of spinal cord lesion',
            'Dislocations',
            'Sprains and strains of joints and adjacent muscles (including acute trauma sprains and strains only)',
            'Intracranial injury, including concussion',
            'Internal injury of chest, abdomen and pelvis',
            'Traumatic amputation, including enucleation of eye (loss of eyeball)',
            'Open wound not involving traumatic amputation',
            'Superficial injury',
            'Contusion with intact skin surface and crushing injury, excluding those with fracture',
            'Foreign body on external eye, in ear or nose or in respiratory, digestive or reproductive systems (including choking)',
            'Burns',
            'Injuries to nerves and spinal cord without evidence of spinal bone injury',
            'Poisoning and toxic effects of substances',
            'Effects of weather, exposure, air pressure and other external causes (including bends, drowning, electrocution)',
            'Multiple injuries (only to be used where no principal injury can be identified)',
            'Damage to artificial aids',
            'Other and unspecified injuries',
            'Deafness',
            'Eye disorders (non-traumatic)',
            'Other diseases of the nervous system and sense organs',
            'Disorders of muscle, tendons and other soft tissues (includes synovitis, tenosynovitis, bursitis)',
            'Other diseases of the musculoskeletal system and connective tissue',
            'Dermatitis and other eczema',
            'Other diseases of the skin and subcutaneous tissue',
            'Hernia',
            'Other diseases of the digestive system',
            'Infectious and parasitic diseases',
            'Diseases of the respiratory system (including asthma, legionnaires disease, asbestosis, pneumoconiosis)',
            'Disease of the circulatory system (including heart disease, hypertension, hypotension, varicose veins)',
            'Cancers and other neoplasms',
            'Mental disorders',
            'Other diseases',
            'Eye',
            'Ear',
            'Face',
            'Head (other than eye, ear and face)',
            'Neck',
            'Back',
            'Trunk (other than back and excluding internal organs)',
            'Shoulders and arms',
            'Hands and fingers',
            'Hips and legs',
            'Feet and toes',
            'Internal organs (located in the trunk)',
            'Multiple locations (more than one of the above)',
            'General and unspecified locations',
            'Falls from a height',
            'Falls on the same level (including trips and slips)',
            'Hitting objects with a part of the body',
            'Exposure to mechanical vibration',
            'Being hit by moving objects',
            'Exposure to sharp, sudden sound',
            'Long term exposure to sounds',
            'Exposure to variations in pressure (other than sound)',
            'Repetitive movement with low muscle loading',
            'Other muscular stress',
            'Contact with electricity',
            'Contact or exposure to heat and cold',
            'Exposure to radiation',
            'Single contact with chemical or substance (excludes insect and spider bites and stings)',
            'Long term contact with chemical or substance',
            'Other contact with chemical or substance (includes insect and spider bites and stings)',
            'Contact with, or exposure to, biological factors',
            'Exposure to mental stress factors',
            'Slide or cave-in',
            'Vehicle accident',
            'Other and multiple mechanisms of injury',
            'Unspecified mechanisms of injury',
            'Machinery and fixed plant',
            'Mobile plant',
            'Road transport',
            'Other transport',
            'Powered equipment, tools and appliances',
            'Non-powered hand tools',
            'Non-powered equipment',
            'Chemicals',
            'Non-metallic substances',
            'Other materials, substances or objects',
            'Outdoor environment',
            'Indoor environment',
            'Underground environment',
            'Live animals',
            'Human agencies',
            'Biological agencies',
            'Non-physical agencies',
            'Other agencies',
            'Unspecified agencies',
        ];
        
        foreach ($injuryTypeParents as $parentTitle) {
            DB::table('incident_injury_types')->insert([
                'title' => $parentTitle,
                'description' => 'Injuries related to the ' . strtolower($parentTitle) . '.',
                'status' => 1,
                'parent_id' => 0, // Top-level category
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
        

        // 6. Training
        $trainings = [
            ['title' => 'First Aid Training', 'description' => 'Certified first aid and CPR training.', 'status' => 1],
            ['title' => 'Manual Handling Techniques', 'description' => 'Training on safe lifting and manual handling.', 'status' => 1],
            ['title' => 'Fire Warden Training', 'description' => 'Training for designated fire wardens.', 'status' => 1],
            ['title' => 'Working at Heights', 'description' => 'Certification for safely working at elevated levels.', 'status' => 1],
        ];

        foreach ($trainings as $item) {
            DB::table('trainings')->insert([
                'title' => $item['title'],
                'description' => $item['description'],
                'status' => $item['status'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'del' => '0',
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    private function storeDemoSafetyDataSheets($customerId, $workspaceId, $createdBy = 0)
    {
        $demoSheets = [
            [
                'title' => 'Acetone',
                'image' => 'assets/img/default.png',
                'revision_date' => now()->subYear()->format('Y-m-d'),
                'expiry_date' => now()->addYear()->format('Y-m-d'),
            ],
            [
                'title' => 'Hydrochloric Acid',
                'image' => 'assets/img/default.png',
                'revision_date' => now()->subMonths(6)->format('Y-m-d'),
                'expiry_date' => now()->addMonths(18)->format('Y-m-d'),
            ],
        ];

        foreach ($demoSheets as $sheet) {
            SafetyDataSheet::create([
                'title' => $sheet['title'],
                'image' => $sheet['image'],
                'date' => now()->format('Y-m-d'),
                'revision_date' => $sheet['revision_date'],
                'expiry_date' => $sheet['expiry_date'],
                'created_by' => $createdBy,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
            ]);
        }
    }

    private function storeDemoHelpdeskTickets($customerId, $workspaceId, $createdBy = 0)
    {
        // Get all available category IDs
        $categoryIds = HelpdeskTicketCategories::pluck('id')->toArray();

        // If there are no categories, you may want to create a default one or skip
        if (empty($categoryIds)) {
            return;
        }

        // Get some employees from the workspace to use their data
        $employees = EmpCompanyDetails::where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->with('empPersonalDetails')
            ->limit(5)
            ->get();

        // If no employees found, use default demo data
        if ($employees->isEmpty()) {
            $employees = collect([
                (object)['employee_email' => 'demo.employee1@company.com', 'empPersonalDetails' => (object)['first_name' => 'Demo', 'last_name' => 'Employee']],
                (object)['employee_email' => 'demo.employee2@company.com', 'empPersonalDetails' => (object)['first_name' => 'Test', 'last_name' => 'User']],
                (object)['employee_email' => 'demo.employee3@company.com', 'empPersonalDetails' => (object)['first_name' => 'Sample', 'last_name' => 'Worker']],
            ]);
        }

        // Dynamic ticket subjects and descriptions
        $ticketTemplates = [
            [
                'subject' => 'Demo Mobile app not syncing',
                'descriptions' => 'The mobile application is not syncing data with the web portal. Changes made on mobile are not reflected.',
                'status' => 1,
                'note' => 'Sync Issue',
            ],
            [
                'subject' => 'Demo Attendance log missing',
                'descriptions' => 'My attendance logs for last week are missing. Can you help me retrieve the data?',
                'status' => 2,
                'note' => 'Data Issue',
            ],
        ];

        // Generate 3-5 random demo tickets
        $numberOfTickets = rand(1, 3);
        
        for ($i = 0; $i < $numberOfTickets; $i++) {
            $employee = $employees->random();
            $template = $ticketTemplates[array_rand($ticketTemplates)];
            
            // Get employee name
            $firstName = $employee->empPersonalDetails->first_name ?? 'Demo';
            $lastName = $employee->empPersonalDetails->last_name ?? 'User';
            $fullName = $firstName . ' ' . $lastName;
            
            // Get employee email
            $email = $employee->employee_email ?? 'demo.user@company.com';
            
            // Assign a category in a round-robin fashion
            $categoryId = $categoryIds[$i % count($categoryIds)];
            
            HelpdeskTicket::create([
                'user_id' => $createdBy,
                'name' => $fullName,
                'ticket_id' => uniqid('TCKT'),
                'email' => $email,
                'category' => $categoryId,
                'subject' => $template['subject'],
                'descriptions' => $template['descriptions'],
                'status' => $template['status'],
                'attachments' => null,
                'note' => $template['note'],
                'workspace' => $workspaceId,
                'created_by' => $createdBy,
            ]);
        }
    }

    private function storeDemoAdminSettings($customerId, $workspaceId)
    {
        $demoSettings = [
            ['key' => 'brand_title_text', 'value' => 'Demo Company'],
            ['key' => 'brand_footer_text', 'value' => 'Demo Company'],
            ['key' => 'brand_logo_dark', 'value' => 'logo.png'],
            ['key' => 'brand_favicon', 'value' => 'favicon.png'],
            ['key' => 'system_date_format', 'value' => 'dd-mm-yyyy'],
            ['key' => 'system_time_format', 'value' => '23:30'],
            ['key' => 'system_menu_type', 'value' => 'topbar'],
            ['key' => 'sidebar_brand_logo', 'value' => 'sidebarlogo.png'],
        ];

        foreach ($demoSettings as $setting) {
            Adminsettings::updateOrCreate(
                [
                    'key' => $setting['key'],
                    'workspace' => $workspaceId,
                    'customer_id' => $customerId,
                ],
                [
                    'value' => $setting['value'],
                ]
            );
        }
    }

    protected function message1($message, $code = 400)
    {
        return response()->json([
            'status' => false,
            'message' => $message
        ], $code);
    }

    protected function handleValidationFailure($validator)
    {
        return response()->json([
            'status' => false,
            'message' => 'Validation errors',
            'errors' => $validator->errors()
        ], 422);
    }


    protected function createSlug1($title)
    {
        return Str::slug($title);
    }

    public function apiCreateDemoCustomerByEmail(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
        ]);

        $user = User::where('email', $request->email)->first();
        if (!$user) {
            return response()->json([
                'status' => false,
                'message' => 'User not found with this email.'
            ], 404);
        }
        return $this->createDemoCustomer($user);
    }

    private function storeDemoInvitedEmployee($customerId, $workspaceId)
    {
        // Generate a random name using your existing logic
        $names = $this->generateEmployeeNames();
        $nameArr = $names[array_rand($names)];

        // Get a random employment type, tier, work permit, and team
        $employmentType = EmpType::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->first();
        $tier = Tier::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->first();
        $workPermit = EmpPermit::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->first();
        $team = EmpTeam::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->first();

        // Fallbacks if not found
        $employmentTypeId = $employmentType ? $employmentType->id : 1;
        $tierId = $tier ? $tier->id : 1;
        $workPermitId = $workPermit ? $workPermit->id : 1;
        $teamId = $team ? $team->id : 1;

        $faker = Faker::create();
        $employeeEmail = $faker->unique()->email;

        $empData = [
            'employee_email' => $employeeEmail,
            'employment_type' => $employmentTypeId,
            'access_role' => 'EMP',
            'tier_id' => $tierId,
            'work_permit_type' => $workPermitId,
            'tax_file_no' => 'TFN' . rand(100000, 999999),
            'employment_start_date' => now()->subYears(rand(1, 10))->format('Y-m-d'),
            'employment_end_date' => now()->addYears(rand(1, 5))->format('Y-m-d'),
            'attendance_effective_from' => now()->subDays(rand(1, 30))->format('Y-m-d'),
            'invited' => 1,
            'credentials' => 0,
            'status' => 1,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'created_by' => $customerId,
            'approved' => '1',
        ];

        $empId = EmpCompanyDetails::insertGetId($empData);

        // Insert meta
        DB::table('user_meta')->insert([
            'emp_id' => $empId,
            'option' => 'employee_payroll_or_external_id',
            'value' => 'PAY' . rand(10000, 99999),
        ]);

        // Insert team membership
        EmpTeamsMember::create([
            'team_id' => $teamId,
            'emp_id' => $empId,
            'workspace_id' => $workspaceId,
            'customer_id' => $customerId,
            'created_by' => $customerId,
        ]);
    }


    private function markDemoAttendanceAccordingToRoster($customerId, $workspaceId, $date = null)
    {
        $date = now()->format('Y-m-d');

        // Get all employees for this customer/workspace
        $employees = EmpCompanyDetails::where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->get();

        $attendanceRecords = [];

        foreach ($employees as $employee) {
            // Find roster assignment for this employee on the given date
            $rosterAssign = RosterAssign::where('assign_to', $employee->id)
                ->where('customer_id', $customerId)
                ->where('workspace_id', $workspaceId)
                ->where('schedule_date', $date)
                ->with('rosterTemplate')
            ->first();
    
            if (!$rosterAssign || !$rosterAssign->rosterTemplate) {
                // No roster for this employee on this date, skip
                continue;
            }

            $kIn = $rosterAssign->rosterTemplate->start_time;
            $kOut = $rosterAssign->rosterTemplate->end_time;

            // Calculate working minutes
            $kInTime = Carbon::parse($kIn);
            $kOutTime = Carbon::parse($kOut);
            $totalWorkingMinutes = $kOutTime->diffInMinutes($kInTime);

            // Find a site for the employee (optional: you can use $rosterAssign->site_id if available)
            $site = Sites::where('customer_id', $customerId)
                ->where('workspace_id', $workspaceId)
                ->inRandomOrder()
                ->first();
    
            // k if attendance already exists for this date
            $existing = EmployeeAttendance::where('employee_id', $employee->id)
                ->where('date', $date)
                ->first();
            if ($existing) {
                $attendanceRecords[] = $existing;
                continue;
            }

            $attendance = EmployeeAttendance::create([
                'employee_id' => $employee->id,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'site_id' => $site ? $site->id : 1,
                'check_in' => $kIn,
                'check_out' => $kOut,
                'working_hours' => $totalWorkingMinutes,
                'date' => $date,
                'added_by' => 0,
            ]);
            EmployeeBreak::create([
                'emp_attendance_id' => $attendance->id,
                'break_in' => '13:00',
                'break_out' => '14:00',
                'date' => $date,
            ]);
            $attendanceRecords[] = $attendance;
        }
        
        return $attendanceRecords;
    }

    private function createDemoLeaveTypes($customerId, $workspaceId)
    {
        $leaveTypes = [
            ['title' => 'Annual Leave', 'description' => 'Paid annual leave', 'leave_hours' => 8],
            ['title' => 'Sick Leave', 'description' => 'Paid sick leave', 'leave_hours' => 8],
            ['title' => 'WFH Leave', 'description' => 'WFH leave', 'leave_hours' => 0],
        ];

        $created = [];
        foreach ($leaveTypes as $type) {
            $created[] = LeaveType::firstOrCreate(
                [
                    'title' => $type['title'],
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                ],
                [
                    'description' => $type['description'],
                    'leave_hours' => $type['leave_hours'],
                ]
            );
        }
        return $created;
    }

    private function createDemoLeavePackages($customerId, $workspaceId, $leaveTypes)
    {
        $roles = Role::where('del', 0)->pluck('id')->toArray();
        $packages = [
            [
                'title' => 'Standard Annual Package',
                'leave_type_id' => $leaveTypes[0]->id,
                'leave_number' => 20,
                'is_paid' => 1,
                'color_code' => '#4CAF50',
                'employee_roles' => $roles,
            ],
            [
                'title' => 'Standard Sick Package',
                'leave_type_id' => $leaveTypes[1]->id,
                'leave_number' => 10,
                'is_paid' => 1,
                'color_code' => '#2196F3',
                'employee_roles' => $roles,
            ],
            [
                'title' => 'WFH Leave Package',
                'leave_type_id' => $leaveTypes[2]->id,
                'leave_number' => 30,
                'is_paid' => 0,
                'color_code' => '#F44336',
                'employee_roles' => $roles,
            ],
        ];

        $created = [];
        foreach ($packages as $pkg) {
            $created[] = LeavePackage::firstOrCreate(
                [
                    'title' => $pkg['title'],
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                ],
                [
                    'leave_type_id' => $pkg['leave_type_id'],
                    'leave_number' => $pkg['leave_number'],
                    'is_paid' => $pkg['is_paid'],
                    'color_code' => $pkg['color_code'],
                    'employee_roles' => implode(',', $pkg['employee_roles']),
                ]
            );
        }
        return $created;
    }

    private function createDemoHolidays($customerId, $workspaceId)
    {
        $holidays = [
            [
                'title' => 'New Year\'s Day',
                'description' => 'First day of the year',
                'from' => now()->startOfYear()->format('Y-m-d'),
                'to' => now()->startOfYear()->format('Y-m-d'),
            ],
            [
                'title' => 'Demo Public Holiday',
                'description' => 'A demo public holiday',
                'from' => now()->addDays(10)->format('Y-m-d'),
                'to' => now()->addDays(10)->format('Y-m-d'),
            ],
        ];

        $created = [];
        foreach ($holidays as $holiday) {
            $created[] = PublicHoliday::firstOrCreate(
                [
                    'title' => $holiday['title'],
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                ],
                [
                    'description' => $holiday['description'],
                    'from' => $holiday['from'],
                    'to' => $holiday['to'],
                ]
            );
        }
        return $created;
    }

    private function applyDemoLeaveForEmployees($customerId, $workspaceId, $leavePackages)
    {
        $employees = EmpCompanyDetails::where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->get();

        // Find a suitable leave date that's not on weekend and is a roster assigned day
        $leaveDate = $this->findSuitableLeaveDate($customerId, $workspaceId);
        
        if (!$leaveDate) {
            // If no suitable date found, skip applying demo leaves
            return [];
        }

        $appliedLeaves = [];

        foreach ($employees as $employee) {
            // Check if employee has roster assigned for this date
            $hasRoster = RosterAssign::where('assign_to', $employee->id)
                ->where('schedule_date', $leaveDate)
                ->exists();

            if (!$hasRoster) {
                continue; // Skip if no roster assigned for this date
            }

            // Pick the first leave package for demo (or match by role if you want)
            $leavePackage = $leavePackages[0];

            $leave = LeaveRequest::firstOrCreate(
                [
                    'employee_id' => $employee->id,
                    'leave_package_id' => $leavePackage->id,
                    'from' => $leaveDate,
                    'to' => $leaveDate,
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                ],
                [
                    'reason' => 'Demo leave for testing',
                    'full_day' => 1,
                    'applied_by' => 1, // or the admin user id
                    'status' => 1, // approved for demo
                ]
            );
            $appliedLeaves[] = $leave;
        }
        return $appliedLeaves;
    }

    /**
     * Find a suitable leave date that's not on weekend and has roster assignments
     */
    private function findSuitableLeaveDate($customerId, $workspaceId)
    {
        // Start checking from 2 days from now
        $startDate = now()->addDays(2);
        
        // Check up to 30 days ahead to find a suitable date
        for ($i = 0; $i < 30; $i++) {
            $checkDate = $startDate->copy()->addDays($i);
            $dateString = $checkDate->format('Y-m-d');
            
            // Check if it's not weekend (Saturday = 6, Sunday = 0)
            if ($checkDate->dayOfWeek === 0 || $checkDate->dayOfWeek === 6) {
                continue; // Skip weekends
            }
            
            // Check if there are any roster assignments for this date
            $hasRosterAssignments = RosterAssign::where('customer_id', $customerId)
                ->where('workspace_id', $workspaceId)
                ->where('schedule_date', $dateString)
                ->exists();
            
            if ($hasRosterAssignments) {
                return $dateString;
            }
        }
        
        return null; // No suitable date found
    }

    public function createDemoLeaveData($customerId, $workspaceId)
    {
        $leaveTypes = $this->createDemoLeaveTypes($customerId, $workspaceId);
        $leavePackages = $this->createDemoLeavePackages($customerId, $workspaceId, $leaveTypes);
        $holidays = $this->createDemoHolidays($customerId, $workspaceId);
        $appliedLeaves = $this->applyDemoLeaveForEmployees($customerId, $workspaceId, $leavePackages);

        return response()->json([
            'leave_types' => $leaveTypes,
            'leave_packages' => $leavePackages,
            'holidays' => $holidays,
            'applied_leaves' => $appliedLeaves,
        ]);
    }

    /**
     * Create demo super fund records for the customer
     */
    private function createDemoSuperFunds($customerId, $workspaceId)
    {
        $funds = [
            [
                'title' => 'Australian Super',
                'percentage' => 11,
                'usi' => 1,
                'usi_number' => 'AUS0000AU',
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'del' => 0
            ],
            [
                'title' => 'REST Super',
                'percentage' => 11,
                'usi' => 1,
                'usi_number' => 'RES0001AU',
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'del' => 0
            ]
        ];

        $createdFunds = [];
        foreach ($funds as $fundData) {
            $fund = Fund::create($fundData);
            $createdFunds[] = $fund;
        }

        return $createdFunds;
    }

    private function createDemoWhsReports($customerId, $workspaceId)
    {
        // 1. Get a site and a project for the demo
        $site = Sites::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->first();
        $project = Project::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->first();
        $role = Role::where('del', '0')->first();
        $swms = Swms::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->first();
        $employee = EmpCompanyDetails::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->first();

        // 2. Step 1: Create the WHS Report
        $whsReport = WhsReport::create([
            'title' => 'Demo WHS Report',
            'number' => 'WHS-' . rand(1000, 9999),
            'authorised_by' => $employee ? $employee->id : null,
            'revision_number' => 'R1',
            'issue_date' => now()->format('Y-m-d'),
            'revision_date' => now()->addMonth()->format('Y-m-d'),
            'site_id' => $site ? $site->id : null,
            'created_by' => $customerId,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
        ]);

        // 3. Step 2: Add meta data
        $whsReport->update([
            'project_id' => $project ? $project->id : null,
            'date' => now()->format('Y-m-d'),
            'start_time' => '09:00:00',
            'end_time' => '17:00:00',
            'swms_id' => $swms ? $swms->id : null,
            'location' => 'Demo Location',
            'activities' => 'Demo activities for WHS report',
        ]);

        // Add demo WhsAdditionalPerson and WhsConductedBy (step 2)
        $employeeIds = EmpCompanyDetails::where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->inRandomOrder()
            ->limit(5)
            ->pluck('id')
            ->toArray();
        $additionalPersonIds = array_slice($employeeIds, 0, 2);
        $conductedByIds = array_slice($employeeIds, 2, 2);
        foreach ($additionalPersonIds as $empId) {
            WhsAdditionalPerson::create([
                'whs_report_id' => $whsReport->id,
                'employee_id' => $empId,
            ]);
        }
        foreach ($conductedByIds as $empId) {
            WhsConductedBy::create([
                'whs_report_id' => $whsReport->id,
                'employee_id' => $empId,
            ]);
        }

        // 4. Step 3: Add report items (questions/answers)
        $whsItems = WhsItem::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->get();
        foreach ($whsItems as $item) {
            WhsReportItem::updateOrCreate(
                [
                    'whs_report_id' => $whsReport->id,
                    'whs_items_id' => $item->id,
                ],
                [
                    'values' => (string) rand(0, 2), // Each record gets its own random value
                ]
            );
        }

        // 5. Step 4: Add hazards/actions
        WhsReportHazards::create([
            'whs_report_id' => $whsReport->id,
            'role_id' => $role ? $role->id : null,
            'level' => 'High',
            'hazard' => 'Demo hazard',
            'action_required' => 'Demo action required',
            'level_of_action' => 'medium-priority',
            'date_completed' => now()->format('Y-m-d'),
        ]);
        $whsReport->update(['general_notes' => 'Demo general notes', 'status' => 1]);

        // 6. Step 5: Add general notes (already done above, but you can update again if needed)
        $whsReport->update(['general_notes' => 'Final demo notes for WHS report']);

        return $whsReport;
    }

    /**
     * Create comprehensive WHSQ demo data with 5 parents and complete hierarchy
     */
    private function createDemoWhsqReports($customerId, $workspaceId)
    {
        // 1. Create WHSQ Table of Content Structure (5 Parents with Children and Grandchildren)
        $whsqStructure = $this->createDemoWhsqTableOfContent($customerId, $workspaceId);
        
        // 2. Create WHSQ Report
        $whsqReport = $this->createDemoWhsqReport($customerId, $workspaceId);
        
        // 3. Create Selected Settings for the Report
        $this->createDemoWhsqSelectedSettings($whsqReport->id, $whsqStructure, $customerId, $workspaceId);
        
        // 4. Create Content Meta Data for each selected setting
        $this->createDemoWhsqContentMeta($whsqReport->id, $whsqStructure, $customerId, $workspaceId);
        
        // 5. Create Signatures
        $this->createDemoWhsqSignatures($whsqReport->id, $customerId, $workspaceId);
        
        return $whsqReport;
    }

    /**
     * Create WHSQ Table of Content Structure with 5 parents based on WHSQ&E Management Plan
     */
    private function createDemoWhsqTableOfContent($customerId, $workspaceId)
    {
        $structure = [];
        
        // Parent 1: WHSQ&E Management Plan Overview
        $parent1 = WHSQE_TableOfContent::create([
            'title' => 'WHSQ&E Management Plan Overview',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $child1_1 = WHSQE_TableOfContentChild::create([
            'title' => 'Plan Preparation Basis',
            'whsqe_table_of_content_id' => $parent1->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $grandchild1_1_1 = WHSQE_TableOfContentGrandChild::create([
            'title' => 'Legislative Framework',
            'whsqe_table_of_content_id' => $parent1->id,
            'whsqe_table_of_content_child_id' => $child1_1->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $grandchild1_1_2 = WHSQE_TableOfContentGrandChild::create([
            'title' => 'Standards and Codes',
            'whsqe_table_of_content_id' => $parent1->id,
            'whsqe_table_of_content_child_id' => $child1_1->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $child1_2 = WHSQE_TableOfContentChild::create([
            'title' => 'Senior Management Approval',
            'whsqe_table_of_content_id' => $parent1->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $structure['parent1'] = [
            'parent' => $parent1,
            'children' => [
                'child1_1' => [
                    'child' => $child1_1,
                    'grandchildren' => [$grandchild1_1_1, $grandchild1_1_2]
                ],
                'child1_2' => [
                    'child' => $child1_2,
                    'grandchildren' => []
                ]
            ]
        ];
        
        // Parent 2: Hazard and Risk Management
        $parent2 = WHSQE_TableOfContent::create([
            'title' => 'Hazard and Risk Management',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $child2_1 = WHSQE_TableOfContentChild::create([
            'title' => 'Risk Assessment Process',
            'whsqe_table_of_content_id' => $parent2->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $grandchild2_1_1 = WHSQE_TableOfContentGrandChild::create([
            'title' => 'Hazard Identification',
            'whsqe_table_of_content_id' => $parent2->id,
            'whsqe_table_of_content_child_id' => $child2_1->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $grandchild2_1_2 = WHSQE_TableOfContentGrandChild::create([
            'title' => 'Hierarchy of Controls',
            'whsqe_table_of_content_id' => $parent2->id,
            'whsqe_table_of_content_child_id' => $child2_1->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $child2_2 = WHSQE_TableOfContentChild::create([
            'title' => 'Worker Consultation',
            'whsqe_table_of_content_id' => $parent2->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $structure['parent2'] = [
            'parent' => $parent2,
            'children' => [
                'child2_1' => [
                    'child' => $child2_1,
                    'grandchildren' => [$grandchild2_1_1, $grandchild2_1_2]
                ],
                'child2_2' => [
                    'child' => $child2_2,
                    'grandchildren' => []
                ]
            ]
        ];
        
        // Parent 3: WHS Information and Reporting
        $parent3 = WHSQE_TableOfContent::create([
            'title' => 'WHS Information and Reporting',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $child3_1 = WHSQE_TableOfContentChild::create([
            'title' => 'Daily Reporting',
            'whsqe_table_of_content_id' => $parent3->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $grandchild3_1_1 = WHSQE_TableOfContentGrandChild::create([
            'title' => 'Daily Report Completion',
            'whsqe_table_of_content_id' => $parent3->id,
            'whsqe_table_of_content_child_id' => $child3_1->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $child3_2 = WHSQE_TableOfContentChild::create([
            'title' => 'Weekly Reporting',
            'whsqe_table_of_content_id' => $parent3->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $grandchild3_2_1 = WHSQE_TableOfContentGrandChild::create([
            'title' => 'WHS Weekly Report',
            'whsqe_table_of_content_id' => $parent3->id,
            'whsqe_table_of_content_child_id' => $child3_2->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $structure['parent3'] = [
            'parent' => $parent3,
            'children' => [
                'child3_1' => [
                    'child' => $child3_1,
                    'grandchildren' => [$grandchild3_1_1]
                ],
                'child3_2' => [
                    'child' => $child3_2,
                    'grandchildren' => [$grandchild3_2_1]
                ]
            ]
        ];
        
        // Parent 4: Legal and Regulatory Compliance
        $parent4 = WHSQE_TableOfContent::create([
            'title' => 'Legal and Regulatory Compliance',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $child4_1 = WHSQE_TableOfContentChild::create([
            'title' => 'Legislation',
            'whsqe_table_of_content_id' => $parent4->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $grandchild4_1_1 = WHSQE_TableOfContentGrandChild::create([
            'title' => 'WHS Act 2011 and Regulations 2017',
            'whsqe_table_of_content_id' => $parent4->id,
            'whsqe_table_of_content_child_id' => $child4_1->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $child4_2 = WHSQE_TableOfContentChild::create([
            'title' => 'Codes of Practice',
            'whsqe_table_of_content_id' => $parent4->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $grandchild4_2_1 = WHSQE_TableOfContentGrandChild::create([
            'title' => 'Construction and Safety Codes',
            'whsqe_table_of_content_id' => $parent4->id,
            'whsqe_table_of_content_child_id' => $child4_2->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $structure['parent4'] = [
            'parent' => $parent4,
            'children' => [
                'child4_1' => [
                    'child' => $child4_1,
                    'grandchildren' => [$grandchild4_1_1]
                ],
                'child4_2' => [
                    'child' => $child4_2,
                    'grandchildren' => [$grandchild4_2_1]
                ]
            ]
        ];
        
        // Parent 5: WHSQ&E Objectives and Monitoring
        $parent5 = WHSQE_TableOfContent::create([
            'title' => 'WHSQ&E Objectives and Monitoring',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $child5_1 = WHSQE_TableOfContentChild::create([
            'title' => 'Site-Specific Objectives',
            'whsqe_table_of_content_id' => $parent5->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $grandchild5_1_1 = WHSQE_TableOfContentGrandChild::create([
            'title' => 'Prestart Meetings and Toolbox Talks',
            'whsqe_table_of_content_id' => $parent5->id,
            'whsqe_table_of_content_child_id' => $child5_1->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $child5_2 = WHSQE_TableOfContentChild::create([
            'title' => 'Review and Monitoring',
            'whsqe_table_of_content_id' => $parent5->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $grandchild5_2_1 = WHSQE_TableOfContentGrandChild::create([
            'title' => 'Management Plan Reviews',
            'whsqe_table_of_content_id' => $parent5->id,
            'whsqe_table_of_content_child_id' => $child5_2->id,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'del' => 0
        ]);
        
        $structure['parent5'] = [
            'parent' => $parent5,
            'children' => [
                'child5_1' => [
                    'child' => $child5_1,
                    'grandchildren' => [$grandchild5_1_1]
                ],
                'child5_2' => [
                    'child' => $child5_2,
                    'grandchildren' => [$grandchild5_2_1]
                ]
            ]
        ];
        
        return $structure;
    }

    /**
     * Create WHSQ Report
     */
    private function createDemoWhsqReport($customerId, $workspaceId)
    {
        $site = Sites::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->first();
        $employee = EmpCompanyDetails::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->first();
        
        $whsqReport = WhsqReport::create([
            'document_title' => 'Demo WHSQ Management System Report',
            'authorised_by' => $employee ? $employee->emp_id : null,
            'revision_number' => 'R1.0',
            'document_number' => 'WHSQ-' . rand(1000, 9999),
            'revision_date' => now()->format('Y-m-d'),
            'next_revision_date' => now()->addYear()->format('Y-m-d'),
            'site_id' => $site ? $site->id : null,
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'created_by' => $customerId,
            'publish' => false,
            'is_completed' => 0,
            'version' => '1.0'
        ]);
        
        return $whsqReport;
    }

    /**
     * Create Selected Settings for WHSQ Report
     */
    private function createDemoWhsqSelectedSettings($reportId, $structure, $customerId, $workspaceId)
    {
        $sortOrder = 1;
        
        // Select all parents and their children/grandchildren
        foreach ($structure as $parentKey => $parentData) {
            $parent = $parentData['parent'];
            
            // Create parent setting
            WHSQECustomerSelectedSettings::create([
                'whsq_report_id' => $reportId,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'parent_id' => $parent->id,
                'child_id' => null,
                'grandchild_id' => null,
                'is_selected' => true,
                'sort_order' => $sortOrder++,
                'level' => 'parent'
            ]);
            
            // Create child settings
            foreach ($parentData['children'] as $childKey => $childData) {
                $child = $childData['child'];
                
                WHSQECustomerSelectedSettings::create([
                    'whsq_report_id' => $reportId,
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                    'parent_id' => $parent->id,
                    'child_id' => $child->id,
                    'grandchild_id' => null,
                    'is_selected' => true,
                    'sort_order' => $sortOrder++,
                    'level' => 'child'
                ]);
                
                // Create grandchild settings
                foreach ($childData['grandchildren'] as $grandchild) {
                    WHSQECustomerSelectedSettings::create([
                        'whsq_report_id' => $reportId,
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                        'parent_id' => $parent->id,
                        'child_id' => $child->id,
                        'grandchild_id' => $grandchild->id,
                        'is_selected' => true,
                        'sort_order' => $sortOrder++,
                        'level' => 'grandchild'
                    ]);
                }
            }
        
        }
    }

    /**
     * Create Content Meta Data for WHSQ Report
     */
    private function createDemoWhsqContentMeta($reportId, $structure, $customerId, $workspaceId)
    {
        $stepId = 1;
        
        foreach ($structure as $parentKey => $parentData) {
            $parent = $parentData['parent'];
            
            // Create parent content
            $parentMeta = WHSQETableOfContentMeta::create([
                'whsq_report_id' => $reportId,
                'step_id' => $stepId,
                'parent_id' => $parent->id,
                'child_id' => null,
                'grandchild_id' => null,
                'content' => $this->getDemoContentForParent($parent->title),
                'sort_order' => 1,
                'start_new' => true,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'is_active' => true
            ]);
            
            // Add options for parent
            $this->createDemoContentOptions($parentMeta->id, $parent->title, $customerId, $workspaceId);
            
            // Create child content
            foreach ($parentData['children'] as $childKey => $childData) {
                $child = $childData['child'];
                
                $childMeta = WHSQETableOfContentMeta::create([
                    'whsq_report_id' => $reportId,
                    'step_id' => $stepId,
                    'parent_id' => $parent->id,
                    'child_id' => $child->id,
                    'grandchild_id' => null,
                    'content' => $this->getDemoContentForChild($child->title),
                    'sort_order' => 2,
                    'start_new' => false,
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                    'is_active' => true
                ]);
                
                // Add options for child
                $this->createDemoContentOptions($childMeta->id, $child->title, $customerId, $workspaceId);
                
                // Create grandchild content
                foreach ($childData['grandchildren'] as $grandchild) {
                    $grandchildMeta = WHSQETableOfContentMeta::create([
                        'whsq_report_id' => $reportId,
                        'step_id' => $stepId,
                        'parent_id' => $parent->id,
                        'child_id' => $child->id,
                        'grandchild_id' => $grandchild->id,
                        'content' => $this->getDemoContentForGrandchild($grandchild->title),
                        'sort_order' => 3,
                        'start_new' => false,
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                        'is_active' => true
                    ]);
                    
                    // Add options for grandchild
                    $this->createDemoContentOptions($grandchildMeta->id, $grandchild->title, $customerId, $workspaceId);
                    
                    // Add dates for grandchild
                    $this->createDemoContentDates($grandchildMeta->id, $grandchild->title, $customerId, $workspaceId);
                }
            }
            
            $stepId++;
        }
    }

    /**
     * Create demo content options
     */
    private function createDemoContentOptions($contentMetaId, $title, $customerId, $workspaceId)
    {
        $options = [
            [
                'option_id' => 1,
                'option_value' => 'checked',
                'option_type' => 'checkbox',
                'option_label' => 'Implemented',
                'main_heading' => 'Status',
                'group_order' => 1
            ],
            [
                'option_id' => 2,
                'option_value' => 'unchecked',
                'option_type' => 'checkbox',
                'option_label' => 'Under Review',
                'main_heading' => 'Status',
                'group_order' => 2
            ],
            [
                'option_id' => 3,
                'option_value' => 'unchecked',
                'option_type' => 'checkbox',
                'option_label' => 'Not Applicable',
                'main_heading' => 'Status',
                'group_order' => 3
            ]
        ];
        
        foreach ($options as $option) {
            WHSQEContentOption::create([
                'content_meta_id' => $contentMetaId,
                'option_id' => $option['option_id'],
                'option_value' => $option['option_value'],
                'option_type' => $option['option_type'],
                'option_label' => $option['option_label'],
                'main_heading' => $option['main_heading'],
                'group_order' => $option['group_order'],
                'level' => 'parent',
                'level_id' => null,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId
            ]);
        }
    }

    /**
     * Create demo content dates
     */
    private function createDemoContentDates($contentMetaId, $title, $customerId, $workspaceId)
    {
        $dates = [
            [
                'date_value' => now()->format('Y-m-d'),
                'date_label' => 'Implementation Date',
                'date_type' => 'implementation'
            ],
            [
                'date_value' => now()->addMonth()->format('Y-m-d'),
                'date_label' => 'Next Review Date',
                'date_type' => 'review'
            ]
        ];
        
        foreach ($dates as $date) {
            WHSQEContentDate::create([
                'content_meta_id' => $contentMetaId,
                'date_value' => $date['date_value'],
                'date_label' => $date['date_label'],
                'date_type' => $date['date_type'],
                'level' => 'grandchild',
                'level_id' => null,
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId
            ]);
        }
    }

    /**
     * Create demo signatures
     */
    private function createDemoWhsqSignatures($reportId, $customerId, $workspaceId)
    {
        $employees = EmpCompanyDetails::where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->inRandomOrder()
            ->limit(3)
            ->get();
        
        $signatureTypes = ['Site Manager', 'Safety Officer', 'Quality Manager'];
        
        foreach ($employees as $index => $employee) {
            if (isset($signatureTypes[$index])) {
                WhsqSignature::create([
                    'whsq_report_id' => $reportId,
                    'employee_id' => $employee->emp_id,
                    'is_site_employee' => true,
                    'signature' => null, // Would be base64 signature in real scenario
                    'job_description' => $signatureTypes[$index],
                    'induction_date' => now()->subDays(rand(1, 30))->format('Y-m-d'),
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId
                ]);
            }
        }
    }

    /**
     * Get demo content for parent sections
     */
    private function getDemoContentForParent($title)
    {
        $contentMap = [
            'Safety Management System' => '<h3>Safety Management System Overview</h3><p>This section outlines our comprehensive safety management system designed to ensure workplace health and safety compliance. The system includes policies, procedures, and risk assessment frameworks that guide our operations.</p><ul><li>Established safety policies and procedures</li><li>Comprehensive risk assessment framework</li><li>Regular safety audits and inspections</li><li>Continuous improvement processes</li></ul>',
            'Quality Management' => '<h3>Quality Management Framework</h3><p>Our quality management system ensures consistent delivery of high-quality services and products. This framework includes quality control procedures, documentation standards, and continuous improvement processes.</p><ul><li>Quality control procedures and protocols</li><li>Documentation and record keeping standards</li><li>Performance monitoring and measurement</li><li>Customer satisfaction management</li></ul>',
            'Environmental Management' => '<h3>Environmental Management System</h3><p>We are committed to environmental responsibility through our comprehensive environmental management system. This includes waste management, resource conservation, and environmental impact reduction strategies.</p><ul><li>Waste management and disposal procedures</li><li>Resource conservation initiatives</li><li>Environmental impact assessments</li><li>Sustainability reporting</li></ul>',
            'Training and Competency' => '<h3>Training and Competency Development</h3><p>Our training and competency framework ensures all personnel have the necessary skills and knowledge to perform their duties safely and effectively. This includes induction programs, ongoing training, and competency assessments.</p><ul><li>Comprehensive induction programs</li><li>Ongoing training and development</li><li>Competency assessment procedures</li><li>Skills gap analysis and planning</li></ul>',
            'Emergency Management' => '<h3>Emergency Management System</h3><p>Our emergency management system ensures we are prepared to respond effectively to various emergency situations. This includes emergency response plans, evacuation procedures, and communication protocols.</p><ul><li>Emergency response plans and procedures</li><li>Evacuation and assembly point protocols</li><li>Emergency communication systems</li><li>Regular emergency drills and training</li></ul>'
        ];
        
        return $contentMap[$title] ?? '<h3>' . $title . '</h3><p>This section contains important information about ' . strtolower($title) . '.</p>';
    }

    /**
     * Get demo content for child sections
     */
    private function getDemoContentForChild($title)
    {
        $contentMap = [
            'Safety Policies and Procedures' => '<h4>Safety Policies and Procedures</h4><p>Our safety policies and procedures provide clear guidance on workplace health and safety requirements. These documents are regularly reviewed and updated to ensure compliance with current legislation and best practices.</p>',
            'Risk Assessment Framework' => '<h4>Risk Assessment Framework</h4><p>Our risk assessment framework provides a systematic approach to identifying, assessing, and controlling workplace hazards. This process ensures risks are managed effectively and continuously monitored.</p>',
            'Quality Control Procedures' => '<h4>Quality Control Procedures</h4><p>Our quality control procedures ensure consistent quality standards across all operations. These procedures include inspection protocols, testing requirements, and quality assurance measures.</p>',
            'Documentation Standards' => '<h4>Documentation Standards</h4><p>We maintain high standards of documentation to ensure clear communication, accountability, and compliance. Our documentation standards cover record keeping, version control, and accessibility requirements.</p>',
            'Waste Management' => '<h4>Waste Management</h4><p>Our waste management procedures ensure proper handling, storage, and disposal of all waste materials. This includes segregation, recycling, and disposal of hazardous materials.</p>',
            'Induction Programs' => '<h4>Induction Programs</h4><p>Our induction programs ensure all new personnel understand workplace requirements, safety procedures, and company policies. These programs are tailored to different roles and responsibilities.</p>',
            'Competency Assessment' => '<h4>Competency Assessment</h4><p>Our competency assessment procedures ensure all personnel have the necessary skills and knowledge for their roles. This includes practical assessments, knowledge testing, and ongoing evaluation.</p>',
            'Emergency Response Plans' => '<h4>Emergency Response Plans</h4><p>Our emergency response plans provide clear procedures for responding to various emergency situations. These plans are regularly tested and updated to ensure effectiveness.</p>'
        ];
        
        return $contentMap[$title] ?? '<h4>' . $title . '</h4><p>This section contains detailed information about ' . strtolower($title) . '.</p>';
    }

    /**
     * Get demo content for grandchild sections
     */
    private function getDemoContentForGrandchild($title)
    {
        $contentMap = [
            'Workplace Health and Safety Policy' => '<h5>Workplace Health and Safety Policy</h5><p>Our workplace health and safety policy demonstrates our commitment to providing a safe and healthy work environment for all personnel. This policy is reviewed annually and communicated to all staff.</p><p><strong>Key Elements:</strong></p><ul><li>Management commitment to safety</li><li>Employee responsibilities and rights</li><li>Hazard identification and control</li><li>Incident reporting and investigation</li><li>Training and competency requirements</li></ul>',
            'Incident Reporting Procedures' => '<h5>Incident Reporting Procedures</h5><p>Our incident reporting procedures ensure all workplace incidents are properly reported, investigated, and managed. This includes near misses, injuries, and property damage incidents.</p><p><strong>Reporting Requirements:</strong></p><ul><li>Immediate reporting of serious incidents</li><li>Written incident reports within 24 hours</li><li>Investigation and root cause analysis</li><li>Corrective action implementation</li><li>Follow-up and monitoring</li></ul>',
            'Hazard Identification Process' => '<h5>Hazard Identification Process</h5><p>Our hazard identification process ensures all workplace hazards are systematically identified, assessed, and controlled. This process involves regular inspections, risk assessments, and employee consultation.</p><p><strong>Process Steps:</strong></p><ul><li>Regular workplace inspections</li><li>Task-specific risk assessments</li><li>Employee hazard reporting</li><li>Hazard register maintenance</li><li>Control measure implementation</li></ul>',
            'Inspection and Testing Protocols' => '<h5>Inspection and Testing Protocols</h5><p>Our inspection and testing protocols ensure all equipment, materials, and processes meet quality standards. These protocols include regular inspections, testing procedures, and documentation requirements.</p><p><strong>Protocol Elements:</strong></p><ul><li>Pre-use equipment inspections</li><li>Regular maintenance schedules</li><li>Quality testing procedures</li><li>Documentation and record keeping</li><li>Non-conformance management</li></ul>',
            'Hazardous Waste Disposal' => '<h5>Hazardous Waste Disposal</h5><p>Our hazardous waste disposal procedures ensure proper handling and disposal of hazardous materials in compliance with environmental regulations. This includes segregation, labeling, and disposal requirements.</p><p><strong>Disposal Requirements:</strong></p><ul><li>Proper segregation of waste types</li><li>Correct labeling and documentation</li><li>Licensed disposal contractors</li><li>Waste tracking and reporting</li><li>Environmental compliance monitoring</li></ul>',
            'Site Safety Induction' => '<h5>Site Safety Induction</h5><p>Our site safety induction ensures all personnel understand site-specific hazards, safety procedures, and emergency protocols. This induction is mandatory for all personnel before commencing work.</p><p><strong>Induction Topics:</strong></p><ul><li>Site-specific hazards and controls</li><li>Emergency procedures and assembly points</li><li>Personal protective equipment requirements</li><li>Incident reporting procedures</li><li>Site rules and expectations</li></ul>',
            'Fire Emergency Procedures' => '<h5>Fire Emergency Procedures</h5><p>Our fire emergency procedures provide clear guidance for responding to fire emergencies. These procedures include evacuation routes, assembly points, and communication protocols.</p><p><strong>Emergency Response:</strong></p><ul><li>Fire detection and alarm systems</li><li>Evacuation routes and procedures</li><li>Assembly point locations</li><li>Emergency communication protocols</li><li>Fire warden responsibilities</li></ul>',
            'Medical Emergency Response' => '<h5>Medical Emergency Response</h5><p>Our medical emergency response procedures ensure prompt and appropriate response to medical emergencies. This includes first aid procedures, emergency contact information, and medical facility locations.</p><p><strong>Response Elements:</strong></p><ul><li>First aid procedures and equipment</li><li>Emergency contact information</li><li>Medical facility locations</li><li>Incident reporting requirements</li><li>Follow-up and support services</li></ul>'
        ];
        
        return $contentMap[$title] ?? '<h5>' . $title . '</h5><p>This section contains specific information about ' . strtolower($title) . '.</p>';
    }

    public function createDemoSwmsReport($customerId, $workspaceId)
    {
        // 1. Get a valid employee for site_manager_or_forman
        $siteManager = EmpCompanyDetails::where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->inRandomOrder()
            ->first();

        $site = Sites::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->first();

        $swms = Swms::create([
            'swms_number' => rand(1000, 9999),
            'title' => 'Demo SWMS Report',
            'site_manager_or_forman' => $siteManager ? $siteManager->id : null, // <-- Set a valid emp_id
            'revision_number' => 'R1',
            'version_number' => 'V1',
            'start_date' => now()->format('Y-m-d'),
            'company_name' => 'Demo Company',
            'site_id' => $site ? $site->id : null,
            'contact_number' => '555-0000',
            'company_address' => '123 Demo St',
            'scope_of_work' => 'Demo scope of work',
            'fast_address' => '123 Demo St',
            'principal_contractor' => 'Demo Contractor',
            'principal_contractor_address' => '123 Contractor St',
            'principal_contractor_number' => '555-1111',
            'description' => 'Demo SWMS description',
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
            'workplace_location_address' => 'Demo Location',
            'published' => '0',
        ]);

        // 2. Create SWMS Meta (Step 2)
        SwmsMeta::create([
            'swms_id' => $swms->id,
            'consultation_method' => 'Toolbox Talk',
            'review_frequency' => 'monthly',
            'recieved_date' => now()->format('Y-m-d'),
            'date_recieved_by_reviewer' => now()->format('Y-m-d'),
            'is_based_on_risk' => 'yes',
            'is_worker_consulted' => 'yes',
            'is_hsr_consulted' => 'No',
            'person_responsible_for_reviewing_swms' => 'Demo Reviewer',
            'person_responsible_for_ensuring_compliance' => 'Demo Compliance',
        ]);

        // 3. General Notes Answers (Step 2)
        $generalNotes = SwmsGeneralNote::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->get();
        foreach ($generalNotes as $note) {
            SwmsGeneralNoteAnswers::create([
                'swms_id' => $swms->id,
                'swms_general_notes_id' => $note->id,
                'answer' => 'Demo answer for ' . $note->title,
            ]);
        }

        // 4. Developed By & Approved By Signatures (Step 3)
        $employees = EmpCompanyDetails::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->limit(2)->pluck('id');
        foreach ($employees as $empId) {
            swmsDevelopedBy::create([
                'swms_id' => $swms->id,
                'employee_id' => $empId,
                'signature' => null,
                'date' => now()->format('Y-m-d'),
            ]);
            SwmsApprovedBy::create([
                'swms_id' => $swms->id,
                'employee_id' => $empId,
                'signature' => null,
                'date' => now()->format('Y-m-d'),
            ]);
        }

        // 5. Job Tasks (Step 4)
        for ($i = 1; $i <= 3; $i++) {
            SwmsTaskDetail::create([
                'swms_id' => $swms->id,
                'responsible_preson_id' => $employees->random(),
                'job_task' => 'Demo Task ' . $i,
                'risk' => 'Demo Risk ' . $i,
                'initial_risk_rating' => rand(1, 5),
                'hazard' => 'Demo Hazard ' . $i,
                'controle_risk_ratting' => rand(1, 5),
                'control_measure' => 'Demo Control Measure ' . $i,
                'final_risk_ratting' => rand(1, 5),
                'image' => 'assets/img/default.png',
            ]);
        }

        // 6. Hazard Risks & Protection Tools (Step 5)
        $hazardRisks = HazardRisk::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->pluck('id')->toArray();
        $protectionTools = SwmsProtectionTool::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->pluck('id')->toArray();
        foreach (array_slice($hazardRisks, 0, 2) as $hazardId) {
            SwmsHazardRiskPivot::create([
                'swms_id' => $swms->id,
                'hazard_risks_id' => $hazardId,
            ]);
        }
        foreach (array_slice($protectionTools, 0, 2) as $toolId) {
            SwmsProtectionToolPivot::create([
                'swms_id' => $swms->id,
                'protection_tool_id' => $toolId,
            ]);
        }

        // 7. SWMS Questions & Answers (Step 5)
        $questions = SwmsQuestions::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->pluck('id');
        foreach ($questions as $questionId) {
            SwmsAwnswers::create([
                'swms_id' => $swms->id,
                'swms_question_id' => $questionId,
                'answer' => 'Demo answer' . $questionId,
            ]);
        }

        // 8. Safety Planning Questions (Step 6)
        $safetyQuestions = SwmsSafetyPlanningQuestion::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->pluck('id');
        foreach ($safetyQuestions as $sqId) {
            SwmsSafetyPlanningAnswers::create([
                'swms_id' => $swms->id,
                'swms_safety_planning_id' => $sqId,
                'answer' => 'Demo safety answer' . $sqId,
            ]);
        }

        // 9. SWMS Signatures (Step 6)
        $roles = Role::where('del', '0')->pluck('id');
        // foreach ($roles as $roleId) {
        //     SwmsSignature::create([
        //         'swms_id' => $swms->id,
        //         'tier_id' => $roleId,
        //         'job_desription' => 'Demo Job' . $roleId,
        //         'inductance_date' => now()->format('Y-m-d'),
        //     ]);
        // }

        // 10. Mark as published/complete if needed
        $swms->update(['process' => '1']);

        return $swms;
    }

    public function createDemoInspectionPlan($customerId, $workspaceId)
    {
        $faker = Faker::create();
        DB::beginTransaction();
            $site = Sites::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->first();
            $project = Project::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->first();
            $employee = EmpCompanyDetails::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->first();

            $settingsExist = InspectionPlanTable::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->exists();
            if (!$settingsExist) {
                DB::rollBack();
                return $this->message('Inspection Plan settings are not seeded. Please run the seeder first.', 404);
            }

            // --- STEP 1: Create the main InspectionPlan record ---
            $inspectionPlan = InspectionPlan::create([
                'title' => 'Demo Inspection Plan Report',  // Random 3-word sentence
                'document_number' => $faker->unique()->numberBetween(100, 999),  // Random number between 100 and 999
                'authorised_by' => $employee ? $employee->id : null,
                'revision_number' => 'R1',  // Random revision number
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'issue_date' => now()->subDays(2)->format('Y-m-d'),
                'revision_date' => now()->addDays(2)->format('Y-m-d'),
                'site_id' => $site ? $site->id : null,
                'del' => '0',
            ]);

            // --- STEP 2: Update Plan with details and create Checklist entries ---
            $inspectionPlan->update([
                'principal_contractor' => $faker->company,  // Random company name
                'principal_contractor_email' => $faker->email,  // Random email
                'project_name' => $project ? $project->id : null,
                'job_number' => $faker->unique()->numberBetween(10000, 99999),  // Random job number
                'activity' => $faker->sentence,  // Random sentence for activity
                'level' => $faker->randomNumber(3, true),  // Random word for level
                'to_level' => $faker->randomNumber(3, true),  // Random word for to_level
                'building' => $faker->word,  // Random word for building
                'zone' => $faker->word,  // Random word for zone
                'pour' => $faker->sentence,  // Random sentence for pour
                'itp_reference_number' => $faker->unique()->numberBetween(100000, 999999),  // Random number for ITP reference
                'open_date' => $faker->date('Y-m-d', 'now'),  // Random open date
            ]);

            $step2Data = [
                "Column_status" => "1", "Column_notes" => $faker->sentence,
                "Stair_status" => "1", "Stair_notes" => $faker->sentence,
                "Stripping-klist-and-Order_status" => "1", "Stripping-klist-and-Order_notes" => $faker->sentence,
                // Inactive steps from your example
                "Wall_status" => "0", "Deck-Pre-Pour_status" => "0", "Concrete-Machine_status" => "0",
            ];

            $checklistIds = [];
            foreach ($step2Data as $key => $value) {
                if (str_ends_with($key, '_status') && $value === '1') {
                    $stepName = str_replace('_status', '', $key);
                $checklist = InspectionPlanChecklist::create([
                    'inspection_plan_id' => $inspectionPlan->id,
                        'name' => $stepName,
                        'status' => '1',
                        'itpc_number' => $step2Data[$stepName] ?? $faker->words(3, true), // Added this line
                        'checklist_note' => $step2Data[$stepName . '_notes'] ?? null,
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                    'is_complete' => 0,
                ]);
                    // Store the ID for the next step
                    $checklistIds[$stepName] = $checklist->id;
                }
            }

            // --- STEP 3: Store detailed data for EACH active checklist ---
            foreach ($checklistIds as $stepName => $itpcId) {
                $companyName = $faker->company;
                $principalName = $faker->name;

                InspectionPlanGeneral::create([
                    'inspection_plan_id' => $inspectionPlan->id,
                    'iptc_id' => $itpcId,
                    'level' => $faker->words(2, true),
                    'to_level' => $faker->words(2, true),
                    'pour' => $faker->sentence,
                    'architectural_drawing_number' => $faker->randomNumber(3, true),
                    'structectural_drawing_number' => $faker->randomNumber(3, true),
                    'Post_Tension_Drawing_Number' => $faker->randomNumber(3, true),
                    'partial_Handover' => '1',
                    'partial_Handover_date' => $faker->dateTimeThisMonth()->format('Y-m-d'),
                    'partial_Handover_time' => $faker->time('H:i'),
                    'partial_Handover_location' => $faker->secondaryAddress,
                    'complete_handover' => '1',
                    'complete_handover_date' => $faker->dateTimeThisMonth()->format('Y-m-d'),
                    'complete_handover_time' => $faker->time('H:i'),
                    'complete_handover_Location' => $faker->secondaryAddress,
                    'company_group_name' => $companyName,
                    'company_group_date' => $faker->date('Y-m-d'),
                    'principal_name' => $principalName,
                    'principal_date' => $faker->date('Y-m-d'),
                ]);

                // Store Table Values (Meta Data) for this step
                $thead = [];
                for ($i = 0; $i < 7; $i++) {
                    $thead[] = $faker->words(2, true);
                }

                $tableValues = [];
                for ($i = 0; $i < 2; $i++) {
                    $row = [];
                    for ($j = 0; $j < 7; $j++) {
                        $row[] = $faker->words(3, true);
                    }
                    $tableValues[] = $row;
                }

                foreach ($tableValues as $row) {
                    foreach ($row as $colIndex => $value) {
                        InspectionPlanMeta::create([
                            'inspection_plan_id' => $inspectionPlan->id,
                            'itpc_id' => $itpcId,
                            'title' => $thead[$colIndex],
                            'value' => $value,
                            'name' => $stepName, // Dynamic name
                            'customer_id' => $customerId,
                            'workspace_id' => $workspaceId,
                            'is_table' => 0, // 0 for data, 1 for settings
                        ]);
                }
            }

            // InspectionPlanSignature::create([
            //         'inspection_plan_id' => $inspectionPlan->id, 'itpc_id' => $itpcId,
            //         'employee_name' => $companyName, 'date' => now()->format('Y-m-d'),
            //         'signature' => 'signatures/demo_company_signature.png', 'signature_type' => '1', // Company Signature
            //     ]);
            //     InspectionPlanSignature::create([
            //         'inspection_plan_id' => $inspectionPlan->id, 'itpc_id' => $itpcId,
            //         'employee_name' => $principalName, 'date' => now()->format('Y-m-d'),
            //         'signature' => 'signatures/demo_principal_signature.png', 'signature_type' => '2', // Principal Signature
            //     ]);

                InspectionImage::create([
                'inspection_plan_id' => $inspectionPlan->id,
                    'itpc_id' => $itpcId,
                    'image' => 'assets/img/default.png',
                ]);

                InspectionPlanChecklist::where('id', $itpcId)->update(['is_complete' => '1']);
            }

            $inspectionPlan->process = '1';
            $inspectionPlan->save();

            // --- FINAL STEP: Store Description Box ---
            $inspectionPlan->update([
                'description' => 'This is a final description for the generated demo inspection plan. All steps and checklists have been processed.'
            ]);

            DB::commit();
            return $this->success(['inspection_plan_id' => $inspectionPlan->id], 'Demo inspection plan created successfully!');

    }


    public function createDemoIncidentReport($customerId, $workspaceId)
    {
        $faker = Faker::create();
        DB::beginTransaction();
            // --- 1. Fetch Prerequisite Data ---
            $site = Sites::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->first();
            $project = Project::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->first();
            $employees = EmpCompanyDetails::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->get();
            $roles = Role::where('del', '0')->get();

            if ($employees->count() < 4) {
                DB::rollBack();
                return $this->message1('Not enough employee data to create a demo incident report.', 404);
            }
            $employee_slice = $employees->random(4);
            $authorised_by = $employee_slice[0];
            $report_compiled_by = $employee_slice[1];
            $reported_by = $employee_slice[1];
            $reported_to = $employee_slice[2];
            $involved_person = $employee_slice[3];
            $supervisor = $employees->where('access_role', 'SPV')->first() ?? $employee_slice[0];

            // Fetch settings IDs
            $injury_classification_ids = IncidentInjuryClassification::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->pluck('id');
            $notifiable_classification_ids = IncidentNotifiableClassification::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->pluck('id');
            $report_question_ids = IncidentReportQuestion::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->pluck('id');
            $injury_type_ids = IncidentInjuryType::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->pluck('id');
            $training_ids = DB::table('trainings')->where('customer_id', $customerId)->where('workspace_id', $workspaceId)->pluck('id');
            $risk_category_id = IncidentRiskCategory::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->value('id');

            if ($injury_classification_ids->isEmpty() || $report_question_ids->isEmpty() || $injury_type_ids->isEmpty()) {
                DB::rollBack();
                return $this->message1('Incident report settings are not seeded. Please run seeders first.', 404);
            }

            // --- 2. Create Main Incident Report ---
            $incidentReport = IncidentReport::create([
                'title' => 'Demo Incident Report',
                'document_number' => $faker->unique()->numberBetween(100, 9999),
                'revision_number' => '1',
                'authorised_by' => $authorised_by->id,
                'issue_date' => now()->subDays(2)->format('Y-m-d'),
                'revision_date' => now()->addDays(2)->format('Y-m-d'),
                'site_id' => $site ? $site->id : null,
                'project_id' => $project ? $project->id : null,
                'incident_date' => $faker->dateTimeThisMonth()->format('Y-m-d'),
                'incident_time' => $faker->time('H:i'),
                'date_incident_reported' => now()->format('Y-m-d'),
                'time_incident_reported' => now()->format('H:i'),
                'report_compiled_by' => $report_compiled_by->id,
                'investigation_number' => $faker->unique()->numberBetween(1000, 9999),
                'office_number' => $faker->unique()->numberBetween(100, 9999),
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_by' => $customerId,
                // Step 6 fields
                'is_plant_involved' => 0,
                'plant_name' => 1,
                'is_victim' => 1,
                'is_correct_action_required' => 1,
                // Step 7 fields
                'is_injury_management' => 0,
                'incident_response' => $faker->sentence,
                // Step 8 fields
                'is_final_incident_classification' => 0,
                'is_final_injury_classification' => 1,
                'lti_or_rwi' => 1,
                // Step 10 fields
                'process' => 1,
                'step_no' => 10,
            ]);

            // Reported By / To
            IncidentReportedBy::create([
                'incident_report_id' => $incidentReport->id,
                'reported_by' => $reported_by->id,
                'role' => $reported_by->job_title,
                'company_name' => $faker->company,
                'contact_number' => $faker->phoneNumber,
                'position_id' => $roles->random()->id
            ]);
            IncidentReportedTo::create([
                'incident_report_id' => $incidentReport->id,
                'reported_to' => $reported_to->id,
                'role' => $reported_to->job_title,
                'company_name' => $faker->company,
                'contact_number' => $faker->phoneNumber,
                'position_id' => $roles->random()->id
            ]);
            // Classifications
            foreach($injury_classification_ids->random(min(2, $injury_classification_ids->count())) as $id){
                IncidentClassificationReport::create([
                    'incident_report_id' => $incidentReport->id,
                    'injury_classification_id' => $id,
                    'details' => $id == 1 ? $faker->sentence : '',
                    'type' => 1
                ]);
            }

            $demoInjuryClassIds = $injury_classification_ids->random(min(2, $injury_classification_ids->count()))->toArray();

            if (!in_array(1, $demoInjuryClassIds) && $injury_classification_ids->contains(1)) {
                $demoInjuryClassIds[0] = 1; // force "Other" in demo
            }

            IncidentClassificationReport::where([
                'incident_report_id' => $incidentReport->id,
                'type' => '0'
            ])->delete();


            $demoClassifications = array_map(function ($c_id) use ($incidentReport) {
                return [
                    "incident_report_id" => $incidentReport->id,
                    "injury_classification_id" => $c_id,
                    "details" =>  "",
                    "type" => "0",
                    "created_at" => now(),
                    "updated_at" => now()
                ];
            }, $demoInjuryClassIds);

            IncidentClassificationReport::insert($demoClassifications);
            if($notifiable_classification_ids->isNotEmpty()){
                IncidentReportNotifiableClassification::create([
                    'incident_report_id' => $incidentReport->id,
                    'notifiable_classification_id' => $notifiable_classification_ids->random()
                ]);
            }
            $incidentReport->is_notified_to = 1;
            $incidentReport->save();
            // Involved Person Details
            $person_details = IncidentInvolvedPersonDetail::create([
                'incident_report_id' => $incidentReport->id,
                'employee_id' => $involved_person->id,
                'supervisor' => $supervisor->id,
                'dob' => $involved_person->personalDetails->date_of_birth ?? $faker->date('Y-m-d', '-20 years'),
                'age' => $faker->numberBetween(20, 60),
                'gender' => $faker->randomElement([0, 1]),
                'contact_number' => $involved_person->personalDetails->mobile ?? $faker->phoneNumber,
                'language' => 'English',
                'occupation' => $involved_person->job_title,
                'experience_years' => $faker->numberBetween(0, 10),
                'experience_months' => $faker->numberBetween(0, 11),
                'is_employer_worker' => 'Employee',
                'employment_type' => $involved_person->employment_type,
            ]);
            // Link Injury Types to Involved Person
            foreach($injury_type_ids->random(min(3, $injury_type_ids->count())) as $id){
                IncidentEmployeeInjuryType::create([
                    'incident_report_id' => $incidentReport->id,
                    'person_id' => $person_details->id, 
                    'injury_type_id' => $id
                ]);
            }
            // Link Training to Involved Person
            if($training_ids->isNotEmpty()){
                IncidentInvolvedPersonTraining::create([
                    'incident_report_id' => $incidentReport->id,
                    'person_id' => $person_details->id,
                    'training_id' => $training_ids->random()
                ]);
            }
            // Question Answers
            foreach($report_question_ids->random(min(5, $report_question_ids->count())) as $id){
                IncidentReportQuestionAnswer::create([
                    'incident_report_id' => $incidentReport->id,
                    'question_id' => $id,
                    'answer' => $faker->sentence
                ]);
            }
            // --- Step 6: Meta Information ---
            IncidentReportMeta::updateOrCreate(
                ['incident_report_id' => $incidentReport->id],
                [
                    'equipment_type' => $faker->word,
                    'registration_number' => $faker->randomNumber(4),
                    'damage' => $faker->sentence,
                    'cost' => $faker->randomFloat(2, 100, 10000),
                    'shift_type' => 'Evening',
                    'shift_time' => '12:00 AM - 15:59 PM',
                ]
            );
            // --- Step 7: Injury Management ---
            IncidentInjuryManagement::updateOrCreate(
                ['incident_report_id' => $incidentReport->id],
                [
                    'date' => now()->format('Y-m-d'),
                    'time' => now()->format('H:i'),
                    'representative_name' => $faker->name,
                    'previous_injury_date' => $faker->date('Y-m-d', '-1 year'),
                    'injured_names' => $faker->name,
                    'is_first_aid' => 1,
                    'is_referred' => 1,
                    'is_doctor' => 1,
                    'is_clinic' => 1,
                    'is_admit' => 1,
                    'return_to_work' => 1,
                    'is_doctor_details' => 0,
                    'doctor_name' => $faker->name,
                    'doctor_number' => $faker->phoneNumber,
                    'doctor_address' => $faker->address,
                    'hospital_name' => $faker->company,
                    'hospital_number' => $faker->phoneNumber,
                    'hospital_address' => $faker->address,
                    'incident_response' => $faker->sentence,
                    'is_recurrence_injury' => 0,
                    'previous_report_number' => $faker->randomNumber(4),
                    'is_hospital_details' => 0,
                ]
            );
            // --- Step 8: Final Classification ---
            IncidentFinalClassification::updateOrCreate(
                ['incident_report_id' => $incidentReport->id],
                [
                    'final_incident_name' => 1,
                    'final_incident_details' => $faker->sentence,
                    'is_rehabilitation' => 1,
                    'return_to_duty_date' => now()->addDays(10)->format('Y-m-d'),
                    'rtw_date' => now()->addDays(15)->format('Y-m-d'),
                    'total_lost_days' => $faker->numberBetween(0, 10),
                    'is_worker_notified' => 1,
                    'notified_by_whom' => $authorised_by->id,
                    'date' => now()->format('Y-m-d'),
                    'time' => now()->format('H:i'),
                    'details' => $faker->sentence,
                ]
            );
            // --- Step 8: Sign-Offs ---
            // List of role codes you want to create signoffs for
            $roleCodes = ['FM', 'SSO']; 

            // foreach ($roleCodes as $roleCode) {
            //     $role = $roles->where('code', $roleCode)->first();
            //     if ($role) {
            //         $employeesWithRole = $employees->where('access_role', $role->code);
            //         foreach ($employeesWithRole as $emp) {
            //             IncidentSignoff::updateOrCreate(
            //                 [
            //                     'incident_report_id' => $incidentReport->id,
            //                     'role_code' => $roleCode,
            //                     'emp_id' => $emp->id,
            //                 ],
            //                 [
            //                     'name' => $emp->first_name . '' . $emp->last_name ?? $faker->name,
            //                     'signature' => 'signatures/demo_sign.png',
            //                     'date' => now()->format('Y-m-d'),
            //                     'time' => now()->format('H:i'),
            //                 ]
            //             );
            //         }
            //     }
            // }

            // --- Step 9: Risk Category Details ---
            IncidentRiskCategoryDetail::updateOrCreate(
                ['incident_report_id' => $incidentReport->id],
                [
                    'incident_risk_category_id' => $risk_category_id,
                    'details' => $faker->sentence,
                ]
            );
            // --- Step 9: Witnesses ---
            IncidentWitnes::where('incident_report_id', $incidentReport->id)->delete();
            for ($i = 0; $i < 2; $i++) {
                IncidentWitnes::create([
                    'incident_report_id' => $incidentReport->id,
                    'name' => $faker->name,
                    'date' => now()->format('Y-m-d'),
                    'time' => now()->format('H:i'),
                    'statement_number' => $faker->randomNumber(3),
                ]);
            }
            // --- Step 9: Documents ---
            IncidentDocument::where('incident_report_id', $incidentReport->id)->delete();
            for ($i = 0; $i < 2; $i++) {
                IncidentDocument::create([
                    'incident_report_id' => $incidentReport->id,
                    'title' => $faker->sentence(3),
                    'number' => $faker->randomNumber(4),
                ]);
            }
            // --- Step 10: Mark as processed ---
            $incidentReport->process = 1;
            $incidentReport->step_no = 10;
            $incidentReport->save();

            // --- Step X: Demo Incident Images ---
            // $demoImagePaths = [
            //     'assets/img/default.png',
            // ];

            // foreach ($demoImagePaths as $imgPath) {
            //     IncidentImage::create([
            //         'incident_report_id' => $incidentReport->id,
            //         'image' => $imgPath,
            //     ]);
            // }



            DB::commit();
            return $this->success(['incident_report_id' => $incidentReport->id], 'Demo incident report created successfully!');

    }

    public function createDemoMeeting($customerId, $workspaceId)
    {
        $faker = Faker::create();
        $customer = User::find($customerId);
        if (!$customer) {
            return $this->message('Customer not found.', 404);
        }

        $site = Sites::where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->where('active', 1)
            ->where('del', 0)
            ->first();

        if (!$site) {
            $site = Sites::where('active', 1)->where('del', 0)->inRandomOrder()->first();
        }
        $project = Project::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->inRandomOrder()->first();
        $lastEmployee = EmpCompanyDetails::where('customer_id', $customerId)
        ->where('workspace_id', $workspaceId)
        ->orderByDesc('id') // get the last added employee
        ->first();
        $employee = EmpCompanyDetails::with('empPersonalDetails')
        ->where('customer_id', $customerId)
        ->where('workspace_id', $workspaceId)
        ->where('id', '!=', $lastEmployee->id) // exclude the last record
        ->inRandomOrder()  
        ->first();  
    
        do {
            $organiser = EmpCompanyDetails::with('empPersonalDetails')
                ->where('customer_id', $customerId)
                ->where('workspace_id', $workspaceId)
                ->where('id', '!=', $lastEmployee->id) // exclude the last record
                ->inRandomOrder()  
                ->first();   
        } while ($organiser->id === $employee->id);
      
        $demoSettings = [
            [
                'title' => 'Safety Briefing',
                'description' => 'Brief about today\'s site-specific safety procedures.',
                'type_of_setting' => 'toolbox'
            ],
            [
                'title' => 'Task Allocation',
                'description' => 'Assigning duties to team members for different tasks.',
                'type_of_setting' => 'toolbox'
            ],
            [
                'title' => 'Weather Conditions',
                'description' => 'Discuss expected weather and its impact on work.',
                'type_of_setting' => 'toolbox'
            ],
        ];
        
        foreach ($demoSettings as $setting) {
            MeetingDocumentSetting::create([
                'title' => $setting['title'],
                'description' => $setting['description'],
                'type_of_setting' => $setting['type_of_setting'],
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
            ]);
        }
        
        // Create the meeting
        $meeting = Meeting::create([
            'created_by' => $customerId,
            'workspace_id' => $workspaceId,
            'customer_id' => $customerId,
            'site_id' => $site->id,
            'agenda' => "Demo Meeting",
            'description' => "Demo Meeting Description",
            'status' => config('constants.meeting_status.pending.key'),
            'start_date' => now()->format('Y-m-d'),
            'end_date' => now()->format('Y-m-d'),
            'start_time' => '09:00',
            'end_time' => '10:00',
            'is_recurring' => 0,
            'allow_meeting_members' => 0,
            'frequency' => null,
            'days' => null,
            'allow_guest' => 1,
            'is_before_meeting' => 0
        ]);

        // Attach organiser
        MeetingOrganiser::create([
            'meeting_id' => $meeting->id,
            'site_id' => $site->id,
            'organiser_id' => $organiser->id
        ]);

        $meetingDocumentNote = MeetingDocumentNote::create([
            'meeting_id' => $meeting->id,
            'prestart_facilitated_by' => $organiser->id ?? null,
            'comments_on_weather' => $faker->sentence(3),
            'project_id' => $project ? $project->id : null,
            'project_number' => $faker->randomNumber(4),
            'site_id' => $site->id,
            'prestart_meeting_notes' => $faker->sentence(3),
            'day_of_the_week' => now()->format('Y-m-d'),
            'type_of_setting' => 'toolbox',
        ]);

        $meetingDocument = new MeetingDocument();
        $meetingDocument->meeting_id = $meeting->id;
        $meetingDocument->title = 'Demo Document';
        $meetingDocument->meeting_date = now()->format('Y-m-d');
        $meetingDocument->uploaded_by = $customerId;
        $meetingDocument->is_signed = 0;
        $meetingDocument->document_path = 'assets/img/default.png'; 
        $meetingDocument->save();

        DB::table('meeting_note_documents_pdfs')->updateOrInsert(
            [
                'meeting_id' => $meeting->id,
                'meeting_note_id' => $meetingDocumentNote->id,
            ],
            [
                'meeting_id' => $meeting->id,
                'meeting_note_id' => $meetingDocumentNote->id,
                'document_path' => null,
                'title' => $meeting->agenda ?? 'Meeting Document',
                'uploaded_by' => $customerId,
                'status' => 0,
            ]
        );

        // Optionally, add a demo MeetingNoteTable row (Step 3)
        $step3Types = [
            'erecting_framework',
            'stripping_framework',
            'jumping_framework',
            'installing_framework',
            'dismantling_framework',
            'stripping_no_framework',
            'preparing_walls',
            'bondek',
            'other',
        ];

        foreach ($step3Types as $type) {
            MeetingNoteTable::create([
                'meeting_id' => $meeting->id,
                'meeting_note_id' => $meetingDocumentNote->id,
                'name' => $type,
                'building' => $faker->sentence(2),
                'level' => $faker->randomDigitNotNull(), 
                'area' => $faker->sentence(1),
                'workfore_allocation' => $faker->sentence(1),
                'del' => '0',
            ]);
        }
        
        // Add history
        $history_description = sprintf(
    "Demo meeting created by %s at %s",
    $organiser && $organiser->empPersonalDetails
                ? trim($organiser->empPersonalDetails->first_name . ' ' . $organiser->empPersonalDetails->middle_name . ' ' . $organiser->empPersonalDetails->last_name)
                :'Demo User',  
            now()->format('d/m/Y H:i:s')
        );
        
        $this->storeMeetingHistory($meeting->id, $history_description,$organiser->id);

        MeetingGuestUser::create([
            'meeting_id'   => $meeting->id,
            'name'         => $faker->name,
            'email'        => $faker->safeEmail,
            'phone_number' => $faker->phoneNumber,
            'occupation'   => $faker->jobTitle,
            'details'      => $faker->sentence(6),
            'added_by'     => $customerId,
            'meeting_date' => Carbon::parse($meeting->start_date)->format('Y-m-d'),
        ]);

        return [
            'meeting' => $meeting,
            'document_note' => $meetingDocumentNote,
            'document' => $meetingDocument
        ];
    }
    function storeMeetingHistory($meeting_id, $description,$customerId)
    {
        MeetingHistory::create([
            'meeting_id' => $meeting_id,
            'updated_by' => $customerId,
            'description' => $description
        ]);
    }
    public function demoData(Request $request)
    {
        if($request->demo_data == 1){
            $user = User::find($request->user_id);
            if($user->demo_data == 1){
                return $this->error('Demo data already exists!');
            }
            $customer = $this->createDemoCustomer($user);
            if($customer){
                
                // Get permissions and settings for the specific user
                $permissions = $this->getUserPermissionsForUser($user);
                $settings = $this->getUserSettingsForUser($user);
                
                $data = [
                    'permissions' => $permissions,
                    'settings' => $settings,
                ];
                return $this->success($data, 'Demo data created successfully');
            }else{
                return $this->error('Demo data creation failed');
            }
        }

        if($request->demo_data == 0){
            $user = User::find($request->user_id);
            if($user->demo_data == 0){
                return $this->error('No demo data exists to delete!');
            }
            $result = $this->clearDemoData($user);
            if($result){
                // Get permissions and settings for the specific user
                $this->storeDemoAdminSettings($user->id, $user->current_workspace_id);
                $permissions = $this->getUserPermissionsForUser($user);
                $settings = $this->getUserSettingsForUser($user);
                
                $data = [
                    'permissions' => $permissions,
                    'settings' => $settings,
                ];
                return $this->success($data, 'Demo data cleared successfully');
            }else{
                return $this->error('Demo data clearing failed');
            }
        }

        // If no specific demo_data parameter, use authenticated user (legacy behavior)
        $userId = auth()->id();
        $workspaceId = auth()->user()->current_workspace_id;
 
        $user = User::find($userId);
        if (!$user) {
            return $this->error('User not found.');
        }
        
        return $this->clearDemoData($user);
    }
    
    /**
     * Clear all demo data for a specific user
     */
    private function clearDemoData($user)
    {
        $userId = $user->id;
        $workspaceId = $user->current_workspace_id;
 
        DB::beginTransaction();
        try {
            // Delete all demo data in reverse order of creation to avoid foreign key constraints
           
            // 1. Delete Meeting related data
            $meetingIds = Meeting::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($meetingIds->count() > 0) {
                // Delete meeting documents and images
                MeetingDocument::whereIn('meeting_id', $meetingIds)->delete();
                MeetingDocumentNote::whereIn('meeting_id', $meetingIds)->delete();
                MeetingHistory::whereIn('meeting_id', $meetingIds)->delete();
                MeetingNoteTable::whereIn('meeting_id', $meetingIds)->delete();
                MeetingOrganiser::whereIn('meeting_id', $meetingIds)->delete();
                MeetingUser::whereIn('meeting_id', $meetingIds)->delete();
                MeetingGuestUser::whereIn('meeting_id', $meetingIds)->delete();
                MeetingNoteDocumentsPdf::whereIn('meeting_id', $meetingIds)->delete();
               
                // Delete meetings
                Meeting::whereIn('id', $meetingIds)->delete();
            }
 
            // Delete meeting document settings separately (they don't have meeting_id)
            MeetingDocumentSetting::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();

            // 1.5. Delete Defect related data
            $defectIds = Defect::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');

            if ($defectIds->count() > 0) {
                DefectHistory::whereIn('defect_id', $defectIds)->delete();
                DefectImage::whereIn('defect_id', $defectIds)->delete();
            }

            Defect::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();

            // 1.6. Delete Site Diary related data
            $siteDiaryIds = \App\Models\SiteDiary::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');

            if ($siteDiaryIds->count() > 0) {
                \App\Models\SiteDiaryEquipment::whereIn('site_diary_id', $siteDiaryIds)->delete();
                \App\Models\SiteDiaryTask::whereIn('site_diary_id', $siteDiaryIds)->delete();
                \App\Models\SiteDiaryImage::whereIn('site_diary_id', $siteDiaryIds)->delete();
                \App\Models\SiteDiaryLog::whereIn('site_diary_id', $siteDiaryIds)->delete();
            }

            \App\Models\SiteDiary::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();

            // 1.7. Delete Asset related data
            Asset::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();

            // 2. Delete Incident Report related data
            $incidentReportIds = IncidentReport::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($incidentReportIds->count() > 0) {
                IncidentClassificationReport::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentDocument::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentInvolvedPersonDetail::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentEmployerDetail::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentReportMeta::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentReportQuestionAnswer::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentInjuryManagement::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentFinalClassification::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentRiskCategoryDetail::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentWitnes::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentSignoff::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentReportedBy::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentReportedTo::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentNotifiedTo::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentReportNotifiableClassification::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentInvolvedPersonTraining::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentEmployeeInjuryType::whereIn('incident_report_id', $incidentReportIds)->delete();
                IncidentImage::whereIn('incident_report_id', $incidentReportIds)->delete();
            }
           
            IncidentReport::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 3. Delete Inspection Plan related data
            $inspectionPlanIds = InspectionPlan::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($inspectionPlanIds->count() > 0) {
                InspectionPlanChecklist::whereIn('inspection_plan_id', $inspectionPlanIds)->delete();
                InspectionPlanGeneral::whereIn('inspection_plan_id', $inspectionPlanIds)->delete();
                InspectionPlanSignature::whereIn('inspection_plan_id', $inspectionPlanIds)->delete();
                InspectionImage::whereIn('inspection_plan_id', $inspectionPlanIds)->delete();
            }
           
            // Delete InspectionPlanMeta separately (it has customer_id and workspace_id directly)
            InspectionPlanMeta::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
           
            // Delete InspectionPlanTable separately (it has customer_id and workspace_id, not inspection_plan_id)
            InspectionPlanTable::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
           
            InspectionPlan::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 4. Delete WHS Reports related data
            $whsReportIds = WhsReport::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($whsReportIds->count() > 0) {
                WhsAdditionalPerson::whereIn('whs_report_id', $whsReportIds)->delete();
                WhsConductedBy::whereIn('whs_report_id', $whsReportIds)->delete();
                WhsReportHazards::whereIn('whs_report_id', $whsReportIds)->delete();
                WhsReportItem::whereIn('whs_report_id', $whsReportIds)->delete();
            }
           
            WhsReport::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 5. Delete SWMS Reports related data
            $swmsIds = Swms::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($swmsIds->count() > 0) {
                SwmsApprovedBy::whereIn('swms_id', $swmsIds)->delete();
                SwmsAwnswers::whereIn('swms_id', $swmsIds)->delete();
                swmsDevelopedBy::whereIn('swms_id', $swmsIds)->delete();
                SwmsGeneralNoteAnswers::whereIn('swms_id', $swmsIds)->delete();
                SwmsHazardRiskPivot::whereIn('swms_id', $swmsIds)->delete();
                SwmsMeta::whereIn('swms_id', $swmsIds)->delete();
                SwmsProtectionToolPivot::whereIn('swms_id', $swmsIds)->delete();
                SwmsSafetyPlanningAnswers::whereIn('swms_id', $swmsIds)->delete();
                SwmsSignature::whereIn('swms_id', $swmsIds)->delete();
                SwmsTaskDetail::whereIn('swms_id', $swmsIds)->delete();
            }
           
            Swms::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 6. Delete Leave related data
            LeaveRequest::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 7. Delete Attendance related data
            $employeeIds = EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)
                ->where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($employeeIds->count() > 0) {
                $employeeAttendanceIds = EmployeeAttendance::whereIn('employee_id', $employeeIds)->pluck('id');

                if ($employeeAttendanceIds->count() > 0) {
                    EmployeeBreak::whereIn('emp_attendance_id', $employeeAttendanceIds)->delete();
                    EmployeeAttendance::whereIn('id', $employeeAttendanceIds)->delete();
                }
            }
 
            // 7.5. Delete Payroll and Compensation related data
            Payroll::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();

            Salary::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();

            Fine::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();

            // 7.6. Delete Overtime related data
            Overtime::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();

            // 8. Delete Roster related data
            RosterAssign::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
           
            RosterTemplate::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 9. Delete Project related data
            $projectIds = Project::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($projectIds->count() > 0) {
                ProjectSite::whereIn('project_id', $projectIds)->delete();
                ProjectMeta::whereIn('project_id', $projectIds)->delete();
            }
           
            Project::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 10. Delete Site related data
            Sites::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 11. Delete Company/Client related data
            $companyIds = Company::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($companyIds->count() > 0) {
                CompanyContactPerson::whereIn('company_id', $companyIds)->delete();
            }
           
            Company::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 12. Delete Employee related data
            if ($employeeIds->count() > 0) {
                EmpDocuments::whereIn('emp_id', $employeeIds)->delete();
                EmpEmergencyContacts::whereIn('emp_id', $employeeIds)->delete();
                EmpPersonalDetails::whereIn('emp_id', $employeeIds)->delete();
                EmpAccess::whereIn('emp_id', $employeeIds)->delete();
                EmpTeamsMember::whereIn('emp_id', $employeeIds)->delete();
               
                EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->whereIn('id', $employeeIds)->delete();
            }
 
            // 13. Delete Team related data
            $teamIds = EmpTeam::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($teamIds->count() > 0) {
                EmpTeamsMember::whereIn('team_id', $teamIds)->delete();
                EmpTeam::whereIn('id', $teamIds)->delete();
                EmpTeam::create([
                    'title' => 'Default Team',
                    'supervisor' => null, // Will be updated later when employees are created
                    'description' => 'Default team created automatically during role setup',
                    'customer_id' => $userId,
                    'workspace_id' => $workspaceId,
                    'created_by' => $userId,
                    'del' => '0',
                ]);
            }
 
            // 14. Delete Settings and Configuration data
            Adminsettings::where('customer_id', $userId)
                ->where('workspace', $workspaceId)
                ->delete();
 
            // 15. Delete Helpdesk Tickets
            HelpdeskTicket::where('user_id', $userId)
                ->where('workspace', $workspaceId)
                ->delete();
 
            // 16. Delete Safety Data Sheets
            SafetyDataSheet::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 17. Delete Funds
            Fund::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 18. Delete Leave Packages
            LeavePackage::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 19. Delete Leave Types
            LeaveType::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 20. Delete Public Holidays
            PublicHoliday::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 21. Delete Required Documents
            $requiredDocumentIds = RequiredDocument::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($requiredDocumentIds->count() > 0) {
                RequiredDocumentField::whereIn('doc_id', $requiredDocumentIds)->delete();
            }
           
            RequiredDocument::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 22. Delete Employee Types, Permits, Worker Types, Work Experience
            EmpType::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            EmpPermit::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            EmpWorkerType::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            EmpWorkExperience::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
 
            // 24. Delete Link Management
            LinkManagement::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 25. Delete WHS Items
            WhsItem::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 26. Delete Hazard Risks
            HazardRisk::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 27. Delete Incident related settings
            IncidentInjuryClassification::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            IncidentInjuryType::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            IncidentReportQuestion::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            IncidentRiskCategory::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            IncidentNotifiableClassification::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 28. Delete SWMS related settings
            HazardRisk::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
            Training::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            SwmsQuestions::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            SwmsSafetyPlanningQuestion::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            SwmsGeneralNote::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            SwmsProtectionTool::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 29. Delete Inspection Plan Settings
            InspectionPlanTable::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 30. Delete WHS Report Settings
            WhsItem::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 31. Delete WHSQ Report related data
            $whsqReportIds = WhsqReport::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->pluck('id');
           
            if ($whsqReportIds->count() > 0) {
                // Delete WHSQ content options and dates
                $whsqContentMetaIds = WHSQETableOfContentMeta::whereIn('whsq_report_id', $whsqReportIds)
                    ->pluck('id');
                
                if ($whsqContentMetaIds->count() > 0) {
                    WHSQEContentOption::whereIn('content_meta_id', $whsqContentMetaIds)->delete();
                    WHSQEContentDate::whereIn('content_meta_id', $whsqContentMetaIds)->delete();
                }
                
                // Delete WHSQ content meta
                WHSQETableOfContentMeta::whereIn('whsq_report_id', $whsqReportIds)->delete();
                
                // Delete WHSQ customer selected settings
                WHSQECustomerSelectedSettings::whereIn('whsq_report_id', $whsqReportIds)->delete();
                
                // Delete WHSQ signatures
                WhsqSignature::whereIn('whsq_report_id', $whsqReportIds)->delete();
                
                // Delete WHSQ reports
                WhsqReport::whereIn('id', $whsqReportIds)->delete();
            }
            
            // Delete WHSQ Table of Content Structure
            WHSQE_TableOfContentGrandChild::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
                
            WHSQE_TableOfContentChild::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
                
            WHSQE_TableOfContent::where('customer_id', $userId)
                ->where('workspace_id', $workspaceId)
                ->delete();
 
            // 32. Delete uploaded images and files
            $this->deleteUploadedFiles($userId, $workspaceId);
 
            // 33. Reset user demo_data flag
            $user->demo_data = 0;
            $user->save();
 
            DB::commit();
 
            return $this->success('Demo data deleted successfully');
 
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('Error deleting demo data: ' . $e->getMessage());
        }
    }

    /**
     * Get permissions for a specific user
     * Uses reflection to call private methods from AdminAuthTrait
     */
    private function getUserPermissionsForUser($user)
    {        

        $permissions = $this->getUserPermissions($user);
            
        return $permissions;
    }

    private function getUserSettingsForUser($user)
    {
        
        $settings = [];
        $adminSettings = [];
        
        // Get admin bank transfer details (always included)
        $adminSettings = Adminsettings::where('customer_id', $this->getSuperAdminId())
            ->where('key', 'bank_transfer_details')
            ->get();
        
        // Check if plan is expired
        $settings = Adminsettings::where('customer_id', $user->id)
            ->where('workspace', $user->current_workspace_id)
            ->get();
        
        // Merge admin bank details with other settings (bank details always included)
        if ($adminSettings->isNotEmpty()) {
            $settings = collect($settings)->merge($adminSettings);
        }
        
        return $settings->toArray();
    }
 
    private function deleteUploadedFiles($userId, $workspaceId)
    {
        // Delete uploaded images and files from storage
        $storagePath = storage_path('app/public');

        // Common demo file patterns to delete
        $patterns = [
            'demo_*',
            'demo-*',
            'assets/img/demo_*',
            'assets/img/demo-*',
            'uploads/demo_*',
            'uploads/demo-*'
        ];

        foreach ($patterns as $pattern) {
            $files = glob($storagePath . '/' . $pattern);
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
        }

        // Also delete any files with user/workspace specific patterns
        $userWorkspacePatterns = [
            "user_{$userId}_*",
            "workspace_{$workspaceId}_*",
            "demo_user_{$userId}_*",
            "demo_workspace_{$workspaceId}_*"
        ];

        foreach ($userWorkspacePatterns as $pattern) {
            $files = glob($storagePath . '/' . $pattern);
            foreach ($files as $file) {
                if (is_file($file)) {
                    unlink($file);
                }
            }
        }
    }

    private function createDemoDefects($customerId, $workspaceId)
    {
        $faker = Faker::create();

        // Get existing projects, sites, and employees in a single query to reduce DB calls
        $projects = Project::where('customer_id', $customerId)
                            ->where('workspace_id', $workspaceId)
                            ->pluck('id');  // Use pluck to retrieve only the ids
        
        $sites = Sites::where('customer_id', $customerId)
                    ->where('workspace_id', $workspaceId)
                    ->where('active', 1)
                    ->where('del', 0)
                    ->pluck('id');  // Use pluck for ids only

        $employees = EmpCompanyDetails::where('customer_id', $customerId)
                                    ->where('workspace_id', $workspaceId)
                                    ->whereNull('link_key')
                                    ->pluck('id');  // Pluck ids directly

        $subcontractors = LinkManagement::where('customer_id', $customerId)
                                        ->where('workspace_id', $workspaceId)
                                        ->pluck('id');  // Pluck ids only

        // Skip if no prerequisite data
        if ($projects->isEmpty() || $sites->isEmpty() || $employees->isEmpty()) {
            return;
        }

        $defects = [];
        $defectData = [
            ['priority' => 'high', 'status' => config('constants.defect_status.open.key'), 'assignment_type' => 'internal_employee', 'due_date' => now()->addDays(7)],
            ['priority' => 'critical', 'status' => config('constants.defect_status.in_progress.key'), 'assignment_type' => 'subcontractor', 'due_date' => now()->addDays(3)],
            ['priority' => 'medium', 'status' => config('constants.defect_status.submitted.key'), 'assignment_type' => 'internal_employee', 'due_date' => now()->addDays(14)],
            ['priority' => 'low', 'status' => config('constants.defect_status.completed.key'), 'assignment_type' => 'internal_employee', 'due_date' => now()->addDays(21)],
        ];

        $defectTitles = [
            'critical' => 'Structural integrity failure identified',
            'high' => 'Safety hazard reported on active site',
            'medium' => 'Quality issue requires follow-up inspection',
            'low' => 'Minor finishing touch-up needed',
        ];

        // Loop over the defect data and create defects
        foreach ($defectData as $index => $data) {
            $assignedEmpId = $employees->random();
            $projectId = $projects->random();
            $siteId = $sites->random();
            $subcontractorId = $subcontractors->isNotEmpty() && $data['assignment_type'] === 'subcontractor' 
                                ? $subcontractors->random() 
                                : null;
            
            // Create defect
            $defect = Defect::create([
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
                'created_by' => $customerId,
                'created_by_type' => 'customer',
                'status' => $data['status'],
                'title' => $defectTitles[$data['priority']] ?? 'Site defect reported',
                'description' => $faker->sentence(7),
                'priority' => $data['priority'],
                'assignment_type' => $data['assignment_type'],
                'assigned_emp_id' => $assignedEmpId,
                'subcontractor_id' => $subcontractorId,
                'project_id' => $projectId,
                'site_id' => $siteId,
                'due_date' => $data['due_date']->format('Y-m-d'),
            ]);

            $defects[] = $defect;

            // Create defect history
            DefectHistory::create([
                'defect_id' => $defect->id,
                'action' => 'created',
                'description' => 'Defect created via demo data',
                'changed_by' => $customerId,
                'changed_by_type' => 'customer',
                'old_value' => null,
                'new_value' => $defect->toArray(),
                'customer_id' => $customerId,
                'workspace_id' => $workspaceId,
            ]);

            // Add demo images with a 50% chance for each defect
            if (rand(0, 1)) {
                for ($i = 0; $i < rand(1, 3); $i++) {
                    DefectImage::create([
                        'defect_id' => $defect->id,
                        'uploaded_by' => $customerId,
                        'image' => 'assets/img/default.png',
                        'type' => 'created_by_customer',
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                    ]);
                }
            }
        }
    }

    private function createDemoSiteDiaries($customerId, $workspaceId)
    {
        $faker = Faker::create();

        // Get existing sites and employees
        $sites = Sites::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->where('active', 1)->where('del', 0)->get();
        $employees = EmpCompanyDetails::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->get();

        if ($sites->isEmpty() || $employees->isEmpty()) {
            return; // Skip if no prerequisite data
        }

        $siteDiaries = [];
        $weatherConditions = ['Sunny', 'Cloudy', 'Rainy', 'Windy', 'Overcast', 'Clear'];
        $equipmentList = [
            ['equipment_name' => 'Concrete Mixer', 'quantity' => rand(1, 3)],
            ['equipment_name' => 'Excavator', 'quantity' => rand(1, 2)],
            ['equipment_name' => 'Dump Truck', 'quantity' => rand(2, 5)],
            ['equipment_name' => 'Generator', 'quantity' => rand(1, 2)],
            ['equipment_name' => 'Welding Machine', 'quantity' => rand(1, 3)],
            ['equipment_name' => 'Scaffold Tower', 'quantity' => rand(1, 4)],
            ['equipment_name' => 'Power Tools Set', 'quantity' => rand(3, 8)],
            ['equipment_name' => 'Safety Equipment Kit', 'quantity' => rand(5, 15)],
        ];

        $taskList = [
            'Foundation excavation completed',
            'Concrete pouring for ground floor',
            'Steel reinforcement installation',
            'Electrical wiring setup',
            'Plumbing installation',
            'Wall framing construction',
            'Roof installation',
            'Interior painting',
            'Flooring installation',
            'Final inspection and cleanup',
        ];

        $workLogs = [
            'Crew completed perimeter footing pour in the morning and set expansion joints before noon. Afternoon shift focused on stripping formwork and preparing reinforcement cages for the next pour.',
            'Electrical subcontractors rough-wired the level one switchboards while carpenters installed additional bracing. Site supervisor coordinated deliveries and updated staging plan with logistics.',
            'Plumbing team pressure-tested the fire service line and logged successful inspection. Drywall installers closed remaining riser shafts and patched penetrations identified in yesterday’s walkthrough.',
            'Roofing crew installed insulation blanket across grid sections A5 to A8 and secured flashing at parapets. Safety officer conducted toolbox talk on working at heights compliance during first break.',
            'Concrete crew polished lobby slab and applied curing compound, followed by electricians installing light fixtures in the communal corridor. Site remained clear of incidents with all permits signed off.'
        ];

        $diaryNotes = [
            'Delivery of precast panels rescheduled to tomorrow due to transport delay.',
            'Inspector requested updated lift shaft barricades before next site visit.',
            'Two apprentices assigned to assist mechanical team for remainder of week.',
            'Weather change expected overnight; tarp coverings double-checked for security.',
            'QA checklist flagged minor paint touch-ups in stairwell level three.'
        ];

        $diarySummaries = [
            'Progress tracking on schedule with critical path tasks meeting forecast.',
            'Key milestones achieved today with follow-up actions documented for trades.',
            'Site operating smoothly; outstanding items logged for morning coordination.',
            'Productive day with no safety incidents and clear visibility on next steps.',
            'Overall performance positive; minor corrective tasks assigned and monitored.'
        ];

        // Create site diaries for the last 5 working days for each site
        foreach ($sites as $site) {
            for ($i = 0; $i < 5; $i++) {
                $diaryDate = now()->subDays($i)->toDateString();

                // Skip weekends
                if (now()->subDays($i)->isWeekend()) {
                    continue;
                }

                // Check if diary already exists for this site and date
                $existingDiary = \App\Models\SiteDiary::where('site_id', $site->id)
                    ->whereDate('diary_date', $diaryDate)
                    ->where('customer_id', $customerId)
                    ->where('workspace_id', $workspaceId)
                    ->where('del', '0')
                    ->first();

                if ($existingDiary) {
                    continue; // Skip if diary already exists
                }

                $siteDiary = \App\Models\SiteDiary::create([
                    'site_id' => $site->id,
                    'diary_date' => $diaryDate,
                    'weather' => $weatherConditions[array_rand($weatherConditions)],
                    'work_log' => $workLogs[array_rand($workLogs)],
                    'notes' => $diaryNotes[array_rand($diaryNotes)],
                    'summary' => $diarySummaries[array_rand($diarySummaries)],
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                    'created_by_type' => 'customer',
                    'created_by' => $customerId,
                ]);

                $siteDiaries[] = $siteDiary;

                // Add equipment (2-4 random pieces per diary)
                $selectedEquipment = array_rand($equipmentList, rand(2, 4));
                if (!is_array($selectedEquipment)) {
                    $selectedEquipment = [$selectedEquipment];
                }

                foreach ($selectedEquipment as $equipmentIndex) {
                    \App\Models\SiteDiaryEquipment::create([
                        'site_diary_id' => $siteDiary->id,
                        'equipment_name' => $equipmentList[$equipmentIndex]['equipment_name'],
                        'quantity' => $equipmentList[$equipmentIndex]['quantity'],
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                    ]);
                }

                // Add tasks (3-6 random tasks per diary)
                $selectedTasks = array_rand($taskList, rand(3, 6));
                if (!is_array($selectedTasks)) {
                    $selectedTasks = [$selectedTasks];
                }

                foreach ($selectedTasks as $taskIndex) {
                    \App\Models\SiteDiaryTask::create([
                        'site_diary_id' => $siteDiary->id,
                        'title' => $taskList[$taskIndex],
                        'is_completed' => (bool) rand(0, 1),
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                    ]);
                }

                // Add demo images (using placeholder paths)
                for ($imgCount = 0; $imgCount < rand(1, 3); $imgCount++) {
                    \App\Models\SiteDiaryImage::create([
                        'site_diary_id' => $siteDiary->id,
                        'image' => 'assets/img/default.png',
                        'customer_id' => $customerId,
                        'workspace_id' => $workspaceId,
                    ]);
                }

                // Create log entry for diary creation
                \App\Models\SiteDiaryLog::create([
                    'site_diary_id' => $siteDiary->id,
                    'loggable_type' => \App\Models\SiteDiary::class,
                    'loggable_id' => $siteDiary->id,
                    'user_id' => $customerId,
                    'emp_id' => null,
                    'action_type' => 'create',
                    'old_values' => null,
                    'new_values' => $siteDiary->toArray(),
                    'notes' => 'Site diary created via demo data',
                    'created_by_type' => 'customer',
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                ]);
            }
        }

        return $siteDiaries;
    }

    private function createDemoAssets($customerId, $workspaceId)
    {
        $faker = Faker::create();
        $sites = Sites::where('customer_id', $customerId)->where('workspace_id', $workspaceId)->where('active', 1)->where('del', 0)->get();
        // Asset categories (integers as per database schema)
        $categories = [
            1 => 'IT Equipment',
            2 => 'Vehicles',
            3 => 'Machinery',
            4 => 'Tools',
            5 => 'Furniture',
            6 => 'Safety Equipment',
            7 => 'Office Equipment',
            8 => 'Construction Equipment'
        ];

        // Asset status values (integers as per controller)
        $statuses = [
            1 => 'Available',
            2 => 'In Use',
            3 => 'Under Maintenance',
            4 => 'Retired',
            5 => 'Lost',
            6 => 'Damaged'
        ];

        // Sample vendors
        $vendors = [
            'TechCorp Solutions',
            'Industrial Supplies Inc',
            'Construction Equipment Ltd',
            'Office Furniture Co',
            'Safety First Equipment',
            'Vehicle Masters',
            'Tool Warehouse',
            'Digital Devices Inc'
        ];

        // Sample locations
        $locations = [
            'Main Office',
            'Warehouse A',
            'Construction Site 1',
            'Workshop',
            'Storage Room',
            'Field Office',
            'Server Room',
            'Parking Lot'
        ];

        // Sample asset templates with realistic data
        $assetTemplates = [
            // IT Equipment
            [
                'category' => 1,
                'assets' => [
                    ['name' => 'Dell Latitude Laptop', 'model' => 'Latitude 5420', 'base_price' => 1200],
                    ['name' => 'HP Desktop Computer', 'model' => 'EliteDesk 800', 'base_price' => 800],
                ]
            ],
            // Vehicles
            [
                'category' => 2,
                'assets' => [
                    ['name' => 'Ford Transit Van', 'model' => 'Transit 350', 'base_price' => 35000],
                    ['name' => 'Toyota Hilux Truck', 'model' => 'SR5', 'base_price' => 45000],
                ]
            ],
            // Machinery
            [
                'category' => 3,
                'assets' => [
                    ['name' => 'Caterpillar Excavator', 'model' => '320D', 'base_price' => 150000],
                    ['name' => 'Bobcat Skid Steer', 'model' => 'S650', 'base_price' => 75000],
                ]
            ],
            // Tools
            [
                'category' => 4,
                'assets' => [
                    ['name' => 'Bosch Power Drill Set', 'model' => 'Professional Series', 'base_price' => 300],
                    ['name' => 'Milwaukee Angle Grinder', 'model' => 'AG45', 'base_price' => 150],
                ]
            ],
            // Furniture
            [
                'category' => 5,
                'assets' => [
                    ['name' => 'Executive Office Chair', 'model' => 'Ergonomic Pro', 'base_price' => 400],
                    ['name' => 'Conference Table', 'model' => 'Boardroom 8-seater', 'base_price' => 1200],
                ]
            ],
            // Safety Equipment
            [
                'category' => 6,
                'assets' => [
                    ['name' => 'Hard Hat', 'model' => 'Type 1 Safety Helmet', 'base_price' => 25],
                    ['name' => 'Safety Harness', 'model' => 'Full Body Fall Arrest', 'base_price' => 150],
                ]
            ],
        ];

        $assets = [];
        $createdAssets = [];

        // Create assets from each category
        foreach ($assetTemplates as $categoryData) {
            $categoryId = $categoryData['category'];
            $categoryAssets = $categoryData['assets'];

            // Create 2-4 assets per category
            $numAssets = 2;

            for ($i = 0; $i < $numAssets; $i++) {
                $template = $categoryAssets[array_rand($categoryAssets)];

                // Generate unique serial number
                $serialNumber = strtoupper(substr($template['name'], 0, 3)) . '-' . rand(10000, 99999) . '-' . chr(rand(65, 90)) . chr(rand(65, 90));

                // Check if serial number already exists
                $existingAsset = Asset::where('serial_number', $serialNumber)
                    ->where('customer_id', $customerId)
                    ->first();

                if ($existingAsset) {
                    // Generate a new serial number if it exists
                    $serialNumber = strtoupper(substr($template['name'], 0, 3)) . '-' . rand(10000, 99999) . '-' . chr(rand(65, 90)) . chr(rand(65, 90)) . rand(10, 99);
                }

                // Random purchase date within last 3 years
                $purchaseDate = now()->subDays(rand(30, 1095))->toDateString();

                // Calculate warranty expiry (1-5 years from purchase)
                $warrantyYears = rand(1, 5);
                $warrantyExpiry = date('Y-m-d', strtotime($purchaseDate . " + {$warrantyYears} years"));

                // Random status with weighted distribution (most assets should be available or in use)
                $statusRand = rand(1, 6);


                // Random price variation (±20%)
                $priceVariation = rand(-20, 20) / 100;
                $finalPrice = $template['base_price'] * (1 + $priceVariation);

                $asset = Asset::create([
                    'asset_name' => $template['name'],
                    'category' => $categoryId,
                    'site_id' => $sites->random()->id,
                    'model' => $template['model'],
                    'serial_number' => $serialNumber,
                    'purchase_date' => $purchaseDate,
                    'purchase_price' => round($finalPrice, 2),
                    'vendor' => $vendors[array_rand($vendors)],
                    'warranty_expiry' => $warrantyExpiry,
                    'location' => $locations[array_rand($locations)],
                    'assigned_to' => $faker->name(), 
                    'status' => $statusRand,
                    'description' => $faker->sentence(rand(5, 15)),
                    'customer_id' => $customerId,
                    'workspace_id' => $workspaceId,
                ]);

                $createdAssets[] = $asset;
            }
        }

        return $createdAssets;
    }

    /**
     * Create demo overtime records for two employees
     */
    private function createDemoOvertime($customerId, $workspaceId)
    {
        // Get two random employees (excluding linked employees)
        $employees = EmpCompanyDetails::where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->whereNull('link_key')
            ->inRandomOrder()
            ->where('invited', 0)
            ->limit(2)
            ->get();

        if ($employees->count() < 2) {
            return; // Skip if not enough employees
        }

        // Get a random site
        $site = Sites::where('customer_id', $customerId)
            ->where('workspace_id', $workspaceId)
            ->inRandomOrder()
            ->first();

        if (!$site) {
            return; // Skip if no site available
        }

        $overtimeRecords = [];

        // Create overtime for first employee
        $employee1 = $employees[0];
        $overtimeDate1 = now()->subDays(rand(1, 7))->format('Y-m-d');
        $checkIn1 = Carbon::parse($overtimeDate1)->setTime(17, 0, 0); // 5:00 PM
        $checkOut1 = Carbon::parse($overtimeDate1)->setTime(20, 30, 0); // 8:30 PM
        $workingHours1 = $checkIn1->diffInMinutes($checkOut1) / 60; // Convert to hours

        $overtime1 = Overtime::create([
            'employee_id' => $employee1->id,
            'site_id' => $site->id,
            'check_in' => $checkIn1->format('Y-m-d H:i:s'),
            'check_out' => $checkOut1->format('Y-m-d H:i:s'),
            'date' => $overtimeDate1,
            'working_hours' => round($workingHours1, 2),
            'description' => 'Demo overtime work - Extended hours for project completion',
            'status' => config('constants.overtime_status.approved'),
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
        ]);

        $overtimeRecords[] = $overtime1;

        // Create overtime for second employee
        $employee2 = $employees[1];
        $overtimeDate2 = now()->subDays(rand(1, 7))->format('Y-m-d');
        $checkIn2 = Carbon::parse($overtimeDate2)->setTime(18, 0, 0); // 6:00 PM
        $checkOut2 = Carbon::parse($overtimeDate2)->setTime(22, 0, 0); // 10:00 PM
        $workingHours2 = $checkIn2->diffInMinutes($checkOut2) / 60; // Convert to hours

        $overtime2 = Overtime::create([
            'employee_id' => $employee2->id,
            'site_id' => $site->id,
            'check_in' => $checkIn2->format('Y-m-d H:i:s'),
            'check_out' => $checkOut2->format('Y-m-d H:i:s'),
            'date' => $overtimeDate2,
            'working_hours' => round($workingHours2, 2),
            'description' => 'Demo overtime work - Weekend shift coverage',
            'status' => config('constants.overtime_status.pending'),
            'customer_id' => $customerId,
            'workspace_id' => $workspaceId,
        ]);

        $overtimeRecords[] = $overtime2;

        return $overtimeRecords;
    }

    private function getSuperAdminId()
    {
        $superAdmin = User::where('user_type', config('constants.user_types.admin'))->first();
        return $superAdmin->id;
    }
}
