<?php
ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';


require_once $base_path_to_learning .'admin_api/modules/transportation/buses/function.php';


require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = $_POST;
// Print the postdata and uploaded files
// echo "<pre>";
// echo "Post Data:\n";
// print_r($postdata);

// echo "\nUploaded Files:\n";
// print_r($_FILES);

// die(); // Stop execution to inspect the output

$required_fields = ['institution_id', 'branch_id', 'bus_number', 'api_signature', 'function_type', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';


$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$bus_number = trim($postdata['bus_number']);
$capacity = trim($postdata['capacity']);
$manufacturer= trim($postdata['manufacturer']);
$model_year = trim($postdata['model_year']);
$model_year_error = validateModelYear($model_year);

if ($model_year_error) {
    // Handle the error (e.g., return it in the response)
    errorreturn($model_year_error);
}
// $route_id=trim($postdata['route_id']);
$year_of_purchase = trim($postdata['year_of_purchase']);
$year_of_purchase_error = validateYearOfPurchase($year_of_purchase);

if ($year_of_purchase_error) {
    // Handle the error (e.g., return it in the response)
    errorreturn($year_of_purchase_error);
}

$meter_readings = trim($postdata['meter_readings']);
$meter_readings_error = validateMeterReadings($meter_readings);

if ($meter_readings_error) {
    // Handle the error (e.g., return it in the response)
    errorreturn($meter_readings_error);
}


$route_id = trim($postdata['route_id']);

// Prepare the query to check if the route exists
$check_route_sql = "SELECT id FROM routes WHERE id = ? and institution_id=?";

// Prepare and execute the statement
$stmt = $conn_rjllearning_specific->prepare($check_route_sql);
$stmt->execute([$route_id,$institution_id]);

// Fetch the route ID if it exists
$existing_route = $stmt->fetch(PDO::FETCH_ASSOC);

if ($existing_route) {
    $route_id = $existing_route['id']; // Fetch the existing route ID
} else {
    // print_r($route_id);
    errorreturn("Route ID does not exist.");
}

// Process insurance details
$insurance_details = is_array($postdata['insurance_details']) ? $postdata['insurance_details'] : json_decode($postdata['insurance_details'], true);

// Process permit details
$permit_details = is_array($postdata['permit_details']) ? $postdata['permit_details'] : json_decode($postdata['permit_details'], true);

// Process passing details
$passing_details = is_array($postdata['passing_details']) ? $postdata['passing_details'] : json_decode($postdata['passing_details'], true);

// Process registration certificate
$registration_certificate = is_array($postdata['registration_certificate']) ? $postdata['registration_certificate'] : json_decode($postdata['registration_certificate'], true);

// Process road tax
$road_tax_details= is_array($postdata['road_tax']) ? $postdata['road_tax'] : json_decode($postdata['road_tax'], true);


// $vehicle_details = isset($postdata['vehcile_details']) ? json_decode($postdata['vehcile_details'], true) : [];
$vehicle_details = !empty($postdata['vehicle_details']) 
    ? (is_array($postdata['vehicle_details']) 
        ? $postdata['vehicle_details'] 
        : json_decode($postdata['vehicle_details'], true)) 
    : [];




$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}


