<?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";


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


checkIfNoPhpContentsReceive();

if (
    
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], 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';
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);

$route_name = ucwords(trim($postdata['route_name']));
$stops_name = $postdata['stops_name'];

$driver_id = isset($postdata['driver_id']) ? intval($postdata['driver_id']) : null;
$conductor_id = isset($postdata['conductor_id']) ? intval($postdata['conductor_id']) : null;
$incharge_id = isset($postdata['incharge_id']) ? intval($postdata['incharge_id']) : null;

$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 validateStaff_Id($conn_rjllearning_specific, $staff_id, $required_group_name, $institution_id, $branch_id)
// {
//     if ($staff_id === null) {
//         return; // Skip validation if the ID is null
//     }

//     // SQL query to join staff_details and staff_groups
//     $sql = "SELECT sd.id, sg.group_name 
//             FROM staff_details sd 
//             JOIN staff_groups sg ON sd.group_id = sg.id 
//             WHERE sd.id = ? 
//             AND sd.institution_id = ? 
//             AND sd.branch_id = ?";

//     $stmt = $conn_rjllearning_specific->prepare($sql);
//     $stmt->execute([$staff_id, $institution_id, $branch_id]);
//     $result = $stmt->fetch(PDO::FETCH_ASSOC);

//     // Debugging output

//     if (!$result || strtolower($result['group_name']) !== strtolower($required_group_name)) {
//         errorreturn("Invalid $required_group_name ID for this institution or branch");
//     }
// }


// validateStaff_Id($conn_rjllearning_specific, $driver_id, 'driver', $institution_id, $branch_id);
// validateStaff_Id($conn_rjllearning_specific, $conductor_id, 'conductor', $institution_id, $branch_id);
// validateStaff_Id($conn_rjllearning_specific, $incharge_id, 'bus_incharge', $institution_id, $branch_id);

// Assuming route_name is coming from post data
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);

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


// Stops validation
if ($stops_name !== 'all') {
    // Ensure stops_name is an array of integers
    if (!is_array($stops_name) || count($stops_name) <= 0) {
        errorreturn("Select at least one stop.");
    }

    // Convert all values in stops_name to integers
    $stops_name = array_map('intval', $stops_name);

    // Count the number of stop IDs
    $count_ids = count($stops_name);

    // Prepare the SQL query to validate the stop IDs
    $sql_codes = $conn_rjllearning_specific->prepare(
        "SELECT COUNT(*) as total FROM bus_stops WHERE id IN (" . implode(",", array_fill(0, $count_ids, "?")) . ") AND institution_id=?"
    );
    $sql_codes->execute(array_merge($stops_name, [$institution_id]));
    $result_branch = $sql_codes->fetchAll()[0]['total'];

    if ($result_branch != $count_ids) {
        errorreturn("Some stops not found.");
    }

    // Store stops_name as a JSON-encoded string with integer values
    $json_stops_names = json_encode($stops_name);
} else {
    // If stops_name is 'all', store it as a JSON-encoded string with the value 'all'
    $json_stops_names = json_encode([$stops_name]);
}

// Route creation process
if ($postdata['function_type'] == "create_route") {
    try {
        // Insert new route
        $sql = "INSERT INTO routes (institution_id, branch_id, route_name, stops_name, added_by, date_created, time_created, status, driver_id, conductor_id, incharge_id) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array(
            $institution_id,
            $branch_id,
            $route_name,
            $json_stops_names,
            $username,
            date('Y-m-d'),
            date('H:i:s'),
            1,
            $driver_id,
            $conductor_id,
            $incharge_id
        ));
    } catch (Exception $e) {
        errorreturn("Error: " . $e->getMessage());
    }

    $id = $conn_rjllearning_specific->lastInsertId();
    successreturn(array('id' => $id, 'successmsg' => "Route successfully added."));
} else if ($postdata['function_type'] == "alter_route") {
    // Check if route_id is provided and not empty
    if (!isset($postdata['route_id']) || !checkIfIssetAndNotEmpty($postdata['route_id'])) {
        errorreturn('route_id does not exist.');
    } else {
        $route_id = trim($postdata['route_id']);
    }

    // Update the existing route
    $sql_users = "UPDATE routes 
                  SET route_name = ?, stops_name = ?, driver_id = ?, conductor_id = ?, incharge_id = ? 
                  WHERE id = ? AND institution_id = ? AND branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql_users);
    
    try {
        $stmt->execute(array(
            $route_name,
            $json_stops_names,
            $driver_id,
            $conductor_id,
            $incharge_id,
            $route_id,
            $institution_id,
            $branch_id
        ));

        // Regardless of whether any rows were affected, return success
        successreturn("Route updated successfully.");

    } catch (Exception $e) {
        errorreturn("Error updating route: " . $e->getMessage());
    }
}
