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

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_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . 'admin_api/modules/students/student_functions.php';
require_once $base_path_to_learning_resources . 'lib/cron_jobs/function/function.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 . 'user_management/faculty/functions.php';

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

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

// Validate required fields
$requiredFields = ['faculty_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;

if ($role == 'principal' or $role == 'teacher') {
    $institution_id = $jwt_validate->data->institution_id;
    $branch_id = $jwt_validate->data->branch_id;
}

if ($role == 'admin' or $role == 'superadmin') {
    if (
        !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])
    ) {
        errorreturn("All fields are required.");
    } else {
        $institution_id = $postdata['institution_id'];
    }
}

$faculty_id = $postdata['faculty_id'];

// Validate user access
$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);

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

        $sql = "SELECT COUNT(*) as count FROM left_teachers WHERE institution_id = ? AND teacher_id = ?";
        $stmt_branch_teacher = $conn_rjllearning_specific->prepare($sql);
        $stmt_branch_teacher->execute([$institution_id, $faculty_id]);
        $result_teachers = $stmt_branch_teacher->fetch();

        if ($result_teachers['count'] != 1) {
            errorreturn("Left teacher Not Found.");
        }

        $sql_delete = "DELETE FROM left_teachers WHERE teacher_id = ? AND institution_id = ?";
        $stmt_delete_left_teacher = $conn_rjllearning_specific->prepare($sql_delete);
        $stmt_delete_left_teacher->execute([$faculty_id, $institution_id]);

        $update_teachers = "UPDATE other_staff_details SET date_of_termination = ? , status = ? WHERE institution_id = ? AND faculty_id = ?";
        $conn_rjllearning_specific->prepare($update_teachers)->execute([null, 1, $institution_id, $faculty_id]);

        $sql_update_teachers = "UPDATE faculty_info SET date_of_termination = ? , status = ? WHERE institution_id = ? AND id = ?";
        $conn_rjllearning_specific->prepare($sql_update_teachers)->execute([null, 1, $institution_id, $faculty_id]);

        $sql_fetch_user_id = "SELECT userid FROM faculty_info WHERE institution_id = ? AND id = ?";
        $stmt_fetch_user_id = $conn_rjllearning_specific->prepare($sql_fetch_user_id);
        $stmt_fetch_user_id->execute([$institution_id, $faculty_id]);

        $result_teacher = $stmt_fetch_user_id->fetchAll();

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

        $teacher_userid = $result_teacher[0]['userid'];

        $sql_update_users = "UPDATE users SET can_activate = ?, status = ? WHERE workspace_id = ? AND institution_id = ? AND id = ?";
        $conn_rjllearning->prepare($sql_update_users)->execute([1, 1, $workspace_id, $institution_id, $teacher_userid]);

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

        successReturn("Teacher 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.");
}
