<?php


function processDocument($conn_rjllearning_specific, $remove_bool, $document_details_key, $busses_id, $institution_id, $branch_id, $username, $workspace_id, $document_type) {
    // Determine the attachment column based on the document type
    $attachment_column = $document_type . '_attachment'; // e.g., 'insured_attachment'

    // Ensure $remove_bool is properly set
    $remove_bool = isset($remove_bool) && !empty($remove_bool) ? trim($remove_bool) : 0;

    // Step 1: Fetch the current attachment from the 'buses' table
    $sql_image = $conn_rjllearning_specific->prepare("SELECT $attachment_column FROM buses WHERE id = ? AND institution_id = ?");
    $sql_image->execute([$busses_id, $institution_id]);
    $result_image = $sql_image->fetch(PDO::FETCH_ASSOC);
    $existing_attachment = $result_image[$attachment_column] ?? null;

    // Step 2: Handle the removal of the existing attachment if $remove_bool is set
    if ($remove_bool == 1 && $existing_attachment) {
        awsS3UserUploadDelete($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $conn_rjllearning_specific, $institution_id, $existing_attachment, null, null);
        $conn_rjllearning_specific->prepare("UPDATE buses SET $attachment_column = ? WHERE id = ? AND institution_id = ?")->execute([null, $busses_id, $institution_id]);
    }

    // Step 3: Handle file upload if a file exists in $_FILES
    // We will check for `$_FILES['insurance_details']['name']['insured_attachment']` format
    if (isset($_FILES[$document_details_key]['name'][$document_type . '_attachment']) && $_FILES[$document_details_key]['error'][$document_type . '_attachment'] == UPLOAD_ERR_OK) {
        // Extract file information
        $file_name = $_FILES[$document_details_key]['name'][$document_type . '_attachment'];
        $fileTmpName = $_FILES[$document_details_key]['tmp_name'][$document_type . '_attachment'];
        $fileSize = $_FILES[$document_details_key]['size'][$document_type . '_attachment'];
        $fileType = $_FILES[$document_details_key]['type'][$document_type . '_attachment'];
        $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        // Allowed file types and extensions
        $allowedTypes = [
            'image/jpeg', 'image/png', 'image/gif', 'image/heic',
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ];
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
        $maxFileSize = 25 * 1024 * 1024; // Maximum file size 25 MB

        // Validate the file
        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

        // Step 4: Prepare directory and file name for S3 upload
        $currentYear = date('Y');
        $currentMonth = date('n');
        $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . $currentYear . "/" . $currentMonth . "/";
        $image_name =  date('d-m-Y') . "." . $file_extension;
        $keyName = $directoryPathMain . uniqid . "_" . time() . '.' . $file_extension;

        try {
            // Upload to S3
            $GLOBALS['s3_learning_bucket']->putObject([
                'Bucket' => $GLOBALS['learning_bucketName'],
                'Key' => $keyName,
                'SourceFile' => $fileTmpName,
            ]);

            // Prepare attachment data as JSON
            $attachment_data = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);

           // Update the database with the new attachment
            $sql_users = "UPDATE buses SET $attachment_column = ? WHERE id = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql_users)->execute([$attachment_data, $busses_id, $institution_id]);

        } catch (Exception $e) {
            errorreturn($e->getMessage());
            return false;
        }
    }

    return true; // No upload necessary if no file
}


function updateInsuranceDetails($conn_rjllearning_specific, $remove_bool, $busses_id, $institution_id, $branch_id, $username, $workspace_id, $insurance_details) {
    $results = []; // Array to hold the results


        
        $insured_on = $insurance_details['insured_on'];
   
        $insured_valid_upto = $insurance_details['insured_valid_upto'];
        // Call processDocument for each insurance detail
        $attachment_column = processDocument(
            $conn_rjllearning_specific,
            $remove_bool,
            'insurance_details',  // Pass the current insurance detail here
            $busses_id,
            $institution_id,
            $branch_id,
            $username,
            $workspace_id,
            'insured'  // Ensure this matches the column name in the database
        );

        // Collect the result
        $results[] = [
            'insured_on' => $insured_on,
            'insured_valid_upto' => $insured_valid_upto,
            'insured_attachment_column' => $attachment_column,
        ];


    // Return the collected results
    return $results;

}


