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

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

require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
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';
require_once $base_path_to_learning . 'functions/common_functions.php';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

//aws image store
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  . 'admin_api/modules/library_management/library_function.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

checkIfNoPhpContentsReceive();
// print_r($postdata);
if (
   
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or !isset($postdata['jwt_token']) or  !isset($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, ["teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $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);

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

// Check if the faculty exists
$Faculty_Codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$Faculty_Codes->execute(array($userid, $institution_id, $branch_id));
$result_faculty = $Faculty_Codes->fetch(PDO::FETCH_ASSOC);
if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}

$faculty_id = $result_faculty['id'];
$teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
$class_section_subjects  = $teacher_data['class_section_subjects'];
$class_incharge_roles = $teacher_data['class_incharge_roles'];
$staff_access_modules = $teacher_data['staff_access_modules'];
// var_dump($class_id);
$check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, null, null, null, $conn_rjllearning);
if($check_faculty_status == false){
    errorreturn("Access denied: You do not have the required permissions.");
}
function getroute($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $limit, $offset)
{
    $sql_count = "SELECT count(*) as total_rows FROM routes WHERE institution_id = ?";
    $array_params = [$institution_id];

    if ($branch_id != 'all' && $branch_id != null) {
        $sql_count .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }

    if ($search_string != null) {
        $sql_count .= " AND route_name LIKE ?";
        $array_params[] = '%' . $search_string . '%';
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $totalrows = $stmt->fetchColumn();

    // Fetching data
    $sql_session = "SELECT * FROM routes WHERE institution_id = ?";
    $array_params = [$institution_id];

    if ($branch_id != 'all' && $branch_id != null) {
        $sql_session .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }

    if ($search_string != null) {
        $sql_session .= " AND route_name LIKE ?";
        $array_params[] = '%' . $search_string . '%';
    }

    $sql_session .= " ORDER BY date_created DESC, time_created DESC";

    if ($limit != 'all') {
        $sql_session .= " LIMIT $offset, $limit";
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_session);
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll();

    $array_return = [];

    foreach ($session_rows as $rows) {
        $stop_info = [];

        $stops_name_array = json_decode($rows['stops_name'], true);

        if (is_array($stops_name_array) && count($stops_name_array) > 0) {
            $stops_name_array = array_map('intval', $stops_name_array);
            $stops_name_list = implode(',', $stops_name_array);

            $sql_stops = "SELECT * FROM bus_stops WHERE institution_id = ? AND id IN ($stops_name_list)";
            $stmt_stops = $conn_rjllearning_specific->prepare($sql_stops);
            $stmt_stops->execute([$institution_id]);
            $stops_name_rows = $stmt_stops->fetchAll();

            foreach ($stops_name_rows as $row) {
                $stop_info[] = [
                    'stop_id' => $row['id'],
                    'stop_name' => ucwords($row['stop_names'])
                ];
            }
        } else {
            error_log("Invalid or empty stops_name for route ID: " . $rows['id']);
        }

        // Fetch branch info
        $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $rows['branch_id']);

        // Fetch staff info
        $staff_ids = [
            'driver_id' => $rows['driver_id'],
            'conductor_id' => $rows['conductor_id'],
            'incharge_id' => $rows['incharge_id']
        ];

        $staff_details = [];

        foreach ($staff_ids as $role => $staff_id) {
            if (!empty($staff_id)) {
                $sql_staff = "SELECT id, name FROM faculty_info WHERE institution_id = ? AND id = ?";
                $stmt_staff = $conn_rjllearning_specific->prepare($sql_staff);
                $stmt_staff->execute([$institution_id, $staff_id]);
                $staff_info = $stmt_staff->fetch();

                $staff_details[$role] = $staff_info ? [
                    'id' => $staff_info['id'],
                    'name' => $staff_info['name']
                ] : null;
            } else {
                $staff_details[$role] = null;
            }
        }

        // Add route info
        $array_return[] = [
            'route_id' => $rows['id'],
            'route_name' => $rows['route_name'],
            'institution_id' => $rows['institution_id'],
            'branch' => $branch,
            'bus_driver' => $staff_details['driver_id'],
            'bus_conductor' => $staff_details['conductor_id'],
            'bus_incharge' => $staff_details['incharge_id'],
            'bus_stops' => $stop_info
        ];
    }

    if (empty($array_return)) {
        errorreturn("No data found.");
    }

    $maxreach = ($limit != 'all' && count($session_rows) < $limit) ? 1 : 0;

    return [
        'total_rows' => $totalrows,
        'routes_info' => $array_return,
        'maxreach' => $maxreach
    ];
}


if ($postdata['function_type'] == "fetch_route") {
    
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }
    

    if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }


    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = getroute($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $limit, $offset);
        successreturn($success);
    } else {
        $success['data'] = getroute($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $limit, null);
        successreturn($success);
    }
}
