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



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


checkIfNoPhpContentsReceive();

if (
    
    !isset($postdata['stop_names']) || !checkIfIssetAndNotEmpty($postdata['stop_names']) ||
    !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);

$stop_name = ucwords(trim($postdata['stop_names']));
$charges = isset($postdata['charges']) && !is_null($postdata['charges']) ? trim($postdata['charges']) : null;
$proximity = isset($postdata['proximity']) && !is_null($postdata['proximity']) ? trim($postdata['proximity']) : null;

 if ($charges < 0) {
        errorreturn ("Charges cannot be negative.");
    }
    


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

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

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

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

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

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

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

if ($postdata['function_type'] == 'bus_stop') {
    // Check if the stop already exists
    $check_stop_sql = "SELECT id FROM bus_stops WHERE institution_id = ? AND branch_id = ? AND stop_names = ?";
    $stmt = $conn_rjllearning_specific->prepare($check_stop_sql);
    $stmt->execute([$institution_id, $branch_id, $stop_name]);

    $existing_stop = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existing_stop) {
        errorreturn("Stop name already exists.");
    }

    // Insert new stop if it doesn't exist
    $insert_bus_sql = "INSERT INTO bus_stops (institution_id, branch_id, stop_names, proximity, charges) VALUES (?, ?, ?, ?, ?)";
    $stmt = $conn_rjllearning_specific->prepare($insert_bus_sql);
    $stmt->execute([$institution_id, $branch_id, $stop_name, $proximity, $charges]);

    $stop_id = $conn_rjllearning_specific->lastInsertId();
    successreturn(['id' => $stop_id, 'successmsg' => "Successfully added stop."]);
} else if ($postdata['function_type'] == 'delete_stop') {
    // Ensure stop_id is provided
    if (empty($postdata['stop_id'])) {
        errorreturn("Stop ID is required for deletion.");
    }

    $stop_id = $postdata['stop_id'];

    // Check if the stop exists based on stop_id
    $check_stop_sql = "SELECT id FROM bus_stops WHERE id = ? and institution_id=?";
    $stmt = $conn_rjllearning_specific->prepare($check_stop_sql);
    $stmt->execute([$stop_id,$institution_id]);

    $existing_stop = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existing_stop) {
        // Delete the existing stop
        $delete_stop_sql = "DELETE FROM bus_stops WHERE id = ? and institution_id=?";
        $stmt = $conn_rjllearning_specific->prepare($delete_stop_sql);
        $stmt->execute([$stop_id,$institution_id]);

        successreturn(['successmsg' => "Successfully deleted stop."]);
    } else {
        errorreturn("Stop ID does not exist.");
    }
} else if ($postdata['function_type'] == 'update_stop') {
    // Ensure stop_id is provided
    if (empty($postdata['stop_id'])) {
        errorreturn("Stop ID is required for update.");
    }

    // Ensure at least one field to update is provided
    if (empty($stop_name) && is_null($charges) && is_null($proximity)) {
        errorreturn("At least one field (stop_name, charges, or proximity) is required for update.");
    }

    $stop_id = $postdata['stop_id'];

    // Check if the stop exists based on stop_id
    $check_stop_sql = "SELECT id FROM bus_stops WHERE id = ?";
    $stmt = $conn_rjllearning_specific->prepare($check_stop_sql);
    $stmt->execute([$stop_id]);

    $existing_stop = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($existing_stop) {
        // Update the existing stop
        $update_stop_sql = "UPDATE bus_stops SET stop_names = COALESCE(?, stop_names), proximity = COALESCE(?, proximity), charges = COALESCE(?, charges) WHERE id = ?";
        $stmt = $conn_rjllearning_specific->prepare($update_stop_sql);
        $stmt->execute([$stop_name, $proximity, $charges, $stop_id]);

        successreturn(['successmsg' => "Successfully updated stop."]);
    } else {
        errorreturn("Stop ID does not exist.");
    }
}