if ($postdata['function_type'] == 'create_bus') {
    
    // Check if the bus_number already exists for the given institution_id and branch_id
$checkQuery = "SELECT COUNT(*) FROM buses WHERE institution_id = ? AND branch_id = ? AND bus_number = ?";
$stmt = $conn_rjllearning_specific->prepare($checkQuery);

// Make sure to pass the institution_id, branch_id, and bus_number to the execute method
$stmt->execute([$institution_id, $branch_id, $bus_number]);

$exists = $stmt->fetchColumn();

if ($exists > 0) {
    errorreturn('Bus with this number already exists.');
}

             
       
$processed_vehicle_images = [];

// Check if vehicle_details is an array and process each attachment
if (is_array($vehicle_details)) {
  
    foreach ($vehicle_details as $detail) {
       
       
        if (isset($detail['type'])) {
            
            
            $attachmentType = $detail['type']; // e.g., 'front_side'
            $fileKey = $attachmentType; // Assuming $_FILES uses the type as the key


            // Check if file exists in $_FILES and process
            if (isset($_FILES[$attachmentType])) {
            
                $attachment = $_FILES[$attachmentType];
                // print_r($attachment);
                
                // Process the attachment
                if ($attachment['error'] === UPLOAD_ERR_OK) {
                    $processed_attachment = processAttachment(
                        $s3_learning_bucket,
                        $learning_bucketName,
                        $attachment, 
                        $attachmentType, 
                        $workspace_id, 
                        $institution_id, 
                        $userid
                    );
                    if ($processed_attachment) {
                        $processed_vehicle_images[] = $processed_attachment;
                    }
                } else {
                    // Handle file upload error
                    $processed_vehicle_images[] = [
                        "type" => $attachmentType,
                        "attachment" => null
                    ];
                }
            } else {
                // Handle missing file key in $_FILES
                $processed_vehicle_images[] = [
                    "type" => $attachmentType,
                    "attachment" => null
                ];
            }
        }
    }
}

// Encode the final array into JSON after all processing
$vehicle_images_json = json_encode($processed_vehicle_images, JSON_PRETTY_PRINT);


// Output or store the final JSON




$response_data = []; // Array to hold the response data

// Validate and process insurance details
if (!empty($insurance_details)) {
    // Assuming only one set of insurance details
    $insurance = $insurance_details;
    

    $insured_on = isset($insurance['insured_on']) ? trim($insurance['insured_on']) : null;
    $insured_valid_upto = isset($insurance['insured_valid_upto']) ? trim($insurance['insured_valid_upto']) : null;
    

    if (empty($insured_on) || empty($insured_valid_upto)) {
        errorreturn("Insurance details must include insured_on and insured_valid_upto.");
    }

    $file_info = null;
        $file_key = 'insured_attachment';
        
         $insured_attachment = null;// Since only one set of details is processed

        if (isset($_FILES['insurance_details']['name']['insured_attachment']) && $_FILES['insurance_details']['error']['insured_attachment'] == UPLOAD_ERR_OK) {
            // Handle file upload
              $file = $_FILES['insurance_details'];
            //   var_Dump($file);
            $file_info = [
            'name' => $file['name']['insured_attachment'],
            'type' => $file['type']['insured_attachment'],
            'tmp_name' => $file['tmp_name']['insured_attachment'],
            'error' => $file['error']['insured_attachment'],
            'size' => $file['size']['insured_attachment'],
        ];

            // Directory path for storing uploaded files
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";

            // File details
            $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 = 25 * 1024 * 1024; // Maximum file size 25 MB

            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

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

           
            try {
            $s3_learning_bucket->putObject([
                'Bucket' => $learning_bucketName,
                'Key' => $keyName,
                'SourceFile' => $fileTmpName,

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

            $insured_attachment = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);
        } else {
             $insured_attachment = null;
        }


    // Add to response data
    $response_data['insurance_details'] = [
        'insured_on' => $insured_on,
        'insured_valid_upto' => $insured_valid_upto,
        'insured_attachment' => $file_info ? $file_info : $insured_attachment,
    ];
}

if (!empty($permit_details) ) {
    $permit = $permit_details; // Assuming only one permit detail is provided
    $permit_initial_date = isset($permit['permit_initial_date']) ? trim($permit['permit_initial_date']) : null;
    $permit_valid_upto = isset($permit['permit_valid_upto']) ? trim($permit['permit_valid_upto']) : null;

    if (empty($permit_initial_date) || empty($permit_valid_upto)) {
        errorreturn("Permit details must include permit_initial_date and permit_valid_upto.");
    }

    $file_info = null;
       
        $file_key = 'permit_attachment'; // Single instance, so using index 0
        $permit_attachment=null;
       if (isset($_FILES['permit_details']['name']['permit_attachment']) && $_FILES['permit_details']['error']['permit_attachment'] == UPLOAD_ERR_OK) {
    $file = $_FILES['permit_details'];
    $file_info = [
        'name' => $file['name']['permit_attachment'],
        'type' => $file['type']['permit_attachment'],
        'tmp_name' => $file['tmp_name']['permit_attachment'],
        'error' => $file['error']['permit_attachment'],
        'size' => $file['size']['permit_attachment'],
    ];

            // Directory path for storing uploaded files
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";

            // File details
            $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 = 25 * 1024 * 1024; // Maximum file size 25 MB

            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

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

           
            try {
            $s3_learning_bucket->putObject([
                'Bucket' => $learning_bucketName,
                'Key' => $keyName,
                'SourceFile' => $fileTmpName,

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

            $permit_attachment = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);
        } else {
           $permit_attachment=null;
        }
    

    // Add to response data
    $response_data['permit_details'] = [
        'permit_initial_date' => $permit_initial_date,
        'permit_valid_upto' => $permit_valid_upto,
        'permit_attachment' => $file_info ? $file_info : $permit_attachment,
    ];
}

// Process passing details
if (!empty($passing_details)) {
    $passing = $passing_details; // Assuming only one passing detail is provided
    $passing_initial_date = isset($passing['passing_initial_date']) ? trim($passing['passing_initial_date']) : null;
    $passing_valid_upto = isset($passing['passing_valid_upto']) ? trim($passing['passing_valid_upto']) : null;

    if (empty($passing_initial_date) || empty($passing_valid_upto)) {
        errorreturn("Passing details must include passing_initial_date and passing_valid_upto.");
    }

    $file_info = null;
        $file_key = 'passing_attachment'; // Single instance, so using index 0
        $passing_attachment=null;
       if (isset($_FILES['passing_details']['name']['passing_attachment']) && $_FILES['passing_details']['error']['passing_attachment'] == UPLOAD_ERR_OK) {
            // Handle file upload
              $file = $_FILES['passing_details'];
            $file_info = [
            'name' => $file['name']['passing_attachment'],
            'type' => $file['type']['passing_attachment'],
            'tmp_name' => $file['tmp_name']['passing_attachment'],
            'error' => $file['error']['passing_attachment'],
            'size' => $file['size']['passing_attachment'],
        ];


            // Directory path for storing uploaded files
             $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";

            // File details
            $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 = 25 * 1024 * 1024; // Maximum file size 25 MB

            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

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

           
            
            try {
            $s3_learning_bucket->putObject([
                'Bucket' => $learning_bucketName,
                'Key' => $keyName,
                'SourceFile' => $fileTmpName,

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

            $passing_attachment = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);
        } else {
           $passing_attachment=null;
        }

    // Add to response data
    $response_data['passing_details'] = [
        'passing_initial_date' => $passing_initial_date,
        'passing_valid_upto' => $passing_valid_upto,
        'passing_attachment' => $file_info ? $file_info : $passing_attachment,
    ];
}

// Process registration details
if (!empty($registration_certificate)) {
    $registration = $registration_certificate; // Assuming only one registration detail is provided
    $registration_date = isset($registration['registration_date']) ? trim($registration['registration_date']) : null;
    $registration_valid_upto = isset($registration['registration_valid_upto']) ? trim($registration['registration_valid_upto']) : null;

    if (empty($registration_date) || empty($registration_valid_upto)) {
        errorreturn("Registration details must include registration_date and registration_valid_upto.");
    }

    $file_info = null;
        $file_key = 'registration_attachment'; // Single instance, so using index 0
        $registration_attachment=null;
     if (isset($_FILES['registration_certificate']['name']['registration_attachment']) && $_FILES['registration_certificate']['error']['registration_attachment'] == UPLOAD_ERR_OK) {
            // Handle file upload
              $file = $_FILES['registration_certificate'];
            $file_info = [
            'name' => $file['name']['registration_attachment'],
            'type' => $file['type']['registration_attachment'],
            'tmp_name' => $file['tmp_name']['registration_attachment'],
            'error' => $file['error']['registration_attachment'],
            'size' => $file['size']['registration_attachment'],
        ];

            // Directory path for storing uploaded files
             $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";

            // File details
            $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 = 25 * 1024 * 1024; // Maximum file size 25 MB

            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

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

           
            try {
            $s3_learning_bucket->putObject([
                'Bucket' => $learning_bucketName,
                'Key' => $keyName,
                'SourceFile' => $fileTmpName,

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

            $registration_attachment = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);
        } else {
            $registration_attachment=null;
        }


    // Add to response data
    $response_data['registration_certificate'] = [
        'registration_date' => $registration_date,
        'registration_valid_upto' => $registration_valid_upto,
        'registration_attachment' => $file_info ? $file_info : $registration_attachment,
    ];
}

// Process road tax details
if (!empty($road_tax_details) ) {
    $road_tax = $road_tax_details; // Assuming only one road tax detail is provided
    $road_tax_initial_date = isset($road_tax['road_tax_initial_date']) ? trim($road_tax['road_tax_initial_date']) : null;
    $road_tax_valid_upto = isset($road_tax['road_tax_valid_upto']) ? trim($road_tax['road_tax_valid_upto']) : null;


    if (empty($road_tax_initial_date) || empty($road_tax_valid_upto)) {
        errorreturn("Road tax details must include road_tax_initial_date and road_tax_valid_upto.");
    }

    $file_info = null;
    
        $file_key = 'road_tax_attachment'; // Single instance, so using index 0
        
         $road_tax_attachment=null;
    if (isset($_FILES['road_tax']['name']['road_tax_attachment']) && $_FILES['road_tax']['error']['road_tax_attachment'] == UPLOAD_ERR_OK) {
            // Handle file upload
              $file = $_FILES['road_tax'];
            $file_info = [
            'name' => $file['name']['road_tax_attachment'],
            'type' => $file['type']['road_tax_attachment'],
            'tmp_name' => $file['tmp_name']['road_tax_attachment'],
            'error' => $file['error']['road_tax_attachment'],
            'size' => $file['size']['road_tax_attachment'],
        ];

            // Directory path for storing uploaded files
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";

            // File details
            $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 = 25 * 1024 * 1024; // Maximum file size 25 MB

            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);

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

           
            try {
            $s3_learning_bucket->putObject([
                'Bucket' => $learning_bucketName,
                'Key' => $keyName,
                'SourceFile' => $fileTmpName,

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

            $road_tax_attachment = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);
        } else {
           $road_tax_attachment=null;
        }
    

    // Add to response data
    $response_data['road_tax_details'] = [
        'road_tax_initial_date' => $road_tax_initial_date,
        'road_tax_valid_upto' => $road_tax_valid_upto,
        'road_tax_attachment' => $file_info ? $file_info : $road_tax_attachment,
    ];
}

  $insert_bus_sql = "INSERT INTO buses (
    institution_id, branch_id, bus_number, capacity, vehicle_images,meter_readings,route_id, 
    manufacturer, model_year, year_of_purchase, insured_on, insured_valid_upto, insured_attachment, 
    permit_initial_date, permit_valid_upto, permit_attachment, passing_initial_date, passing_valid_upto, 
    passing_attachment, registration_date, registration_valid_upto, registration_attachment, 
    road_tax_initial_date, road_tax_valid_upto, road_tax_attachment, added_by, date_created, time_created, status
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";


$stmt = $conn_rjllearning_specific->prepare($insert_bus_sql);

$stmt->execute([
    $institution_id,
    $branch_id,
    $bus_number,
    $capacity,
    $vehicle_images_json,
    $meter_readings,
    $route_id,
    $manufacturer,
    $model_year,
    $year_of_purchase,
    $insured_on,
    $insured_valid_upto,
    $insured_attachment,
    $permit_initial_date,
    $permit_valid_upto,
    $permit_attachment,
    $passing_initial_date,
    $passing_valid_upto,
    $passing_attachment,
    $registration_date,
    $registration_valid_upto,
    $registration_attachment,
    $road_tax_initial_date,
    $road_tax_valid_upto,
    $road_tax_attachment,
    $username,
    date('Y-m-d'),
    time(),
    1
]);
   


    $bus_id = $conn_rjllearning_specific->lastInsertId();
    successreturn(array('id' => $bus_id, 'successmsg' => "Successfully stored vehicle."));
}

if ($postdata['function_type'] == 'alter_bus') {
   $busses_id = isset($postdata['bus_id']) ? $postdata['bus_id'] : errorreturn("Bus ID is required.");
    
    if (!empty($insurance_details)) {
        // Assuming only one set of insurance details
        $insurance = $insurance_details;
        $insured_on = isset($insurance['insured_on']) ? trim($insurance['insured_on']) : null;
        $insured_valid_upto = isset($insurance['insured_valid_upto']) ? trim($insurance['insured_valid_upto']) : null;
        $remove_bool_insurance_details = isset($insurance['remove_bool_insurance_details']) ? (int) $insurance['remove_bool_insurance_details'] : 0;
    
        // Validate required fields
        if (empty($insured_on) || empty($insured_valid_upto)) {
            errorreturn("Insurance details must include insured_on and insured_valid_upto.");
        }
    
        // Fetch existing attachment from the database
        $sql_image = $conn_rjllearning_specific->prepare("SELECT insured_attachment 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['insured_attachment'] ?? null;
    
        // Step 2: Check if a new file is uploaded
        $new_file_uploaded = isset($_FILES['insurance_details']['name']['insured_attachment']) && $_FILES['insurance_details']['error']['insured_attachment'] == UPLOAD_ERR_OK;
    
        // Remove existing attachment if remove_bool_insurance_details = 1 OR a new file is uploaded
        if (($remove_bool_insurance_details || $new_file_uploaded) && $existing_attachment) {
            $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);
            $conn_rjllearning_specific->prepare("UPDATE buses SET insured_attachment = NULL WHERE id = ? AND institution_id = ?")->execute([$busses_id, $institution_id]);
            $existing_attachment = null;
        }
    
        // Handle new file upload if present
        $insured_attachment = null;
        if ($new_file_uploaded) {
            $file = $_FILES['insurance_details'];
            $file_info = [
                'name' => $file['name']['insured_attachment'],
                'type' => $file['type']['insured_attachment'],
                'tmp_name' => $file['tmp_name']['insured_attachment'],
                'error' => $file['error']['insured_attachment'],
                'size' => $file['size']['insured_attachment'],
            ];
    
            // Directory path for storing uploaded files
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";
    
            // File details
            $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 = 25 * 1024 * 1024; // Maximum file size 25 MB
    
            // Check file validation
            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    
            $keyName = $directoryPathMain . uniqid('', true) . "_" . time() . '.' . $file_extension;
    
            // Upload to S3
            try {
                $s3_learning_bucket->putObject([
                    'Bucket' => $learning_bucketName,
                    'Key' => $keyName,
                    'SourceFile' => $fileTmpName,
                ]);
            } catch (Exception $e) {
                errorreturn($e->getMessage());
            }
    
            $insured_attachment = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);
    
            // Update the database with the new attachment
            $sql_users = "UPDATE buses SET insured_attachment = ? WHERE id = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql_users)->execute([$insured_attachment, $busses_id, $institution_id]);
        }
    
        // Add to response data
        $response_data['insurance_details'] = [
            'insured_on' => $insured_on,
            'insured_valid_upto' => $insured_valid_upto,
            'insured_attachment' => $insured_attachment ?? null,
        ];
    }
    
    
    if (!empty($permit_details)) {
        // Assuming only one set of permit details
        $permit = $permit_details;
        $permit_initial_date = isset($permit['permit_initial_date']) ? trim($permit['permit_initial_date']) : null;
        $permit_valid_upto = isset($permit['permit_valid_upto']) ? trim($permit['permit_valid_upto']) : null;
        $remove_bool_permit_details = isset($permit['remove_bool_permit_details']) ? (int) $permit['remove_bool_permit_details'] : 0;
    
        // Validate required fields
        if (empty($permit_initial_date) || empty($permit_valid_upto)) {
            errorreturn("Permit details must include permit_initial_date and permit_valid_upto.");
        }
    
        // Fetch existing attachment from the database
        $sql_image = $conn_rjllearning_specific->prepare("SELECT permit_attachment 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['permit_attachment'] ?? null;
    
        // Check if a new file is uploaded
        $new_file_uploaded = isset($_FILES['permit_details']['name']['permit_attachment']) && $_FILES['permit_details']['error']['permit_attachment'] == UPLOAD_ERR_OK;
    
        // Remove existing attachment if remove_bool_permit_details = 1 OR a new file is uploaded
        if (($remove_bool_permit_details || $new_file_uploaded) && $existing_attachment) {
            $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);
            $conn_rjllearning_specific->prepare("UPDATE buses SET permit_attachment = NULL WHERE id = ? AND institution_id = ?")->execute([$busses_id, $institution_id]);
            $existing_attachment = null;
        }
    
        // Handle new file upload if present
        $permit_attachment = null;
        if ($new_file_uploaded) {
            $file = $_FILES['permit_details'];
            $file_info = [
                'name' => $file['name']['permit_attachment'],
                'type' => $file['type']['permit_attachment'],
                'tmp_name' => $file['tmp_name']['permit_attachment'],
                'error' => $file['error']['permit_attachment'],
                'size' => $file['size']['permit_attachment'],
            ];
    
            // Directory path for storing uploaded files
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";
    
            // File details
            $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 = 25 * 1024 * 1024; // Maximum file size 25 MB
    
            // Check file validation
            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    
            $keyName = $directoryPathMain . uniqid('', true) . "_" . time() . '.' . $file_extension;
    
            // Upload to S3
            try {
                $s3_learning_bucket->putObject([
                    'Bucket' => $learning_bucketName,
                    'Key' => $keyName,
                    'SourceFile' => $fileTmpName,
                ]);
            } catch (Exception $e) {
                errorreturn($e->getMessage());
            }
    
            // Prepare attachment data for database
            $permit_attachment = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);
    
            // Update the database with the new attachment
            $sql_users = "UPDATE buses SET permit_attachment = ? WHERE id = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql_users)->execute([$permit_attachment, $busses_id, $institution_id]);
        }
    
        // Add to response data
        $response_data['permit_details'] = [
            'permit_initial_date' => $permit_initial_date,
            'permit_valid_upto' => $permit_valid_upto,
            'permit_attachment' => $permit_attachment ?? null,
        ];
    }
    
    
    
    if (!empty($passing_details)) {
        // Assuming only one set of passing details is provided
        $passing = $passing_details; 
        $passing_initial_date = isset($passing['passing_initial_date']) ? trim($passing['passing_initial_date']) : null;
        $passing_valid_upto = isset($passing['passing_valid_upto']) ? trim($passing['passing_valid_upto']) : null;
        $remove_bool_passing_details = isset($passing['remove_bool_passing_details']) ? (int) $passing['remove_bool_passing_details'] : 0;
    
        // Validate required fields
        if (empty($passing_initial_date) || empty($passing_valid_upto)) {
            errorreturn("Passing details must include passing_initial_date and passing_valid_upto.");
        }
    
        // Fetch existing attachment from the database
        $sql_image = $conn_rjllearning_specific->prepare("SELECT passing_attachment 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['passing_attachment'] ?? null;
    
        // Step 2: Check if a new file is uploaded
        $new_file_uploaded = isset($_FILES['passing_details']['name']['passing_attachment']) && $_FILES['passing_details']['error']['passing_attachment'] == UPLOAD_ERR_OK;
    
        // Handle the removal of the existing attachment if remove_bool_passing_details = 1 OR a new file is uploaded
        if (($remove_bool_passing_details || $new_file_uploaded) && $existing_attachment) {
            $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);
            $conn_rjllearning_specific->prepare("UPDATE buses SET passing_attachment = NULL WHERE id = ? AND institution_id = ?")->execute([$busses_id, $institution_id]);
            $existing_attachment = null;
        }
    
        // Handle new file upload if present
        $passing_attachment = null;
        if ($new_file_uploaded) {
            $file = $_FILES['passing_details'];
            $file_info = [
                'name' => $file['name']['passing_attachment'],
                'type' => $file['type']['passing_attachment'],
                'tmp_name' => $file['tmp_name']['passing_attachment'],
                'error' => $file['error']['passing_attachment'],
                'size' => $file['size']['passing_attachment'],
            ];
    
            // Directory path for storing uploaded files
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";
    
            // File details
            $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));
    
            // 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 uploaded file
            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    
            // Generate unique key for S3 upload
            $keyName = $directoryPathMain . uniqid('', true) . "_" . time() . '.' . $file_extension;
    
            // Upload to S3
            try {
                $s3_learning_bucket->putObject([
                    'Bucket' => $learning_bucketName,
                    'Key' => $keyName,
                    'SourceFile' => $fileTmpName,
                ]);
            } catch (Exception $e) {
                errorreturn($e->getMessage());
            }
    
            // Prepare the attachment data
            $passing_attachment = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);
    
            // Update the database with the new attachment
            $sql_update = "UPDATE buses SET passing_attachment = ? WHERE id = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql_update)->execute([$passing_attachment, $busses_id, $institution_id]);
        }
    
        // Add to response data
        $response_data['passing_details'] = [
            'passing_initial_date' => $passing_initial_date,
            'passing_valid_upto' => $passing_valid_upto,
            'passing_attachment' => $passing_attachment ?? null,
        ];
    }
    
    
    
    if (!empty($registration_certificate)) {
        // Assuming only one set of registration certificate details is provided
        $registration = $registration_certificate;
        $registration_date = isset($registration['registration_date']) ? trim($registration['registration_date']) : null;
        $registration_valid_upto = isset($registration['registration_valid_upto']) ? trim($registration['registration_valid_upto']) : null;
        $remove_bool_registration_certificate = isset($registration['remove_bool_registration_certificate']) ? (int) $registration['remove_bool_registration_certificate'] : 0;
    
        // Validate required fields
        if (empty($registration_date) || empty($registration_valid_upto)) {
            errorreturn("Registration certificate details must include registration_date and registration_valid_upto.");
        }
    
        // Fetch existing attachment from the database
        $sql_image = $conn_rjllearning_specific->prepare("SELECT registration_attachment 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['registration_attachment'] ?? null;
    
        // Check if a new file is uploaded
        $new_file_uploaded = isset($_FILES['registration_certificate']['name']['registration_attachment']) && $_FILES['registration_certificate']['error']['registration_attachment'] == UPLOAD_ERR_OK;
    
        // Remove existing attachment if remove_bool_registration_certificate = 1 OR a new file is uploaded
        if (($remove_bool_registration_certificate || $new_file_uploaded) && $existing_attachment) {
            $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);
            $conn_rjllearning_specific->prepare("UPDATE buses SET registration_attachment = NULL WHERE id = ? AND institution_id = ?")->execute([$busses_id, $institution_id]);
            $existing_attachment = null;
        }
    
        // Handle new file upload if present
        $registration_attachment = null;
        if ($new_file_uploaded) {
            $file = $_FILES['registration_certificate'];
            $file_info = [
                'name' => $file['name']['registration_attachment'],
                'type' => $file['type']['registration_attachment'],
                'tmp_name' => $file['tmp_name']['registration_attachment'],
                'error' => $file['error']['registration_attachment'],
                'size' => $file['size']['registration_attachment'],
            ];
    
            // Directory path for storing uploaded files
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";
    
            // File details
            $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));
    
            // 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 uploaded file
            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    
            // Generate unique key for S3 upload
            $keyName = $directoryPathMain . uniqid('', true) . "_" . time() . '.' . $file_extension;
    
            // Upload to S3
            try {
                $s3_learning_bucket->putObject([
                    'Bucket' => $learning_bucketName,
                    'Key' => $keyName,
                    'SourceFile' => $fileTmpName,
                ]);
            } catch (Exception $e) {
                errorreturn($e->getMessage());
            }
    
            // Prepare the attachment data
            $registration_attachment = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);
    
            // Update the database with the new attachment
            $sql_update = "UPDATE buses SET registration_attachment = ? WHERE id = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql_update)->execute([$registration_attachment, $busses_id, $institution_id]);
        }
    
        // Add to response data
        $response_data['registration_certificate'] = [
            'registration_date' => $registration_date,
            'registration_valid_upto' => $registration_valid_upto,
            'registration_attachment' => $registration_attachment ?? null,
        ];
    }
    
    
    if (!empty($road_tax_details)) {
        $tax = $road_tax_details;
        $road_tax_initial_date = isset($tax['road_tax_initial_date']) ? trim($tax['road_tax_initial_date']) : null;
        $road_tax_valid_upto = isset($tax['road_tax_valid_upto']) ? trim($tax['road_tax_valid_upto']) : null;
        $remove_bool_road_tax = isset($tax['remove_bool_road_tax']) ? (int) $tax['remove_bool_road_tax'] : 0;
    
        if (empty($road_tax_initial_date) || empty($road_tax_valid_upto)) {
            errorreturn("Road tax details must include road_tax_initial_date and road_tax_valid_upto.");
        }
    
        // Fetch existing attachment from the database
        $sql_image = $conn_rjllearning_specific->prepare("SELECT road_tax_attachment 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['road_tax_attachment'] ?? null;
    
        // Check if a new file is uploaded
        $new_file_uploaded = isset($_FILES['road_tax']['name']['road_tax_attachment']) && $_FILES['road_tax']['error']['road_tax_attachment'] == UPLOAD_ERR_OK;
    
        // Handle removal of existing attachment if `remove_bool_road_tax` is set to 1
        if ($remove_bool_road_tax && $existing_attachment) {
            $existing_file = json_decode($existing_attachment, true);
            $file_path = $existing_file['filepath'];
    
            // Delete file from AWS S3
            awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $file_path, null, null);
    
            // Remove file reference from the database
            $conn_rjllearning_specific->prepare("UPDATE buses SET road_tax_attachment = NULL WHERE id = ? AND institution_id = ?")->execute([$busses_id, $institution_id]);
    
            // Reset existing attachment after deletion
            $existing_attachment = null;
        }
    
        // Handle new file upload if present
        $road_tax_attachment = null;
        if ($new_file_uploaded) {
            $file = $_FILES['road_tax'];
            $file_info = [
                'name' => $file['name']['road_tax_attachment'],
                'type' => $file['type']['road_tax_attachment'],
                'tmp_name' => $file['tmp_name']['road_tax_attachment'],
                'error' => $file['error']['road_tax_attachment'],
                'size' => $file['size']['road_tax_attachment'],
            ];
    
            $directoryPathMain = "user_uploads/" . $workspace_id . "/" . $institution_id . "/transport/" . date('Y') . "/" . date('m') . "/";
    
            $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));
    
            // 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;
    
            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    
            $keyName = $directoryPathMain . uniqid('', true) . "_" . time() . '.' . $file_extension;
    
            try {
                $s3_learning_bucket->putObject([
                    'Bucket' => $learning_bucketName,
                    'Key' => $keyName,
                    'SourceFile' => $fileTmpName,
                ]);
            } catch (Exception $e) {
                errorreturn($e->getMessage());
            }
    
            $road_tax_attachment = json_encode(['filepath' => $keyName, 'original_name' => $file_name]);
    
            $sql_update = "UPDATE buses SET road_tax_attachment = ? WHERE id = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql_update)->execute([$road_tax_attachment, $busses_id, $institution_id]);
        }
    
        $response_data['road_tax'] = [
            'road_tax_initial_date' => $road_tax_initial_date,
            'road_tax_valid_upto' => $road_tax_valid_upto,
            'road_tax_attachment' => $road_tax_attachment ?? null,
        ];
    }

        $update_vehicle_images= updateMultipleAttachments(
            $conn_rjllearning_specific,
            $s3_learning_bucket,
            $learning_bucketName,
            $workspace_id,
            $institution_id,
            $userid,
            $busses_id,
            $vehicle_details
        );
        
        // Prepare the SQL update statement
        $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 = ?";
        
        // Prepare the statement
        $stmt = $conn_rjllearning_specific->prepare($update_bus_sql);
        
        // Execute the statement with the provided data
        $stmt->execute([
            $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,
        
            $username,
            date('Y-m-d'),
            time(),
            1,
            $busses_id,
            $institution_id
        ]);
        
        if ($stmt) {
            successreturn(['successmsg' => 'Bus details updated successfully.']);
        } else {
            errorreturn('Failed to update bus details.');
    }
        
        
}
        
        
        
        
