<?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";
require_once $base_path_to_learning_resources . "lib/validate_function.php";
require_once $base_path_to_learning . "user_management/authenticate.php";
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning_resources . "includes/specific_db_config.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "user_management/functions/functions.php";
// require_once $base_path_to_learning ."admin_api/modules/transportation/buses/function.php";

$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

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

// Specific DB connection
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;
$name = $jwt_validate->data->name;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;
$bus_id = trim($postdata['bus_id']);

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

$academicSessionId = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academicSessionId) {
    errorreturn("Invalid institution_id");
}

$isBranchClassSubjectValid = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, null, null, $institution_id);
if (!$isBranchClassSubjectValid) {
    errorreturn("Invalid branch_id.");
}

function processAttachment($attachment)
{
    if ($attachment != null && !is_array($attachment)) {
        $data_attachment = json_decode($attachment, true);
        if (is_array($data_attachment) && isset($data_attachment['filepath'])) {
            $filepath = $data_attachment['filepath'];
            $originalName = $data_attachment['original_name'];
            $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filepath);
            return array("filepath" => $aws_attachment, "name" => $originalName);
        }
    }
    return null;
}

function getRouteDetails($conn_rjllearning_specific, $route_id) {
    $sql = "SELECT id, route_name FROM routes WHERE id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$route_id]);
    $route = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$route) {
        return null; // or handle with an error message if needed
    }

    return [
        "id" => $route['id'],
        "name" => $route['route_name']
    ];
}

function getRouteStops($conn_rjllearning_specific, $route_id) {
    // Step 1: Fetch the stops_name (IDs) for the given route from the routes table
    $sql = "SELECT stops_name FROM routes WHERE id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$route_id]);
    $route = $stmt->fetch();

    if (!$route) {
        return null; 
    }

    $stops_ids = explode(',', $route['stops_name']); // Split the comma-separated IDs into an array

    // Step 2: Fetch stop names for each stop ID from the bus_stops table
    $placeholders = implode(',', array_fill(0, count($stops_ids), '?'));
    $sqlStops = "SELECT id, stop_names FROM bus_stops WHERE id IN ($placeholders)";
    $stmtStops = $conn_rjllearning_specific->prepare($sqlStops);
    $stmtStops->execute($stops_ids);
    $stops = $stmtStops->fetchAll();

    // Step 3: Format the response
    $stopsArray = [];
    foreach ($stops as $stop) {
        $stopsArray[] = [
            'stop_id' => $stop['id'],
            'stop_name' => $stop['stop_names'],
        ];
    }

    return $stopsArray;
}