function updatepermitdetails($conn_rjllearning_specific, $remove_bool, $busses_id, $institution_id, $branch_id, $username, $workspace_id, $permit_result) {
    $results = []; // Array to hold the results

        $permit_initial_date = $permit_result['permit_initial_date'];
        $permit_valid_upto = $permit_result['permit_valid_upto'];
       
       

        // Call processDocument for each insurance detail
        $attachment_column = processDocument(
            $conn_rjllearning_specific,
            $remove_bool,
            'permit_result',  // Pass the current insurance detail here
            $busses_id,
            $institution_id,
            $branch_id,
            $username,
            $workspace_id,
            'permit'  // Ensure this matches the column name in the database
        );

        // Collect the result
        $results[] = [
            'permit_initial_date' => $permit_initial_date,
            'permit_valid_upto' => $permit_valid_upto,
            'permit_attachment' => $attachment_column,
        ];
    

    // Return the collected results
    return $results;

}





function updatepassingdetails($conn_rjllearning_specific, $remove_bool, $busses_id, $institution_id, $branch_id, $username, $workspace_id, $passing_details) {
    $results = []; // Array to hold the results


        $passing_initial_date = $passing_details['passing_initial_date'];
        $passing_valid_utpo = $passing_details['passing_valid_upto'];


        // Call processDocument for each insurance detail
        $attachment_column = processDocument(
            $conn_rjllearning_specific,
            $remove_bool,
            'passing_details',  // Pass the current insurance detail here
            $busses_id,
            $institution_id,
            $branch_id,
            $username,
            $workspace_id,
            'passing'  // Ensure this matches the column name in the database
        );

        // Collect the result
        $results[] = [
            'passing_initial_date' => $passing_initial_date,
            'passing_valid_utpo' => $passing_valid_utpo,
            'passing_attachment' => $attachment_column,
        ];
    
    // Return the collected results
    return $results;
}

function updateregistrationDetails($conn_rjllearning_specific, $remove_bool, $busses_id, $institution_id, $branch_id, $username, $workspace_id, $registration_certificate) {
    $results = []; // Array to hold the results

        // Extract values with default handling
        $registration_date = isset($registration_certificate['registration_date']) ? $registration_certificate['registration_date'] : null;
        $registration_valid_upto = isset($registration_certificate['registration_valid_upto']) ? $registration_certificate['registration_valid_upto'] : null;
       

        // Call processDocument for each registration detail
        $attachment_column = processDocument(
            $conn_rjllearning_specific,
            $remove_bool,
            'registration_certificate',  // Pass the current registration detail here
            $busses_id,
            $institution_id,
            $branch_id,
            $username,
            $workspace_id,
            'registration'  // Ensure this matches the column name in the database
        );

        // Collect the result
        $results[] = [
            'registration_date' => $registration_date,
            'registration_valid_upto' => $registration_valid_upto,
            'registration_attachment' => $attachment_column,
        ];
    

    // Return the collected results
    return $results;
}

function updateroadDetails($conn_rjllearning_specific, $remove_bool, $busses_id, $institution_id, $branch_id, $username, $workspace_id, $road_tax_details) {
    $results = []; // Array to hold the results

   
        $road_tax_initial_date = $road_tax_details['road_tax_initial_date'];
        $road_tax_valid_upto = $road_tax_details['road_tax_valid_upto'];


        // Call processDocument for each insurance detail
        $attachment_column = processDocument(
            $conn_rjllearning_specific,
            $remove_bool,
            'road_tax_details',  // Pass the current insurance detail here
            $busses_id,
            $institution_id,
            $branch_id,
            $username,
            $workspace_id,
            'road_tax'  // Ensure this matches the column name in the database
        );

        // Collect the result
        $results[] = [
            'road_tax_initial_date' => $road_tax_initial_date,
            'road_tax_valid_upto' => $road_tax_valid_upto,
            'road_tax_attachment' => $attachment_column,
        ];
    
    // Return the collected results
    return $results;
}


