<?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';

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

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

foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || empty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

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.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

$institution_id = trim($postdata['institution_id']);
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);

if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}

$branch_id = trim($postdata['branch_id']);
$teacher_id = trim($postdata['teacher_id']);
$date_of_leaving = isset($postdata['date_of_leaving']) ? $postdata['date_of_leaving'] : date('Y-m-d');
$attachment = (isset($_FILES['attachment']) and !empty($_FILES['attachment'])) ? $_FILES['attachment'] : null;
$reason = trim($postdata['reason']);
$remarks = isset($postdata['remarks']) ? $postdata['remarks'] : null;
$marked_on = date('Y-m-d');

// verifying teacher
$verify_query = "SELECT userid FROM faculty_info WHERE institution_id = ? AND branch_id = ? AND id = ? AND role = 'teacher' AND 
date_of_termination IS NULL AND status = 1";
$verify_stmt = $conn_rjllearning_specific->prepare($verify_query);
$verify_stmt->execute([$institution_id, $branch_id, $teacher_id]);
$teacher_exists = $verify_stmt->fetchAll();

if (count($teacher_exists) != 1) {
    errorreturn("teacher record not found.");
}
$teacher_userid = $teacher_exists[0]['userid'];

$conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
$conn_rjllearning_specific->beginTransaction();

if ($postdata['function_type'] == "create_manage_teacher_alumni") {
    $res = $conn_rjllearning_specific->prepare("SELECT id FROM left_teachers WHERE institution_id = ? AND branch_id = ? AND teacher_id = ?");
    $res->execute([$institution_id, $branch_id, $teacher_id]);
    $result1 = $res->fetchAll();

    if (count($result1) >= 1) {
        errorreturn("Teacher alumni already exists.");
    } else {

        if ($attachment == null) {
            $attachment = null;
        } else {
            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');
            $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/left_teachers/" . $currentYear . "/" . $currentMonth . "/";
            $file_name = $_FILES['attachment']['name'];
            $fileTmpName = $_FILES['attachment']["tmp_name"];
            $fileSize = $_FILES['attachment']["size"];
            $fileType = $_FILES['attachment']["type"];
            $fileError = $_FILES['attachment']["error"];
            $file_extension = strtolower(pathinfo($_FILES['attachment']['name'], PATHINFO_EXTENSION));
            $size = filesize($fileTmpName);
            // Check if it's a valid image
            $allowedTypes = [
                'image/jpeg',
                'image/png',
                'image/gif',
                'image/heic',
                'application/pdf',
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'application/vnd.ms-excel',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            ]; // Allowed image types
            $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
            $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

            checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        }

        try {
            $insert_query = "INSERT INTO left_teachers (institution_id, branch_id, teacher_id, date_of_leaving, attachment, reason, remarks, 
            marked_by, marked_on) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn_rjllearning_specific->prepare($insert_query);
            $stmt->execute([
                $institution_id,
                $branch_id,
                $teacher_id,
                $date_of_leaving,
                $attachment,
                $reason,
                $remarks,
                $username,
                $marked_on
            ]);
        } catch (Exception $e) {
            echo "Error : " . $e->getMessage();
        }

        $id = $conn_rjllearning_specific->lastInsertId();

        if ($attachment !=  null) {
            $image_name = "teacherleft_" . $id . "." . $file_extension; // Define the image name dynamically
            $path = $directoryPathMain . $image_name; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $attachment, $path, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_image = json_encode(array("filepath" => $path, "original_name" => $file_name));
            $sql_logo = "UPDATE left_teachers SET attachment = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $id));
        }

        $sql = "UPDATE faculty_info set status = -1, date_of_termination = ? where institution_id = ? and id = ?";
        $conn_rjllearning_specific->prepare($sql)->execute(array($marked_on, $institution_id, $teacher_id));

        $conn_rjllearning_specific->commit();
        $sql = "UPDATE users set can_activate = 0, status = 0 where workspace_id = ? and institution_id = ? and id = ?";
        $conn_rjllearning->prepare($sql)->execute(array($workspace_id, $institution_id, $teacher_userid));
        // Return success response
        successreturn("Successfully added teacher alumni.");
    }
}