function processVehicleImages($vehicle_images)
{
    $processed_images = [];
    if ($vehicle_images != null) {
        $data_vehicle_images = json_decode($vehicle_images, true);

        if (is_array($data_vehicle_images)) {
            foreach ($data_vehicle_images as $image) {
                // Debugging output
                if (is_string($image)) {
                    $image = json_decode($image, true); // Decode each JSON string if needed
                }

                if (isset($image['filepath'], $image['original_name'], $image['type'])) {
                    $filePath = $image['filepath'];
                    $originalName = $image['original_name'];
                    $type = $image['type'];

                    // Map the type to the corresponding origin
                    $origin = '';
                    switch ($type) {
                        case 'front_side':
                            $origin = 'Front';
                            break;
                        case 'back_side':
                            $origin = 'Back';
                            break;
                        case 'left_side':
                            $origin = 'Left';
                            break;
                        case 'right_side':
                            $origin = 'Right';
                            break;
                    }

                    // Generate the AWS attachment link
                    $aws_attachment = displayFileFromS3($GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName'], $filePath);

                    // Add processed image with origin
                    $processed_images[] = array(
                        "filepath" => $aws_attachment,
                        "name" => $originalName,
                        "type" => $type,
                        "origin" => $origin
                    );
                }
            }
        }
    }
    return $processed_images;
}

function getspecific_bus_details($conn_rjllearning_specific, $institution_id, $branch_id, $bus_id)
{
    $response = [];

    $sql = "SELECT * FROM buses WHERE id = ? AND institution_id = ? AND branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$bus_id, $institution_id, $branch_id]);
    $bus_detail = $stmt->fetch();

    if (!$bus_detail) {
        errorreturn("No Bus found.");
    }


    $final_insured_attachment = processAttachment($bus_detail['insured_attachment']);
    $final_permit_attachment = processAttachment($bus_detail['permit_attachment']);
    $final_passing_attachment = processAttachment($bus_detail['passing_attachment']);
    $final_registration_attachment = processAttachment($bus_detail['registration_attachment']);
    $final_road_tax_attachment = processAttachment($bus_detail['road_tax_attachment']);


    $branch_info  = getBranchInfo($conn_rjllearning_specific, $institution_id, $bus_detail['branch_id']);
    $processed_vehicle_images = processVehicleImages($bus_detail['vehicle_images']);

    $current_date = new DateTime();

    $insurance_expiry_date = new DateTime($bus_detail['insured_valid_upto']);
    $remaining_days = $insurance_expiry_date > $current_date ? $insurance_expiry_date->diff($current_date)->days : "Expired";

    $passing_expiry_date = new DateTime($bus_detail['passing_valid_upto']);
    $passing_remaining_days = $passing_expiry_date > $current_date ? $passing_expiry_date->diff($current_date)->days : "Expired";

    $permit_expiry_date = new DateTime($bus_detail['permit_valid_upto']);
    $permit_remaining_days = $permit_expiry_date > $current_date ? $permit_expiry_date->diff($current_date)->days : "Expired";

    $rc_expiry_date = new DateTime($bus_detail['registration_valid_upto']);
    $rc_remaining_days = $rc_expiry_date > $current_date ? $rc_expiry_date->diff($current_date)->days : "Expired";

    $roadtax_expiry_date = new DateTime($bus_detail['road_tax_valid_upto']);
    $roadtax_remaining_days = $roadtax_expiry_date > $current_date ? $roadtax_expiry_date->diff($current_date)->days : "Expired";

    $insurance_details = [
        'insured_on' => $bus_detail['insured_on'],
        'insured_valid_upto' => $bus_detail['insured_valid_upto'],
        'insured_attachment' => $final_insured_attachment,
        'insurance_remaining_days' => $remaining_days,
    ];

    $permit_details = [
        'permit_initial_date' => $bus_detail['permit_initial_date'],
        'permit_valid_upto' => $bus_detail['permit_valid_upto'],
        'permit_attachment' => $final_permit_attachment,
        'permit_remaining_days' => $permit_remaining_days,
    ];

    $passing_details = [
        'passing_initial_date' => $bus_detail['passing_initial_date'],
        'passing_valid_upto' => $bus_detail['passing_valid_upto'],
        'passing_attachment' => $final_passing_attachment,
        'passing_remaining_days' => $passing_remaining_days,
    ];

    $registration_details = [
        'registration_date' => $bus_detail['registration_date'],
        'registration_valid_upto' => $bus_detail['registration_valid_upto'],
        'registration_attachment' => $final_registration_attachment,
        'rc_remaining_days' => $rc_remaining_days,
    ];
    
    $road_tax_details = [
        'road_tax_initial_date' => $bus_detail['road_tax_initial_date'],
        'road_tax_valid_upto' => $bus_detail['road_tax_valid_upto'],
        'road_tax_attachment' => $final_road_tax_attachment,
        'roadtax_remaining_days' => $roadtax_remaining_days,
    ];
    
    $route_info = getRouteDetails($conn_rjllearning_specific, $bus_detail['route_id']);

    $stops_info = getRouteStops($conn_rjllearning_specific, $bus_detail['route_id']);
    
    $response = [
        'bus_id' => $bus_detail['id'],
        'institution_id' => $bus_detail['institution_id'],
        'branch_id' => $branch_info,
        'bus_number' => $bus_detail['bus_number'],
        'manufacturer' => $bus_detail['manufacturer'],
        'model_year' => $bus_detail['model_year'],
        'year_of_purchase' => $bus_detail['year_of_purchase'],
        'capacity' => $bus_detail['capacity'],
        'route_info' => $route_info,
        'stops_info' => $stops_info,
        'meter_readings' => $bus_detail['meter_readings'],
        // 'vehicle_images' => json_decode($bus_detail['vehicle_images'], true),
        'insurance_details' => $insurance_details,
        'permit_details' => $permit_details,
        'passing_details' => $passing_details,
        'registration_certificate' => $registration_details,
        'road_tax' => $road_tax_details,
        'added_by' => $bus_detail['added_by'],
        'date_created' => $bus_detail['date_created'],
        'time_created' => $bus_detail['time_created'],
        'status' => $bus_detail['status'],
        'vehicle_details' => $processed_vehicle_images
    ];
    return $response;
}

if ($postdata['function_type'] == "fetch_specific_bus_detail") {
    $response = getspecific_bus_details($conn_rjllearning_specific, $institution_id, $branch_id, $bus_id);
    successreturn($response);
} else {
    errorreturn("Invalid function type.");
}