function vehicle($conn_rjllearning_specific, $postdata, $remove_bool, $busses_id, $institution_id, $branch_id, $username, $workspace_id) {
    $results = [];
    
    // Define the specific file keys expected
    $file_keys = ['front_side', 'back_side', 'left_side', 'right_side'];
    
    // Iterate over each file key
    foreach ($file_keys as $file_key) {
        $attachment_column = $file_key;

        // Fetch existing attachment
        $sql_image = $conn_rjllearning_specific->prepare("SELECT $attachment_column FROM buses WHERE id = ? AND institution_id = ?");
        $sql_image->execute([$busses_id, $institution_id]);
        $rows = $sql_image->fetch(PDO::FETCH_ASSOC);
        $existing_attachment = $rows[$attachment_column] ?? null;

        // Handle removal of the existing attachment
        if ($remove_bool == 1 && $existing_attachment) {
            // Delete from S3
            $existing_file = json_decode($existing_attachment, true);
           $file_path = $existing_file['filepath'];
            awsS3UserUploadDelete($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $conn_rjllearning_specific, $institution_id, $file_path, null, null);

            // Update database
            $sql = "UPDATE buses SET $attachment_column = NULL WHERE id = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql)->execute([$busses_id, $institution_id]);
        }

        // Handle file upload if a new file is provided
        if (isset($_FILES[$file_key]) && $_FILES[$file_key]['error'] == UPLOAD_ERR_OK) {
            $file = $_FILES[$file_key];
            $file_info = [
                'name' => $file['name'],
                'type' => $file['type'],
                'tmp_name' => $file['tmp_name'],
                'error' => $file['error'],
                'size' => $file['size'],
            ];


            $currentYear = date('Y');
            $currentMonth = date('m');
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . $currentYear . "/" . $currentMonth . "/";

            $file_name = $file_info['name'];
            $fileTmpName = $file_info['tmp_name'];
            $fileSize = $file_info['size'];
            $fileType = $file_info['type'];
            $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

            $allowedTypes = [
                'image/jpeg', 'image/png', 'image/gif', 'image/heic',
                'application/pdf', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'application/vnd.ms-excel', 'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            ];
            $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
            $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

            // Check if the file is valid
            try {
                checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
            } catch (Exception $e) {
                errorreturn($e->getMessage());
                $results[$attachment_column] = false;
                continue; // Skip to next file key
            }

            $image_name = time() . "-" . date('d-m-Y') . "." . uniqid.$file_extension;
            $attachment = $directoryPathMain . $image_name;

            try {
                // Upload to S3
                $GLOBALS['s3_learning_bucket']->putObject([
                    'Bucket' => $GLOBALS['learning_bucketName'],
                    'Key' => $attachment,
                    'SourceFile' => $fileTmpName,
                ]);

                // Prepare the attachment data as JSON
                $attachment_data = json_encode(['filepath' => $attachment, 'original_name' => $file_name]);

                // Update the database with the new attachment
                $sql_users = "UPDATE buses SET $attachment_column = ? WHERE id = ? AND institution_id = ?";
                $conn_rjllearning_specific->prepare($sql_users)->execute([$attachment_data, $busses_id, $institution_id]);

                $results[$attachment_column] = $attachment_data;
            } catch (Exception $e) {
                errorreturn($e->getMessage());
                $results[$attachment_column] = false;
            }
        } else {
            // Handle cases where file upload errors occur
            if (isset($_FILES[$file_key]) && $_FILES[$file_key]['error'] != UPLOAD_ERR_OK) {
                $results[$attachment_column] = "File upload error: " . $_FILES[$file_key]['error'];
            } else {
                $results[$attachment_column] = false;
            }
        }
    }

    return $results;
}





function handleBusAttachment(
    $conn_rjllearning_specific,
    $s3_learning_bucket,
    $learning_bucketName,
    $workspace_id,
    $institution_id,
    $busses_id,
    $username,
    $remove_bool,
    $side
) {
    try {
        // Check for existing attachment
        $res = $conn_rjllearning_specific->prepare("SELECT $side FROM buses WHERE id = ? AND institution_id = ?");
        $res->execute(array($busses_id, $institution_id));
        $result = $res->fetchAll();

        if (count($result) != 1) {
        errorreturn("$side does not exist for the given bus.");
    }
        $existing_attachment = $result[0][$side] ?? null;

        // Handle removal of existing attachment
        if ($remove_bool == 1 && $existing_attachment !== null) {
            // Remove from S3
            $existing_file = json_decode($existing_attachment, true);
        $file_path = $existing_file['filepath'];
            awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $file_path, null, null);

            // Update database
            $sql = "UPDATE buses SET $side = ? WHERE id = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql)->execute(array(null, $busses_id, $institution_id));
        }

        // Handle new attachment
        if ($remove_bool == 1 && isset($_FILES[$side])) {
            if ($existing_attachment === null) {
                $currentYear = date('Y');
                $currentMonth = date('m');
                $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . $currentYear . "/" . $currentMonth . "/";
          
            } else {
                $directoryPathMain = substr($existing_attachment, 0, strrpos($existing_attachment, '/') + 1);
            }

            // Handle the new file
            $file_name = $_FILES[$side]['name'];
            $fileTmpName = $_FILES[$side]["tmp_name"];
            $fileSize = $_FILES[$side]["size"];
            $fileType = $_FILES[$side]["type"];
            $file_extension = strtolower(pathinfo($_FILES[$side]['name'], PATHINFO_EXTENSION));
            $maxFileSize = 2 * 1024 * 1024; // 2 MB

            // Validate the file
            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, 
                ['image/jpeg', 'image/png', 'image/gif', 'image/heic', 'application/pdf', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'], 
                ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx']
            );

            $image_name = uniqid . "." . time().$file_extension;
            $attachment_path = $directoryPathMain . $image_name;
            
            // Upload to S3
            try {
                $s3_learning_bucket->putObject([
                    'Bucket' => $learning_bucketName,
                    'Key' => $attachment_path,
                    'SourceFile' => $fileTmpName,
                ]);
            } catch (Exception $e) {
                return false;
            }

            // Update database
            $attachment = json_encode(array("filepath" => $attachment_path, "original_name" => $file_name));
            $sql = "UPDATE buses SET $side = ? WHERE id = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql)->execute(array($attachment, $busses_id, $institution_id));

            return true;
        }

        return true;
    } catch (Exception $e) {
        return false;
    }
}



