<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Models\Fund;
use App\Models\Role;
use App\Models\Tier;
use App\Models\User;
use App\Models\EmpTeam;
use App\Models\EmpType;
use App\Models\EmpAccess;
use App\Models\EmpPermit;
use App\Models\FundsMeta;
use App\General\MetaClass;
use App\Models\EmpDocuments;
use App\Models\RosterAssign;
use Illuminate\Http\Request;
use App\Models\EmpWorkerType;
use App\Models\RosterHistory;
use App\Models\Adminsettings;
use App\Models\EmpTeamsMember;
use App\Models\LinkManagement;
use App\Models\RosterTemplate;
use Illuminate\Validation\Rule;
use App\Models\RequiredDocument;
use App\Models\EmpCompanyDetails;
use App\Models\EmpWorkExperience;
use App\Models\EmpPersonalDetails;
use App\Models\PorfileSubmittedLog;
use App\Traits\RosterTemplateTrait;
use App\Models\EmpEmergencyContacts;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Intervention\Image\Facades\Image;
use App\Models\RequiredExternalDocument;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\EmpTeamController;


class ExternalEmployeeOnboardingController extends Controller
{
    use RosterTemplateTrait;
    public function externalEmployeeOnboardingEdit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'emp_id' => 'required'
        ], [
            'emp_id.required' => 'Employee ID is required.'
        ]);

        if ($validator->fails()) {

            $error = $validator->errors()->first();

            return response()->json([
                'message' => $error

            ], 422);
        } else {

            $validatedData =  $validator->validated();
            $userTable = $this->getUserTable();
            $auth_id = 0;
            $workspace_id = 0;
            if ($userTable === "customer") {
                $auth_id = Auth::user()->id;
                $workspace_id = Auth::user()->current_workspace_id;
                $authPersonalDetails = User::where('id', Auth::user()->id)->first();
            }
            if ($userTable === "emp") {
                $auth_id = auth()->user()->customer_id;
                $workspace_id = auth()->user()->workspace_id;
                $authPersonalDetails = EmpPersonalDetails::where('emp_id', Auth::user()->id)->first();
            }

            $emp_company_details =  EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->with(['empPersonalDetails', 'empEmergencyContacts', 'empAccess', 'empworkExperience', 'workerType', 'empTeamsMembers'])->where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->where('id', $validatedData['emp_id'])->first();
            if ($emp_company_details) unset($emp_company_details['password']);

            $data['emp_company_details'] = $emp_company_details;

            $emp_permits =  EmpPermit::where('del', '0')->where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->select('id', 'title')->get();

            $data['emp_permits'] = $emp_permits;

            $emp_types =  EmpType::where('del', '0')->where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->select('id', 'title')->get();

            $data['emp_types'] = $emp_types;

            $pkg_tiers =  Tier::where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->select('id', 'title')->get();

            $data['pkg_tiers'] = $pkg_tiers;

            $roles = Role::where('del', '0')->get();

            $data['emp_roles'] = $roles;

            $emp_work_experiences =  EmpWorkExperience::where('del', '0')->where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->select('id', 'title')->get();

            $data['emp_work_experiences'] = $emp_work_experiences;

            $emp_worker_types =  EmpWorkerType::where('del', '0')->where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->get();

            $data['emp_worker_types'] = $emp_worker_types;


            $funds = Fund::where('del', '0')->where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->get();
            $funds_meta = FundsMeta::where('emp_id', $validatedData['emp_id'])->with('fund')->get();

            $c = 0;

            foreach ($funds as $f) {

                foreach ($funds_meta as $fm) {
                    if ($fm->fund_id == $f->id) {
                        $funds[$c]['usi_number'] = $fm->usi_number;
                    }
                }

                $c++;
            }

            $data['funds'] = $funds;
            $data['funds_meta'] = $funds_meta;

            $user_meta =  DB::table('user_meta')->where('emp_id', $validatedData['emp_id'])->get();

            $account_title = MetaClass::getOptionValue('account_title', $user_meta);
            $account_number = MetaClass::getOptionValue('account_number', $user_meta);
            $bank_name = MetaClass::getOptionValue('bank_name', $user_meta);

            $data['meta']['account_title'] = $account_title;
            $data['meta']['account_number'] = $account_number;
            $data['meta']['bank_name'] = $bank_name;


            $data['medicalAttachFiles'] = DB::table('medical_attach_files')->where('emp_id', $validatedData['emp_id'])->get();




            $data['required_documents'] = RequiredDocument::with('requiredDocumentField')->where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->where('del', '0');
            $isInternal = ($emp_company_details->user_type === '0' || $emp_company_details->user_type === 0); // 0 = Internal, 1 = External
            $isExternal = ($emp_company_details->user_type === '1' || $emp_company_details->user_type === 1); // 1 = External
            
            if ($isInternal) {
                // For internal employees, return documents with for_who = 'internal' or 'both'
                $data['required_documents'] = $data['required_documents']->whereIn('for_who', ['internal', 'both']);
            } elseif ($isExternal) {
                // For external employees, return documents with for_who = 'external' or 'both'
                $data['required_documents'] = $data['required_documents']->whereIn('for_who', ['external', 'both']);
            } else {
                // If no conditions match (unknown user_type), return only 'both' documents
                $data['required_documents'] = $data['required_documents']->where('for_who', 'both');
            }
            $data['required_documents'] = $data['required_documents']->get();
            $data['emp_documents'] = EmpDocuments::where('emp_id', $validatedData['emp_id'])->where('del', '0')->get();
            $data['emp_emergency_contacts']  = EmpEmergencyContacts::where('emp_id', $validatedData['emp_id'])->get();
            $data['teams'] = EmpTeam::where('customer_id', $auth_id)->where('workspace_id', $workspace_id)->get();
            $data['employee_team_members'] = isset($emp_company_details->empTeamsMembers) ? $emp_company_details->empTeamsMembers : [];

            return $this->success($data, 'External employee Get successfully');
        }
    }

    public function externalEmployeeOnboardingsStore(Request $request)
    {
        // Start database transaction
        DB::beginTransaction();
        
        try {
            if ($request->emp_id == 0) {
                $validator = Validator::make($request->all(), [
                    'image' => 'required|',
                ], [
                    'image.required' => 'The Profile Image field is required.',
                ]);

                if ($validator->fails()) {
                    $error = $validator->errors()->first();
                    return $this->error($error, 422);
                }
            }


            $validator = Validator::make($request->all(), [
            'emp_id' => 'required',
            'team_id' => 'nullable',
            'first_name' => 'required',
            'middle_name' => 'nullable',
            'last_name' => 'required',
            'image' => 'nullable|mimes:jpeg,png,jpg,gif|max:1024',
            'temporary_student_visa' => 'nullable|mimes:jpeg,png,jpg,gif|max:1024',
            'signature' => 'nullable|mimes:jpeg,png,jpg,gif|max:1024',
            'medical_attach_files.*' => 'nullable|mimes:jpeg,png,jpg,gif|max:1024',
            'employee_email' => ['required', 'email', Rule::unique('emp_company_details', 'employee_email')->ignore($request->emp_id, 'id'), Rule::unique('users', 'email')->ignore($request->emp_id, 'id'),],
            'date_of_birth' => 'required|date|before:' . Carbon::now()->subYears(15)->format('Y-m-d'),
            'mobile' => 'required|numeric',
            'suburb' => 'required|regex:/^[a-zA-Z\s]*$/',
            'state' => 'required|regex:/^[a-zA-Z\s]*$/',
            'streat_address' => 'required',
            'job_title' => 'required',
            'employer_name' => 'required',
            'worker_type' => 'required',
            'trade_qualified' => 'required',
            'trade_qualified_year' => 'required_if:trade_qualified,=,1',
            'trade_licensed' => 'required',
            'trade_licensed_year' => 'required_if:trade_licensed,=,1',
            'work_experience' => 'required',
            'year_commenced' => 'required',
            'legally_australia' => 'required',
            'citizenship_status' => 'required',

            'classified_high_risk' => 'nullable',
            'contact_name_first' => 'required',
            'contact_relation_first' => 'required',
            'contact_phone_first' => 'required',

            'allergies' => 'nullable',
            'details_allergies' => 'nullable',
            'previous_injuries' => 'nullable',
            'details_previous_injuries' => 'nullable',
            'medical_condition' => 'nullable'

        ], [
            'image.mimes' => 'The image must be a file of type: jpeg, png, jpg, gif.',
            'image.max' => 'The image may not be greater than 1MB.',
            'suburb.regex' => 'The suburb field must contain only alphabetic characters.',
            'state.regex' => 'The state field contain only alphabetic characters.',
            'date_of_birth.before' => 'You must be at least 15 years old to register.',
            'trade_qualified_year.required_if' => 'The trade qualified year field is required',
            'trade_licensed_year.required_if' => 'The trade licensed year field is required',
            'contact_name_first.required' => 'The contact name field is required',
            'contact_relation_first.required' => 'The contact relation field is required',
            'contact_phone_first.required' => 'The contact phone field is required',
            'bank_name.required' => 'The BSB field is required',
            'account_title.required' => 'The Account Name field is required',
            'bank_name.size' => 'The BSB field must be exactly 6 digits long',
            'employer_name.required' => 'The employer company name field is required',
        ]);

            if ($validator->fails()) {
                $error = $validator->errors()->first();
                return $this->error($error, 422);
            }

            $link_detail = LinkManagement::where('secret_key', $request->key)->first();

            // Validate LinkManagement record exists
            if (!$link_detail) {
                return $this->error('Invalid or expired onboarding link', 422);
            }

            // Validate customer_id exists
            if (!$link_detail->customer_id) {
                return $this->error('Customer information not found for this onboarding link', 422);
            }

            $required_documents = RequiredDocument::with('requiredDocumentField')->where('del', '0')->where('customer_id', $link_detail->customer_id)->where('workspace_id', $link_detail->workspace_id)->where('for_who', '!=', 'internal')->get();
            $count = EmpDocuments::where('emp_id', $request->emp_id)->count();

            $i = 0;

            foreach ($required_documents as $required_document) {
                foreach ($required_document->requiredDocumentField as $required_document_field) {
                    if ($required_document_field->field_required == "1" && !$request->filled('document_array.' . $required_document_field->doc_id . '.' . $required_document_field->id) && !$request->hasFile('document_array.' . $required_document_field->doc_id . '.' . $required_document_field->id)) {
                        if ($count == 0) {
                            return $this->error($required_document_field->field_name . ' field is required', 422);
                        } else {
                            if ($required_document_field->field_type != 'image') {
                                return $this->error($required_document_field->field_name . ' field is required', 422);
                            }
                        }
                    }
                    if ($required_document_field->field_type == "image" && $request->hasFile('document_array.' . $required_document_field->doc_id . '.' . $required_document_field->id)) {
                        $allowedExtensions = ['jpg', 'jpeg', 'png', 'docx', 'pdf'];
                        $document_file = $request->file('document_array.' . $required_document_field->doc_id . '.' . $required_document_field->id);
                        $extension = $document_file->getClientOriginalExtension();
                        $mimeType = $document_file->getMimeType();

                        // Validate extension and MIME type
                        if (!in_array($extension, $allowedExtensions) || !in_array($mimeType, ['image/jpeg', 'image/png', 'application/pdf', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'])) {
                            return $this->error($required_document_field->field_name . 'file must be a file of type: jpg, jpeg, png, docx, pdf.', 422);
                        }
                    }
                }
                $i++;
            }

            $msg  = $this->companyDetailStore($request);
            $this->personalDetailsStore($request);
            $this->documentsStore($request);
            $this->emergencyContactsStore($request);
            $this->accessStore($request);
            $team_ids = explode(',', $request->team_id);
            if ($team_ids) {
                EmpTeamsMember::where([
                    'emp_id' => $request->emp_id,
                ])
                    ->delete();
                foreach ($team_ids as $team_id) {

                    EmpTeamsMember::insert([
                        'team_id' => $team_id,
                        'emp_id' => $request->emp_id,
                        'applied' => 1
                    ]);
                }
            }

            if (str_contains($msg, 'Register')) {

                $this->assignShift($request->key, $request->emp_id);
                $this->sendExternalOnboardingEmail($request->emp_id, $link_detail->customer_id);
            }

            // Commit transaction if everything succeeds
            DB::commit();

            $data['emp_id'] =  $request->emp_id;
            return $this->success($data, $msg);
            
        } catch (\Exception $e) {
            // Rollback transaction on any error
            DB::rollBack();
            Log::error('externalEmployeeOnboardingsStore error: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString(),
                'request' => $request->all()
            ]);
            return $this->error('An error occurred while processing your request. Please try again.', 500);
        }
    }

    public function companyDetailStore($request)
    {
        $validatedData = $request->only([
            'employee_email',
            'job_title',
            'employer_name',
            'worker_type',
            'trade_qualified',
            'trade_qualified_year',
            'trade_licensed',
            'trade_licensed_year',
            'work_experience',
            'year_commenced',
            'citizenship_status',
            'classified_high_risk',
            'allergies',
            'details_allergies',
            'previous_injuries',
            'details_previous_injuries',
            'medical_condition',
            'legally_australia'
        ]);

        if ($request->hasFile('temporary_student_visa')) {
            $temporary_student_visa = $request->file('temporary_student_visa');
            $imageName = time() . '.' . $temporary_student_visa->getClientOriginalExtension();
            $temporary_student_visa->move(public_path('upload/temporary_student_visa'), $imageName);
            $validatedData['temporary_student_visa'] = 'upload/temporary_student_visa/' . $imageName;
        }

        if ($request->hasFile('signature')) {
            $signature = $request->file('signature');
            $imageName = time() . '2.' . $signature->getClientOriginalExtension();
            $signature->move(public_path('upload/signature'), $imageName);
            $validatedData['signature'] = 'upload/signature/' . $imageName;
        }

        $link_detail = LinkManagement::where('secret_key', $request->key)->first();
        if (EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->where('id', $request->emp_id)->count() == 0) {
            $validatedData['status'] = "1";
            $validatedData['credentials'] = "1";
            $validatedData['user_type'] = "1";
            $validatedData['created_by'] = "1";
            $validatedData['access_role'] = "ext-emp";
            $validatedData['tier_id'] = "3";
            $validatedData['force_reset'] = "0";
            $validatedData['two_factor'] = "1";
            $validatedData['compeleted'] = "1";
            $validatedData['approved'] = '1';
            $validatedData['approved_by'] = '1';
            $validatedData['customer_id'] =  $link_detail->customer_id;
            $validatedData['workspace_id'] = $link_detail->workspace_id;

            $request->emp_id =  EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->insertGetId($validatedData);
            $msg = 'Registered Successfully.Verify your email address.';
        } else {
            EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->where('id', $request->emp_id)->update($validatedData);
            $msg = 'Updated Successfully.';
        }

        // Handle medical attached files - Delete existing files first if new files are being uploaded
        if ($request->hasFile('medical_attach_files')) {
            // Get existing medical files from database
            $existingFiles = DB::table('medical_attach_files')
                ->where('emp_id', $request->emp_id)
                ->get();

            // Delete existing files from public folder and database
            foreach ($existingFiles as $existingFile) {
                // Delete file from public folder if it exists
                $filePath = public_path($existingFile->file);
                if (file_exists($filePath)) {
                    unlink($filePath);
                }
            }

            // Delete records from database
            DB::table('medical_attach_files')
                ->where('emp_id', $request->emp_id)
                ->delete();

            // Upload new medical files
            $medical_attach_files = $request->file('medical_attach_files');
            $i = 0;
            foreach ($medical_attach_files as $medical_attach_file) {
                $i++;
                $imageName = time() . $i . '.' . $medical_attach_file->getClientOriginalExtension();
                $medical_attach_file->move(public_path('upload/medical_attach_files'), $imageName);
                DB::table('medical_attach_files')->insert([
                    'emp_id' => $request->emp_id,
                    'file' => 'upload/medical_attach_files/' . $imageName
                ]);
            }
        }

        return $msg;
    }

    public function personalDetailsStore($request)
    {
        $validatedData = $request->only([
            'emp_id',
            'first_name',
            'middle_name',
            'last_name',
            'date_of_birth',
            'mobile',
            'suburb',
            'state',
            'streat_address'
        ]);

        if ($request->hasFile('image')) {

            $image = $request->file('image');
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('upload/images'), $imageName);
            $validatedData['image'] = 'upload/images/' . $imageName;
        }

        $validatedData['emp_id'] = $request->emp_id;
        if (EmpPersonalDetails::where('emp_id', $request->emp_id)->count() == 0) {
            $validatedData['created_by']   =  '0';
            EmpPersonalDetails::insertGetId($validatedData);
        } else {
            unset($validatedData['emp_id']);
            EmpPersonalDetails::where('emp_id', $request->emp_id)->update($validatedData);
        }
        return 0;
    }

    public function documentsStore($request)
    {
        $link_detail = LinkManagement::where('secret_key', $request->key)->first();

        $required_documents = RequiredDocument::with('requiredDocumentField')->where('del', '0')->where('customer_id', $link_detail->customer_id)->where('workspace_id', $link_detail->workspace_id)->where('for_who', '!=', '0')->get();
        $count = EmpDocuments::where('emp_id', $request->emp_id)->count();

        $i = 0;

        foreach ($required_documents as $required_document) {
            foreach ($required_document->requiredDocumentField as $required_document_field) {

                $EmpDocumentsData = [
                    'emp_id' => $request->emp_id,
                    'required_document' => $required_document_field->doc_id,
                    'required_document_field' =>  $required_document_field->id,
                ];
                if ($required_document_field->field_type == "image" && $request->hasFile('document_array.' . $required_document_field->doc_id . '.' . $required_document_field->id)) {
                    $document_file = $request->file('document_array.' . $required_document_field->doc_id . '.' . $required_document_field->id);
                    $documentName = $i . time() . '.' . $document_file->getClientOriginalExtension();
                    $document_file->move(public_path('upload/documents'), $documentName);
                    $EmpDocumentsData['value'] = 'upload/documents/' . $documentName;
                    EmpDocuments::where(['emp_id' => $request->emp_id, 'required_document' => $required_document_field->doc_id, 'required_document_field' => $required_document_field->id])->delete();
                    EmpDocuments::insert($EmpDocumentsData);
                }

                if ($required_document_field->field_type != "image") {
                    if (isset($request->document_array[$required_document_field->doc_id][$required_document_field->id])) {
                        $EmpDocumentsData['value'] =  $request->document_array[$required_document_field->doc_id][$required_document_field->id];
                        EmpDocuments::where(['emp_id' => $request->emp_id, 'required_document' => $required_document_field->doc_id, 'required_document_field' => $required_document_field->id])->delete();
                        EmpDocuments::insert($EmpDocumentsData);
                    }
                }
            }

            $i++;
        }


        return 0;
    }

    public function emergencyContactsStore($request)
    {
        EmpEmergencyContacts::where('emp_id', $request->emp_id)->delete();

        EmpEmergencyContacts::insert([
            'emp_id' => $request->emp_id,
            'name' => $request->contact_name_first,
            'relation' => $request->contact_relation_first,
            'phone' => $request->contact_phone_first,
            'created_by' => '0',
        ]);

        return 0;
    }

    public function accessStore(Request $request)
    {
        $validatedData = [
            'emp_id' => $request->emp_id,
            'web_app' => '0',
            'mobile_app' => '1',
            'attendance' => '1',
            'timesheet_reminders' => '1',
            'email' => '1',
            'timesheet' => '1'
        ];

        EmpAccess::where('emp_id', $request->emp_id)->delete();
        EmpAccess::insertGetId($validatedData);
    }

    public function deleteMedicalAttachment(Request $request)
    {
        DB::table('medical_attach_files')->where(['emp_id' => $request->emp_id, 'id' => $request->id])->delete();
        return 0;
    }

    public function sendOnExternalOnboarding($id)
    {
        $user = EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->where('id', $id)->exists();

        if ($user) {

            $user_details = EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->where('id', $id)->first();

            $digits = 6;
            $password =  rand(pow(10, $digits - 1), pow(10, $digits) - 1);
            EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->where('id', $id)->update([
                'password' => Hash::make($password)
            ]);

            $params = [
                'subject' => 'Employee Registration | ' . env("APP_NAME"),
                'to' => $user_details->employee_email,
                'blade' => view('Emails/external_employee_registration', ['email' => $user_details->employee_email, 'password' => $password, 'subject' => 'Employee Registration'])->render()
            ];

            $emailSent = $this->SendInstantEmail($params);

            if ($emailSent) {
                return 'Email has been sent, Please check your Email.';
            } else {
                return 'SMTP is not Working, Try Later!';
            }
        } else {
            return 'Account with the entered email does not exsit.';
        }
    }

    public function assignShift($key, $id)
    {
        $link_management =  DB::table('link_management')->where(['secret_key' => $key])->first();

        // Validate link_management exists
        if (!$link_management) {
            Log::error('assignShift: Link management not found', ['key' => $key, 'id' => $id]);
            throw new \Exception('Link management not found for the provided key');
        }

        $role = DB::table('roles')->where('id', $link_management->role_id)->first();

        // Validate role exists
        if (!$role) {
            Log::error('assignShift: Role not found', ['role_id' => $link_management->role_id, 'key' => $key, 'id' => $id]);
            throw new \Exception('Role not found for the provided role_id: ' . $link_management->role_id);
        }

        // Validate role has code property
        if (!isset($role->code) || $role->code === null) {
            Log::error('assignShift: Role code is missing', ['role_id' => $link_management->role_id, 'key' => $key, 'id' => $id]);
            throw new \Exception('Role code is missing for role_id: ' . $link_management->role_id);
        }

        EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->where('id', $id)->update(['access_role' => $role->code, 'tier_id' => $link_management->tier_id, 'link_key' => $key]);
        $days = [];
        // Validate working_days exists and is not empty
        if (!empty($link_management->working_days)) {
            $working_days = explode(',', $link_management->working_days);
            foreach ($working_days as $day) {
                // Convert to proper case (MONDAY -> Monday) before looking up in constants
                $proper_case_day = ucfirst(strtolower(trim($day)));
                $mapped_day = config('constants.weekdays_name.' . $proper_case_day);
                if ($mapped_day) {
                    $days[] = $mapped_day;
                }
            }
        }
        
        $arr = [
            'start_date' => Carbon::today()->format('Y-m-d'),
            'end_date' =>  Carbon::today()->addDays($link_management->number_of_days ?? 1)->format('Y-m-d'),
            'start_time' => $link_management->start_time ?? '09:00:00',
            'end_time' => $link_management->end_time ?? '17:00:00',
            'working_hours' => $link_management->required_hours ?? 8,
            'color_code' => $link_management->color_code ?? null,
            'break_minutes' => $link_management->paid_break ?? 0,
            'shift_notes' => $link_management->description ?? null,
            'users_ids' => [$id],
            'working_days_hidden' => implode(',', $days),
            'site_id' => $link_management->site_id ?? null
        ];

        return  $this->externalbulkScheduleRoasterCreate($arr, $arr, $key); //Trait
        return 0;
    }

    public function storeHistory($arr)
    {
        RosterHistory::create([
            'roster_template_id' => $arr['roster_template_id'],
            'updated_by' => '1',
            'description' => $arr['description']
        ]);
    }

    function getShortDayNames($days)
    {
        $shortDays = array();

        foreach ($days as $day) {
            switch ($day) {
                case "Monday":
                    $shortDays[] = "Mon";
                    break;
                case "Tuesday":
                    $shortDays[] = "Tue";
                    break;
                case "Wednesday":
                    $shortDays[] = "Wed";
                    break;
                case "Thursday":
                    $shortDays[] = "Thu";
                    break;
                case "Friday":
                    $shortDays[] = "Fri";
                    break;
                case "Saturday":
                    $shortDays[] = "Sat";
                    break;
                case "Sunday":
                    $shortDays[] = "Sun";
                    break;
                default:
                    $shortDays[] = "Invalid day";
                    break;
            }
        }

        return $shortDays;
    }

    function required_external_data(Request $request)
    {
        $secritkey = $request->key;
        $link_detail = LinkManagement::where('secret_key', $secritkey)->first();

        if (!$link_detail) {
            return $this->error('Invalid secret key', 404);
        }

        // Get customer settings from Adminsettings table
        $customerSettings = Adminsettings::where('customer_id', $link_detail->customer_id)
            ->where('workspace', $link_detail->workspace_id)
            ->get()
            ->map(function ($setting) {
                return [
                    'key' => $setting->key,
                    'value' => $setting->value
                ];
            })
            ->toArray();

        $data['emp_worker_types'] = EmpWorkerType::where('del', '0')
            ->where('customer_id', $link_detail->customer_id)
            ->where('workspace_id', $link_detail->workspace_id)
            ->get();

        $data['teams'] = EmpTeam::where('del', '0')
            ->where('customer_id', $link_detail->customer_id)
            ->where('workspace_id', $link_detail->workspace_id)
            ->get();
        $data['customer_settings'] = $customerSettings;
        $data['required_documents'] = RequiredDocument::with(['requiredDocumentField' => function ($query) {
            $query->where('status', 1)->where('del', 0);  // Only retrieve related records where status = 1
        }])->where('del', '0')->where('customer_id', $link_detail->customer_id)->where('workspace_id', $link_detail->workspace_id)->where('for_who', '!=', 'internal')->get();
        return $this->success($data, 'Get data successfully');
    }

    /**
     * Send external employee onboarding email with login credentials
     * 
     * @param int $empId
     * @return void
     */
    private function sendExternalOnboardingEmail($empId, $customer_id)
    {
        // Validate customer_id
        if (!$customer_id) {
            Log::error('sendExternalOnboardingEmail: customer_id is missing', ['empId' => $empId]);
            return;
        }

        // Get employee data
        $employeeCompany = EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)
            ->find($empId);
        $employee = EmpPersonalDetails::where('emp_id', $empId)->first();

        if (!$employeeCompany || !$employee) {
            Log::error('sendExternalOnboardingEmail: Employee data not found', ['empId' => $empId, 'customer_id' => $customer_id]);
            return;
        }



        $teamMember = EmpTeamsMember::where('emp_id', $empId)->first();
        $teamName = 'N/A';
        
        if ($teamMember && isset($teamMember->team_id)) {
            $team = EmpTeam::where('id', $teamMember->team_id)->first();
            $teamName = $team->title ?? 'N/A';
        }

        // Generate random password
        $password = $this->generateRandomPassword();

        // Hash and save password to employee
        $employeeCompany->password = Hash::make($password);
        $employeeCompany->save();

        // Get worker type
        $workerType = EmpWorkerType::find($employeeCompany->worker_type);

        // Prepare login URL
        $loginUrl = env('FRONTEND_URL', url('/'));

        // Get roster assignments and schedule details for this employee
        $rosterAssignments = RosterAssign::where('assign_to', $empId)
            ->with('rosterTemplate')
            ->orderBy('schedule_date', 'asc')
            ->get();

        $rosterDetails = [
            'individual_shifts' => [],
            'bulk_schedule' => null
        ];

        // Get link management details to show bulk schedule info
        $employeeDetails = EmpCompanyDetails::withoutGlobalScope(\App\Scopes\NotDeletedScope::class)->find($empId);
        $linkManagement = null;
        if ($employeeDetails && $employeeDetails->link_key) {
            $linkManagement = LinkManagement::where('secret_key', $employeeDetails->link_key)->first();
        }

        // If we have link management, show bulk schedule details
        if ($linkManagement) {
            $working_days = explode(',', $linkManagement->working_days);
            $working_day_names = [];
            foreach ($working_days as $day) {
                // Convert to proper case (MONDAY -> Monday) before looking up in constants
                $proper_case_day = ucfirst(strtolower(trim($day)));
                $mapped_day = config('constants.weekdays_name.' . $proper_case_day, $proper_case_day);
                $working_day_names[] = $mapped_day;
            }

            $startDate = Carbon::today();
            $endDate = Carbon::today()->addDays($linkManagement->number_of_days);

            $rosterDetails['bulk_schedule'] = [
                'schedule_period_start' => $startDate->format('d-m-Y'),
                'schedule_period_end' => $endDate->format('d-m-Y'),
                'total_days' => $linkManagement->number_of_days,
                'working_days' => implode(', ', $working_day_names),
                'daily_start_time' => date('h:i A', strtotime($linkManagement->start_time)),
                'daily_end_time' => date('h:i A', strtotime($linkManagement->end_time)),
                'daily_break_minutes' => $linkManagement->paid_break ?? 0,
                'shift_notes' => $linkManagement->description ?? '',
                'total_working_days' => count($working_days)
            ];
        }

        // Get some example individual shifts (next 7 days)
        $exampleShifts = $rosterAssignments->take(7);
        foreach ($exampleShifts as $assignment) {
            if ($assignment->rosterTemplate) {
                $rosterDetails['individual_shifts'][] = [
                    'schedule_date' => date('d-m-Y', strtotime($assignment->schedule_date)),
                    'day_name' => date('l', strtotime($assignment->schedule_date)),
                    'start_time' => date('h:i A', strtotime($assignment->rosterTemplate->start_time)),
                    'end_time' => date('h:i A', strtotime($assignment->rosterTemplate->end_time)),
                    'break_minutes' => $assignment->rosterTemplate->break_minutes ?? 0,
                    'shift_notes' => $assignment->rosterTemplate->shift_notes ?? '',
                    'working_hours' => $assignment->rosterTemplate->working_hours ?? 0
                ];
            }
        }

        // Send email with login credentials and roster details
        $emailParams = [
            'to' => $employeeCompany->employee_email,
            'subject' => 'Welcome to ' . env('APP_NAME', 'WMS') . ' - Your Login Credentials & Schedule',
            'msg' => view('Emails.external_employee_onboarding', [
                'subject' => 'Welcome to ' . env('APP_NAME', 'WMS') . ' - Your Login Credentials & Schedule',
                'employee' => $employee,
                'employeeCompany' => $employeeCompany,
                'workerType' => $workerType,
                'password' => $password,
                'login_url' => $loginUrl,
                'rosterDetails' => $rosterDetails,
                'teamName' => $teamName,
                'customer_id' => $customer_id
            ])->render()
        ];

        $this->SendInstantEmail($emailParams);
    }

    /**
     * Generate random password
     * 
     * @return string
     */
    private function generateRandomPassword()
    {
        $length = 8;
        $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $password = '';

        for ($i = 0; $i < $length; $i++) {
            $password .= $characters[rand(0, strlen($characters) - 1)];
        }

        return $password;
    }
}
