<?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';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}
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;

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

function get_teacher_alumni($conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $limit, $offset)
{
    $sql_count = "SELECT count(*) as total_rows FROM left_teachers WHERE institution_id = ?";
    $array_params = [$institution_id];

    if ($branch_id && $branch_id != 'all') {
        $sql_count .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }

    if ($search_string !== null) {
        $sql_count .= " AND (reason LIKE ? or remarks LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    $sql_session = "SELECT * FROM left_teachers WHERE institution_id = ?";
    $array_params = [$institution_id];

    if ($branch_id && $branch_id != 'all') {
        $sql_session .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }

    if ($search_string !== null) {
        $sql_session .= " AND (reason LIKE ? or remarks LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

    if ($limit != 'all') {
        $sql_session .= " LIMIT " . $offset . ", " . $limit;
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_session);
    $stmt->execute($array_params);
    $session_rows = $stmt->fetchAll();

    $array_return = [];

    foreach ($session_rows as $row) {
        $teacher_sql = "SELECT * FROM faculty_info WHERE institution_id = ? and status = 0 and id = ? AND date_of_termination = ?";

        // Prepare and execute the query
        $teacher_stmt = $conn_rjllearning_specific->prepare($teacher_sql);
        $teacher_stmt->execute([$institution_id, $row['teacher_id'], $row['marked_on']]);
        $teacher_result = $teacher_stmt->fetchAll(PDO::FETCH_ASSOC);

        // Check if the result is not empty
        if (empty($teacher_result)) {
            errorreturn("Enter a valid teacher info");
        } else {
            foreach ($teacher_result as $result) {
                $teacher_info = ["name" => $result['name'], "userid" => $result['userid'], "designation" => $result['designation']];
            }
        }

        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $row['branch_id']);

        $array_return[] = [
            'teacher_alumni_id' => $row['id'],
            'institution_id' => $row['institution_id'],
            'branch_info' => $branch_info,
            'teacher_info' => $teacher_info,
            'date_of_leaving' => $row['date_of_leaving'],
            'attachment' => $row['attachment'],
            'reason' => $row['reason'],
            'remarks' => $row['remarks'],
            'marked_by' => $row['marked_by'],
            'marked_on' => $row['marked_on']
        ];
    }

    if (count($array_return) < 50) {
        return ['total_rows' => $totalrows, 'alumni_info' => $array_return, 'maxreach' => 1];
    } else {
        return ['total_rows' => $totalrows, 'alumni_info' => $array_return, 'maxreach' => 0];
    }
}

if ($postdata['function_type'] == "fetch_teacher_alumni") {
    
    $institution_id = $postdata['institution_id'];

    $academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($academic_id == false) {
        errorreturn("Access denied. Academic session not active.");
    }
    $branch_id = $postdata['branch_id'];

    if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success = get_teacher_alumni($conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $limit, $offset);
        successreturn($success);
    } else {
        $success = get_teacher_alumni($conn_rjllearning_specific, $institution_id, $branch_id, $search_string, $limit, null);
        successreturn($success);
    }
}