function updateBusDetails(
    $conn_rjllearning_specific,
    $busses_id,
    $institution_id,
    $branch_id,
    $bus_number,
    $capacity,
    $meter_readings,
    $route_id,
    $manufacturer,
    $model_year,
    $year_of_purchase,
    $insuranceDetails,
    $permitDetails,
    $passingDetails,
    $registrationDetails,
    $roadtaxDetails,
    $username,
    $date_created,
    $time_created,
    $status
) {  
            
    // Prepare the SQL query for UPDATE
    $update_bus_sql = "UPDATE buses SET
        bus_number = ?,
        capacity = ?,
        meter_readings = ?,
        route_id = ?,
        manufacturer = ?,
        model_year = ?,
        year_of_purchase = ?,
        insured_on = ?,
        insured_valid_upto = ?,
        permit_initial_date = ?,
        permit_valid_upto = ?,
        passing_initial_date = ?,
        passing_valid_upto = ?,
        registration_date = ?,
        registration_valid_upto = ?,
        road_tax_initial_date = ?,
        road_tax_valid_upto = ?,
        added_by = ?,
        date_created = ?,
        time_created = ?,
        status = ?
        WHERE id = ? AND institution_id = ?";

    try {
        // Prepare and execute the SQL query
        $stmt = $conn_rjllearning_specific->prepare($update_bus_sql);

        $stmt->execute([
            $bus_number,
            $capacity,
            $meter_readings,
             $route_id,
            $manufacturer,
            $model_year,
            $year_of_purchase,
            $insuranceDetails[0]['insured_on'] ?? null,
             $insuranceDetails[0]['insured_valid_upto'] ?? null,
            $permitDetails[0]['permit_initial_date'] ?? null,
            $permitDetails[0]['permit_valid_upto'] ?? null,
            $passingDetails[0]['passing_initial_date'] ?? null,
            $passingDetails[0]['passing_valid_utpo'] ?? null,
            $registrationDetails[0]['registration_date'] ?? null,
             $registrationDetails[0]['registration_valid_upto'] ?? null,
            $roadtaxDetails[0]['road_tax_initial_date'] ?? null,
            $roadtaxDetails[0]['road_tax_valid_upto'] ?? null,
            $username,
            $date_created,
            $time_created,
            $status,
            $busses_id,
           $institution_id
        ]);

        // Return true on success
        return true;
    } catch (PDOException $e) {
        // Return false on error
        return false;
    }
}












