<?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 . "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 . "vendor/autoload.php";

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

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

checkIfNoPhpContentsReceive();

$required_fields = ['institution_id', 'branch_id', 'class_id', 'section_id', '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;
$name = $jwt_validate->data->name;

$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$class_id = trim($postdata['class_id']);
$section_id = trim($postdata['section_id']);
$student_bus_info = $postdata['student_bus_info'];

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'], $institution_id, $branch_id);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}
$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

$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.");
}

if ($postdata['function_type'] === "students_stops") {
    try {
        $student_ids = [];
        $bus_ids = [];
        $route_ids = [];
        $stop_ids = [];

        foreach ($student_bus_info as $student_info) {
            $student_ids[] = $student_info['student_id'];
            if (!in_array($student_info['bus_id'], $bus_ids)) {
                $bus_ids[] = $student_info['bus_id'];
            }
            if (!in_array($student_info['route_id'], $route_ids)) {
                $route_ids[] = $student_info['route_id'];
            }
            if (!in_array($student_info['stop_id'], $stop_ids)) {
                $stop_ids[] = $student_info['stop_id'];
            }
        }
        

        // Validate student IDs
        if (!empty($student_ids)) {
            $placeholders = implode(',', array_fill(0, count($student_ids), '?'));
            $sql_codes = $conn_rjllearning_specific->prepare("SELECT COUNT(*) AS total FROM students WHERE id IN ('" . implode("', '", $student_ids) . "') AND institution_id = ? and branch_id = ?");
            // $student_id_params = array_merge($student_ids, [$institution_id]);
            $sql_codes->execute(array($institution_id, $branch_id));
            $result = $sql_codes->fetch(PDO::FETCH_ASSOC)['total'];
            if ($result != count($student_ids)) {
                errorreturn("Some student IDs were not found.");
            }
        }

        // Validate bus IDs
        if (!empty($bus_ids)) {
            $placeholders = implode(',', array_fill(0, count($bus_ids), '?'));
            $sql_codes = $conn_rjllearning_specific->prepare("SELECT COUNT(*) AS total FROM buses WHERE id IN ('" . implode(
                "', '",
                $bus_ids
            ) . "') AND institution_id = ? and branch_id = ?");
            // $bus_id_params = array_merge($bus_ids, [$institution_id]);
            $sql_codes->execute(array($institution_id, $branch_id));
            $result = $sql_codes->fetch(PDO::FETCH_ASSOC)['total'];
            if ($result != count($bus_ids)) {
                errorreturn("Some bus IDs were not found.");
            }
        }

        // Validate route IDs
        if (!empty($route_ids)) {
            $placeholders = implode(',', array_fill(0, count($route_ids), '?'));
            $sql_codes = $conn_rjllearning_specific->prepare("SELECT COUNT(*) AS total FROM routes WHERE id IN ('" . implode(
                "', '",
                $route_ids
            ) . "') AND institution_id = ? and branch_id = ?");
            // $route_ids_params = array_merge($route_ids, [$institution_id]);
            $sql_codes->execute(array($institution_id, $branch_id));
            $result = $sql_codes->fetch(PDO::FETCH_ASSOC)['total'];
            if ($result != count($route_ids)) {
                errorreturn("Some route IDs were not found.");
            }
        }

        // Validate stop IDs
        if (!empty($stop_ids)) {
            $placeholders = implode(',', array_fill(0, count($stop_ids), '?'));
            $sql_codes = $conn_rjllearning_specific->prepare("SELECT COUNT(*) AS total FROM bus_stops WHERE id IN ('" . implode(
                "', '",
                $stop_ids
            ) . "') AND institution_id = ? and branch_id = ?");
            // $stop_ids_params = array_merge($stop_ids, [$institution_id]);
            $sql_codes->execute(array($institution_id, $branch_id));
            $result = $sql_codes->fetch(PDO::FETCH_ASSOC)['total'];
            if ($result != count($stop_ids)) {
                errorreturn("Some stop IDs were not found.");
            }
        }

        // Process student stops
        foreach ($student_bus_info as $student_info) {
            $student_id = $student_info['student_id'];
            $bus_id = $student_info['bus_id'];
            $route_id = $student_info['route_id'];
            $stop_id = $student_info['stop_id'];

            // Validate that the student exists
            // $student_query = "SELECT id FROM students WHERE id = ? AND institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ?";
            // $stmt_student = $conn_rjllearning_specific->prepare($student_query);
            // $stmt_student->execute([$student_id, $institution_id, $branch_id, $class_id, $section_id]);

            // if ($stmt_student->rowCount() === 0) {
            //     errorreturn("Invalid student ID: $student_id for the provided institution_id, branch_id, class_id, and section_id.");
            //     continue;
            // }

            // $bus_query = "SELECT id FROM buses WHERE id = ? AND route_id = ?";
            // $stmt_bus = $conn_rjllearning_specific->prepare($bus_query);
            // $stmt_bus->execute([$bus_id, $route_id]);

            // if ($stmt_bus->rowCount() === 0) {
            //     errorreturn("Invalid bus_id: $bus_id or route_id: $route_id.");
            //     continue;
            // }

            // $route_query = "SELECT stops_name FROM routes WHERE id = ?";
            // $stmt_route = $conn_rjllearning_specific->prepare($route_query);
            // $stmt_route->execute([$route_id]);
            // $route = $stmt_route->fetch();

            // if ($route) {
            //     $stops_name = json_decode($route['stops_name'], true);
            //     if (!in_array($stop_id, $stops_name)) {
            //         errorreturn("Invalid stop_id: $stop_id for the selected route_id: $route_id.");
            //         continue;
            //     }
            // } else {
            //     errorreturn("Invalid route_id: $route_id.");
            //     continue;
            // }

            $existing_stop_query = "SELECT id, bus_id, route_id, stop_id FROM student_stops WHERE student_id = ? AND institution_id = ? AND branch_id = ? AND class_id = ? AND section_id = ?";
            $stmt_existing_stop = $conn_rjllearning_specific->prepare($existing_stop_query);
            $stmt_existing_stop->execute([$student_id, $institution_id, $branch_id, $class_id, $section_id]);
            $existing_stop = $stmt_existing_stop->fetch();

            $current_time = date('Y-m-d H:i:s');
            if ($stmt_existing_stop->rowCount() > 0) {
                if ($existing_stop['bus_id'] != $bus_id || $existing_stop['route_id'] != $route_id || $existing_stop['stop_id'] != $stop_id) {
                    $update_query = "UPDATE student_stops 
                    SET bus_id = ?, route_id = ?, stop_id = ?, last_modified_by = ?, last_modified_at = ?
                    WHERE institution_id = ? AND branch_id = ? AND student_id = ? AND class_id = ? AND section_id = ?";
                    $stmt_update = $conn_rjllearning_specific->prepare($update_query);
                    $stmt_update->execute([$bus_id, $route_id, $stop_id, $username, $current_time, $institution_id, $branch_id, $student_id, $class_id, $section_id]);
                }
                //  else {
                //     errorreturn("No changes were made.");
                //     continue;
                // }
            } else {
                $insert_query = "INSERT INTO student_stops (institution_id, branch_id, student_id, class_id, section_id, bus_id, route_id, stop_id, created_by, created_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt_insert = $conn_rjllearning_specific->prepare($insert_query);
                $stmt_insert->execute([$institution_id, $branch_id, $student_id, $class_id, $section_id, $bus_id, $route_id, $stop_id, $username, $current_time]);
            }
        }

        successreturn("Student's stop information updated successfully.");
    } catch (Exception $e) {
        errorreturn("Error while processing student stop information: " . $e->getMessage());
    }
} else {
    errorreturn("Invalid function_type.");
}
