<?php
// Enable error display for debugging
ini_set('display_errors', 1);

// Include necessary 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 . 'user_management/authenticate.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.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 . 'faculty_api/modules/marksheet/publish_marksheet/function.php';

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

// Check if no data was received
checkIfNoPhpContentsReceive();

// Validate required fields
// if (
//     !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
//     !isset($postdata['academic_session']) || !checkIfIssetAndNotEmpty($postdata['academic_session']) ||
//     !isset($postdata['template_id']) || !checkIfIssetAndNotEmpty($postdata['template_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.");
// }

$requiredFields = [
    // 'institution_id',
    'marksheet_id',
    'api_signature',
    'function_type',
    'jwt_token'
];

foreach ($requiredFields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.$field");
        break; // Exit the loop once an error is found
    }
}


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

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

// Extract user details 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;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

// Validate user access and get specific database name
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $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);

// Extract necessary fields from $postdata
// $institution_id = trim($postdata['institution_id']);
$marksheet_id = trim($postdata['marksheet_id']);
$function_type = trim($postdata['function_type']); // Function type ("publish_marksheet" or "depublish_marksheet")

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

// Determine status based on function type
$status = 0; // Default to 0 (depublish)
if ($function_type === "publish_marksheet") {
    $status = 1; // Mark as published
} elseif ($function_type === "depublish_marksheet") {
    $status = 0; // Mark as unpublished
} else {
    return errorreturn("Invalid function type.");
}

// Update query to set the status of the marksheet in marksheet_info table
$update_query = "UPDATE marksheet_info 
                 SET status = ? 
                 WHERE institution_id = ? AND id = ?";

// Prepare the query
$stmt_update = $conn_rjllearning_specific->prepare($update_query);

// Execute the query with parameters: status, institution_id, and marksheet_id
$stmt_update->execute([$status, $institution_id, $marksheet_id]);

// Check if the update was successful
if ($stmt_update->rowCount() > 0) {
    if ($function_type === "publish_marksheet") {
         //notification send
        sendMarksheetNotification(
            $conn_rjllearning, 
            $conn_rjllearning_specific, 
            $institution_id, 
            $marksheet_id, 
            $workspace_id, 
            $web_app_title
        );
    }
    successreturn("Marksheet status updated successfully.");
} else {
    errorreturn("Failed to update marksheet status or no changes made.");
}

?>
