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

// Include required files
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 . 'admin_api/academic_session/functions/validate_faculty.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/functions.php';
require_once $base_path_to_learning . 'functions/common_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_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';
require_once $base_path_to_learning_resources .  'external_requests/finware_curl/student/curl_restore_left_student_finware.php';

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

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

// Validate required fields
$requiredFields = ['student_id', 'api_signature', 'function_type', 'jwt_token'];
foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Validate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract user data from JWT
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$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);

if ($postdata['function_type'] == "restore_student_enrollment") {
    try {
    // Start the transaction
    $conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    $conn_rjllearning_specific->beginTransaction();

    // Step 1: Delete the student from the `left_students` table
    $student_id = $postdata['student_id'];
    
    //get branch id of student
    $sql_branch_student = "SELECT id,branch_id,class_id,section_id FROM left_students WHERE institution_id = ? AND student_id  = ?";
    $stmt_branch_student = $conn_rjllearning_specific->prepare($sql_branch_student);
    $stmt_branch_student->execute([$institution_id, $student_id]);
    $result_students = $stmt_branch_student->fetchAll();
    if(count($result_students) != 1){
        errorreturn("Left Student Not Found.");
    }
    $branch_id = $result_students[0]['branch_id'];
    $class_info = getClass($conn_rjllearning_specific, $institution_id, $result_students[0]['class_id']);
    $section = getSection($conn_rjllearning_specific, $institution_id, $result_students[0]['section_id']);

    $sql_delete_left_students = "DELETE FROM left_students WHERE student_id = ? AND institution_id = ?";
    $stmt_delete_left_students = $conn_rjllearning_specific->prepare($sql_delete_left_students);
    $stmt_delete_left_students->execute([$student_id, $institution_id]);

    // Step 2: Reactivate the student in the `students` table
    $sql_update_students = "UPDATE students SET can_activate = ?, status = ? WHERE institution_id = ? AND id = ?";
    $conn_rjllearning_specific->prepare($sql_update_students)->execute([1, 1, $institution_id, $student_id]);

    // Step 3: Fetch the corresponding `user_id` from the `students` table
    $sql_fetch_user_id = "SELECT user_id FROM students WHERE institution_id = ? AND id = ?";
    $stmt_fetch_user_id = $conn_rjllearning_specific->prepare($sql_fetch_user_id);
    $stmt_fetch_user_id->execute([$institution_id, $student_id]);

    $result_student = $stmt_fetch_user_id->fetchAll();

    if (count($result_student) !== 1) {
        $conn_rjllearning_specific->rollBack();
        errorreturn('Unable to restore student.');
    }

    $student_userid = $result_student[0]['user_id'];

    $group_info = array("class"=>$class_info['class_name'],"section"=>$section['section_name'],"student" => $student_id);
    $branch = getBranchDetails($conn_rjllearning_specific,$branch_id,$institution_id);
    //print_r($branch);die();
    if (!empty($branch)) {
        $student_data  = array("workspace_id" => $workspace_id, "branch" => $branch, "student_data" => $group_info);
        curlRestoreLeftStudentFinware($student_data);
    }
       

    // Step 4: Reactivate the corresponding user in the `users` table
    $sql_update_users = "UPDATE users SET can_activate = ?, status = ? WHERE workspace_id = ? AND institution_id = ? AND id = ?";
    $conn_rjllearning->prepare($sql_update_users)->execute([0, 0, $workspace_id, $institution_id, $student_userid]);

    // Commit the transaction
    $conn_rjllearning_specific->commit();

    successReturn("Student enrollment restored successfully.");
} catch (PDOException $e) {
    // Rollback on error
    $conn_rjllearning_specific->rollBack();
    errorreturn("Database error: " . $e->getMessage());
} catch (Exception $e) {
    // Rollback on error
    $conn_rjllearning_specific->rollBack();
    errorreturn($e->getMessage());
}

} else {
    errorreturn("Invalid function_type.");
}