// Function to handle file upload and storage
function processFile($institution_id,$workspace_id,$file, $directoryPathMain, $userid, $maxFileSize, $allowedTypes, $allowed_extensions) {
    if ($file !== null) {
        $file_name = $file['name'];
        $fileTmpName = $file["tmp_name"];
        $fileSize = $file["size"];
        $fileType = $file["type"];
        $fileError = $file["error"];
        $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
 $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";
 $maxFileSize = 25 * 1024 * 1024; // Maximum file size 25 MB
$allowedTypes = [
    'image/jpeg', 'image/png', 'image/gif', 'image/heic',
    'application/pdf',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-excel',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
];
$allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];

        $keyName = $directoryPathMain . uniqid . "_" . time() . '.' . $file_extension;
        // Move uploaded file to the target directory
        move_uploaded_file($fileTmpName, $keyName);

        return json_encode(array("filepath" => $keyName, "original_name" => $file_name));
    }
    return null;
}



function processAttachment($s3_learning_bucket, $learning_bucketName, $attachment, $type, $workspace_id, $institution_id, $userid) {
    // Check if $attachment is a valid file
    if (is_array($attachment) && !empty($attachment['name'])) {
        // Extract file details
        $file_name = $attachment['name'];
        $fileTmpName = $attachment["tmp_name"];
        $fileSize = $attachment["size"];
        $fileType = $attachment["type"];
        $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        
        // Ensure valid file types
        $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
        $allowed_extensions = ['jpg', 'gif', 'png', 'jpeg', 'pdf'];
        $maxFileSize = 25 * 1024 * 1024; // 25MB
        
        // Validate the file (you would add a function checkFileValidation here)
        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        
        // Generate a unique name using a timestamp and user ID
        $unique_id = uniqid($userid . "_", true); // Example: 12345_63f5c1f7cc3e7.567890
        $unique_file_name = $unique_id . "." . $file_extension;
        
        // Construct the directory path
        $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";
        $attachment_path = $directoryPathMain . $unique_file_name;
        
        // Try to upload the file
        try {
            $s3_learning_bucket->putObject([
                'Bucket' => $learning_bucketName,
                'Key' => $attachment_path,
                'SourceFile' => $fileTmpName,
            ]);
        } catch (Exception $e) {
            errorreturn($e->getMessage());
        }
        
        // Return the processed attachment as an array (not JSON yet)
        return [
            "type" => $type,
            "filepath" => $attachment_path,
            "original_name" => $file_name
        ];
    }
    
    // Return null if no valid attachment was processed
    return null;
}




















