<?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/dashboard/dashboard_functions.php';

require_once $base_path_to_learning_resources . 'lib/student_birthdays/function.php';
require_once $base_path_to_learning_resources . 'lib/common_modules/timetable_adjustment/functions.php';

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

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

$required_fields = ['institution_id', 'branch_id', 'api_signature', 'function_type', 'jwt_token'];

foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing or empty field: " . $field);
    }
}

validateApiSignature($postdata['api_signature']);
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

if (!$jwt_validate) {
    errorreturn("Invalid JWT Token.");
}

$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

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

$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$original_teacher_id = trim($postdata['original_teacher_id']);
// $replacement_teacher_id = trim($postdata['replacement_teacher_id']);
// $lecture_id = trim($postdata['lecture_id']);
$adjustment_date = trim($postdata['adjustment_date']);
$adjustment_info = $postdata['adjustment_info'];

$current_date = date('Y-m-d'); // Get today's date in YYYY-MM-DD format

if ($adjustment_date < $current_date) {
    errorreturn("Invalid adjustment date. You can only create adjustments for today or future dates.");
}

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

if ($postdata['function_type'] === "create_timetable_adjustment") {
    create_timetable_adjustments($conn_rjllearning_specific, $institution_id, $branch_id, $original_teacher_id, $adjustment_info, $adjustment_date, $username);
}
 else {
    errorreturn("Enter a valid function type");
}

// else if ($postdata['function_type'] == "alter_timetable_adjustment") {

//     if (!isset($postdata['adjustment_id']) or !checkIfIssetAndNotEmpty($postdata['adjustment_id'])) {
//         errorreturn('Error in updating the adjustment.');
//     } else {
//         $adjustment_id = trim($postdata['adjustment_id']);
//     }

//     try {
//         // Check if the adjustment exists
//         $sql = "SELECT id FROM timetable_adjustments WHERE institution_id = ? AND id = ?";
//         $stmt_check = $conn_rjllearning_specific->prepare($sql);
//         $stmt_check->execute([$institution_id, $adjustment_id]);

//         if ($stmt_check->rowCount() == 0) {
//             errorreturn("adjustment not found.");
//         }

//         // Update the adjustment
//         $sql_update = "UPDATE timetable_adjustments SET replacement_teacher_id = ?, lecture_id = ?, adjustment_date = ?, last_modified_by = ?, last_modified_at = ? 
//                       WHERE institution_id = ? AND id = ?";
//         $stmt_update = $conn_rjllearning_specific->prepare($sql_update);
//         $stmt_update->execute([
//             $replacement_teacher_id,
//             $lecture_id,
//             $adjustment_date,
//             $username,
//             date('Y-m-d H:i:s'),
//             $institution_id,
//             $adjustment_id
//         ]);

//         successreturn([
//             'id' => $adjustment_id,
//             'successmsg' => "Adjustment updated successfully."
//         ]);
//     } catch (Exception $e) {
//         errorreturn("Error: " . $e->getMessage());
//     }
// }
