<?php

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_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 . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning_resources . "includes/specific_db_config.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "user_management/functions/functions.php";
require_once $base_path_to_learning_resources . 'template/marksheet/header/header1.php';
require_once $base_path_to_learning_resources . 'template/marksheet/header/header2.php';

// /home/rejoicebilldesk/public_html/rjllearning_development/resources/
// Check if JSON is valid
$postdata = json_decode(file_get_contents("php://input"), true);
// print_r($postdata);
checkIfNoPhpContentsReceive();


$required_fields = [ 'api_signature', 'jwt_token'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("Missing required field: $field");
    }
}
validateApiSignature($postdata['api_signature']);
// Authenticate user and get user details
$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;

$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;
$class_id = $jwt_validate->data->class;
$section_id = $jwt_validate->data->section;

$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["student"], null, null, $userid);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
validateStudentClassSection($conn_rjllearning_specific, $userid, $institution_id, $branch_id, $class_id, $section_id);



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



function getPublishedMarksheetData($institution_id, $branch_id, $class_id,$userid, $conn_rjllearning_specific)
{
    $response = [
        'published_marksheets' => []
    ];

    // Step 1: Fetch the published marksheet data using the marksheet_info table
    $queryMarksheetInfo = "
        SELECT marksheet_id 
        FROM marksheet_info 
        WHERE class_id = ? AND institution_id = ? AND branch_id = ? AND status = 1";  // status = 1 for published
    
    $params = [$class_id, $institution_id, $branch_id];

    $stmtMarksheetInfo = $conn_rjllearning_specific->prepare($queryMarksheetInfo);
    $stmtMarksheetInfo->execute($params);
    $marksheetInfoData = $stmtMarksheetInfo->fetchAll(PDO::FETCH_ASSOC);

    if (!$marksheetInfoData) {
        errorreturn("No published marksheets found for the given criteria.");
    }

    // Step 2: Fetch detailed information for each published marksheet
    foreach ($marksheetInfoData as $marksheetInfo) {
        $marksheet_id = $marksheetInfo['marksheet_id'];

        // Step 3: Check if any student has marksheet data for this marksheet
        $queryStudentMarksheetData = "
            SELECT student_id
            FROM student_marksheet_data 
            WHERE marksheet_id = ?";
        $stmtStudentMarksheetData = $conn_rjllearning_specific->prepare($queryStudentMarksheetData);
        $stmtStudentMarksheetData->execute([$marksheet_id]);
        $studentMarksheetData = $stmtStudentMarksheetData->fetchAll(PDO::FETCH_ASSOC);

        if ($studentMarksheetData) {
            // Step 4: Fetch common data from the marksheet table for this marksheet_id
            $queryMarksheet = "
                SELECT academic_session, examination_name, id as marksheet_id
                FROM marksheet 
                WHERE id = ? AND institution_id = ?";
            $stmtMarksheet = $conn_rjllearning_specific->prepare($queryMarksheet);
            $stmtMarksheet->execute([$marksheet_id, $institution_id]);
            $marksheetData = $stmtMarksheet->fetch(PDO::FETCH_ASSOC);

            if ($marksheetData) {
                $response['published_marksheets'][] = $marksheetData;  // Add the published marksheet data to the response
            }
        }
    }

    return $response;  // Return the list of published marksheets for which student data exists
}



if ($postdata['function_type'] == "fetch_published_marksheet_students") {
   
        $success['data'] = getPublishedMarksheetData($institution_id, $branch_id, $class_id,$userid, $conn_rjllearning_specific);
        successreturn($success['data']);
    
}

