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

// Validation files
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/check_username_availability.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 . 'functions/common_functions.php';
// Dynamic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";


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


// Check if required fields are present
if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

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

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

// Extract data from JWT token
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$branch_id = $jwt_validate->data->branch_id;
// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

// Extract and validate input data
$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);
$status = trim($postdata['status']);

// Validate status value
if ($status !== null && !in_array($status, [0, 1, 2])) {
    errorreturn('Invalid status value.');
}

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

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

// Validate branch
if ($branch_id != "all") {
    $sql_branch = $conn_rjllearning_specific->prepare("SELECT id, name FROM branch WHERE id = ? AND institution_id = ?");
    $sql_branch->execute([$branch_id, $institution_id]);
    $branch = $sql_branch->fetch(PDO::FETCH_ASSOC);
    if (!$branch) {
        errorreturn("Branch does not exist in the specified institution.");
    }
}


if ($postdata['function_type'] === "create_status_updates") {
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];
    $class_incharge_roles = $teacher_data['class_incharge_roles'];
    $staff_access_modules = $teacher_data['staff_access_modules'];

    $check_faculty_status = checkFacultyModuleGranted($postdata['function_type'], $class_section_subjects, $class_incharge_roles, $staff_access_modules, null, null, null, $conn_rjllearning);
    if ($check_faculty_status == false) {
        errorreturn("Access denied: You do not have the required permissions.");
    }

    // if(!is_array($postdata['leave_id'])){
    //       errorreturn("Leave IDs must be multiple are required for updating status.");
    // }
    $leave_id = $postdata['leave_id'];
    if (is_array($leave_id)) {

        if (!is_array($leave_id) or count($leave_id) <= 0) {
            errorreturn("Select atleast one leave.");
        }

        $imploded_leavesids = "('" . implode("','", $leave_id) . "')";
        $sql_leaves = $conn_rjllearning_specific->prepare("SELECT COUNT(*) FROM  staff_apply_leaves WHERE id IN $imploded_leavesids AND institution_id = ? AND branch_id = ?");
        $sql_leaves->execute([$institution_id, $branch_id]);
        $count = $sql_leaves->fetchColumn();
        if ($count < 0) {
            errorreturn("Leave IDs not found.");
        }
    }

    if (is_array($leave_id)) {
        $placeholders = implode(',', array_fill(0, count($leave_id), '?'));
        $sql = "UPDATE staff_apply_leaves SET status = ?,approved_by=? WHERE institution_id = ? AND id IN ($placeholders)";
        $array_params = array_merge([$status, $username, $institution_id], $leave_id);
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute($array_params);
    } else {
        $sql = "UPDATE staff_apply_leaves SET status = ?,approved_by=? WHERE id = ? AND  institution_id = ? AND branch_id = ?";
        $array_params = [$status, $leave_id, $username, $institution_id, $branch_id];
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute($array_params);
    }
    successreturn("Successfully updated status for leave ID.");
}