function updateMultipleAttachments(
    $conn_rjllearning_specific,
    $s3_learning_bucket,
    $learning_bucketName,
    $workspace_id,
    $institution_id,
    $userid,
    $busses_id,
    $vehicle_details
) {
    try {
        // Check if the bus record exists
        $res = $conn_rjllearning_specific->prepare("SELECT vehicle_images FROM buses WHERE id = ? AND institution_id = ?");
        $res->execute([$busses_id, $institution_id]);
        $result1 = $res->fetchAll();

        if (count($result1) != 1) {
            errorreturn("Bus record does not exist.");
            return false; // Early exit if the record does not exist
        }

        // Decode existing attachments
        $existing_attachments = !empty($result1[0]['vehicle_images']) ? json_decode($result1[0]['vehicle_images'], true) : [];

        // Prepare to handle new attachments and removal
        $processed_vehicle_images = [];
        $types_to_remove = [];
        $currentYear = date('Y');
        $currentMonth = date('m');
        $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . $currentYear . "/" . $currentMonth . "/";

        // Keep track of existing types to avoid duplicates
        $existing_types = array_column($existing_attachments, 'type');

        foreach ($vehicle_details as $attachmentDetail) {
            if (is_array($attachmentDetail) && isset($attachmentDetail['type'])) {
                $attachmentType = $attachmentDetail['type']; // e.g., 'front_side'

                // Check for uploaded file for the current type
                $fileKey = $attachmentType; // This should match the key in $_FILES
                if (isset($_FILES[$fileKey]) && $_FILES[$fileKey]['error'] == UPLOAD_ERR_OK) {
                    // If a new file is found, prepare to process it
                    $types_to_remove[] = $attachmentType;

                    // Process the file upload
                    $attachment = $_FILES[$fileKey];
                    $file_name = $attachment['name'];
                    $fileTmpName = $attachment["tmp_name"];
                    $fileSize = $attachment["size"];
                    $fileType = $attachment["type"];
                    $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

                    // Validate file
                    $allowedTypes = [
                        'image/jpeg', 'image/png', 'image/gif', 'image/heic', 'application/pdf',
                        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel',
                        'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    ]; // Allowed file types
                    $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
                    $maxFileSize = 2 * 1024 * 1024; // 2MB

                    // Check file validation
                    checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

                    $image_name = $directoryPathMain . uniqid('', true) . "_" . time() . '.' . $file_extension;

                    $attachmentKey = $directoryPathMain . $image_name;

                    if (file_exists($fileTmpName)) {
                        // Upload file to S3
                        $s3_learning_bucket->putObject([
                            'Bucket' => $learning_bucketName,
                            'Key' => $attachmentKey,
                            'SourceFile' => $fileTmpName,
                        ]);

                        // Add processed attachment to the list
                        $processed_vehicle_images[] = [
                            "type" => $attachmentType,
                            "filepath" => $attachmentKey,
                            "original_name" => $file_name
                        ];
                    } else {
                        errorreturn("File not found: " . $fileTmpName);
                    }
                }
            } else {
                errorreturn("Invalid attachment detail format.");
                return false; // Early exit for invalid format
            }
        }

        // Remove existing attachments for the types that have new files uploaded
        foreach ($types_to_remove as $type) {
            foreach ($existing_attachments as $key => $attachment) {
                if ($attachment['type'] === $type && isset($attachment['filepath'])) {
                    // Delete the file from S3
                    awsS3UserUploadDelete(
                        $s3_learning_bucket,
                        $learning_bucketName,
                        $conn_rjllearning_specific,
                        $institution_id,
                        $attachment['filepath'],
                        null,
                        null
                    );
                    // Remove the attachment from the array
                    unset($existing_attachments[$key]);
                }
            }
        }

        // Combine old and new attachments, ensuring no duplicates
        $final_attachments = array_merge($existing_attachments, $processed_vehicle_images);
        $attachmentsJson = json_encode(array_values($final_attachments)); // Re-index the array

        // Update database with new attachments
        $sql_users = "UPDATE buses SET vehicle_images = ? WHERE id = ? AND institution_id = ?";
        $conn_rjllearning_specific->prepare($sql_users)->execute([$attachmentsJson, $busses_id, $institution_id]);

        return true; // Return true if everything was successful

    } catch (Exception $e) {
        errorreturn($e->getMessage());
        return false; // Return false if an exception was caught
    }
}

function validateModelYear($model_year) {
    // Trim the input
    $model_year = trim($model_year);

    // Check if the model year is empty
    if (empty($model_year)) {
        return "Model year is required.";
    }

    // Check if it's a valid four-digit year
    if (!preg_match('/^\d{4}$/', $model_year)) {
        return "Model year must be a four-digit number.";
    }

    // Check if the year is not in the future (assuming the current year is the maximum valid year)
    $currentYear = date("Y");
    if ($model_year > $currentYear) {
        return "Model year cannot be in the future.";
    }

    // Optionally: Check for a minimum year (e.g., 1900)
    if ($model_year < 1900) {
        return "Model year must be after 1900.";
    }

    // If all checks pass, return null (indicating valid input)
    return null;
}

function validateMeterReadings($meter_readings) {
    // Trim the input
    $meter_readings = trim($meter_readings);

    // Check if the meter readings is empty
    if (empty($meter_readings)) {
        return "Meter readings are required.";
    }

    // Check if it's a valid number (integer or float)
    if (!is_numeric($meter_readings)) {
        return "Meter readings must be a numeric value.";
    }

    // Optionally: Check for non-negative values
    if ($meter_readings < 0) {
        return "Meter readings cannot be negative.";
    }

    // If all checks pass, return null (indicating valid input)
    return null;
}

function validateYearOfPurchase($year_of_purchase) {
    // Trim the input
    $year_of_purchase = trim($year_of_purchase);

    // Check if the year of purchase is empty
    if (empty($year_of_purchase)) {
        return "Year of purchase is required.";
    }

    // Check if it's a valid four-digit year
    if (!preg_match('/^\d{4}$/', $year_of_purchase)) {
        return "Year of purchase must be a four-digit number.";
    }

    // Check if the year is not in the future
    $currentYear = date('Y');
    if ($year_of_purchase > $currentYear) {
        return "Year of purchase cannot be in the future.";
    }

    // If all checks pass, return null (indicating valid input)
    return null;
}



