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


// /home/rejoicebilldesk/public_html/rjllearning_development/resources/
// Check if JSON is valid
$postdata = $_GET;


$required_fields = [ 'marksheet_id', 'class_id', '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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

// Validate user access to specific database
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["teacher"], 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);

$marksheet_id = trim($postdata['marksheet_id']);
$class_id = trim($postdata['class_id']);

$section_id = isset($postdata['section_id']) ? trim($postdata['section_id']) : "null";
$student_id = isset($postdata['student_id']) ? trim($postdata['student_id']) : "all";

function getMarksheetData($marksheet_id, $institution_id, $branch_id, $class_id, $section_id = null, $student_id = 'all', $conn_rjllearning, $conn_rjllearning_specific)
{
    $response = [
        'common_info' => [],
        'students_array' => []
    ];

    // Step 1: Fetch common marksheet data from the `marksheet` table
    $queryMarksheet = "
        SELECT academic_session, examination_name, template_id ,custom_stylesheet_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) {
        return "Marksheet data not found.";
    }

    $academic_session = $marksheetData['academic_session'];
    $examination_name = $marksheetData['examination_name'];
    $template_id = $marksheetData['template_id'];
        $custom_stylesheet_id = $marksheetData['custom_stylesheet_id'];

    // Step 2: Fetch template details from the `template_info` table
    $queryTemplate = "
        SELECT template_name, label, description, pattern, cols 
        FROM template_info WHERE id = ?";
    $stmtTemplate = $conn_rjllearning->prepare($queryTemplate);
    $stmtTemplate->execute([$template_id]);
    $templateData = $stmtTemplate->fetch(PDO::FETCH_ASSOC);

    if (!$templateData) {
        return "Template data not found.";
    }

    $response['common_info'] = array_merge($response['common_info'], $marksheetData, $templateData);

    // Step 3: Fetch marksheet info from the `marksheet_info` table
    $queryMarksheetInfo = "SELECT branch_id FROM marksheet_info WHERE marksheet_id = ? AND class_id = ? AND institution_id = ?";
    $params = [$marksheet_id, $class_id, $institution_id];

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

    if (!$marksheetInfoData) {
        return "Marksheet info not found.";
    }

    // Step 4: Fetch students data from the `students` table
    $queryStudents = "
        SELECT id, institution_id, branch_id, admission_number, name, fathername, class_id, section_id, mothername, dob,gender, status
        FROM students WHERE class_id = ? AND institution_id = ?";
    
    $students_params = [$class_id, $institution_id];

    // Apply the section filter if section_id is provided
    if ($section_id !== null) {
        $queryStudents .= " AND section_id = ?";
        $students_params[] = $section_id;
    }

    // Apply the student_id filter if it's not 'all'
    if ($student_id !== 'all') {
        $queryStudents .= " AND id = ?";
        $students_params[] = $student_id;
    }

    // Execute the query to fetch students
    $stmtStudents = $conn_rjllearning_specific->prepare($queryStudents);
    $stmtStudents->execute($students_params);
    $students = $stmtStudents->fetchAll(PDO::FETCH_ASSOC);
    
    
    $students_array = [];

    // Step 5: Fetch the marksheet data for each student
    foreach ($students as $student) {
        
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $student['class_id']);
        $section_info = getSection($conn_rjllearning_specific, $institution_id, $student['section_id']);
        // Check if data exists in `student_marksheet_data` table for this student
        $queryTemplateData = "SELECT data FROM student_marksheet_data WHERE marksheet_id = ? AND student_id = ?";
        $stmtTemplateData = $conn_rjllearning_specific->prepare($queryTemplateData);
        $stmtTemplateData->execute([$marksheet_id, $student['id']]);
        $templateData = $stmtTemplateData->fetch(PDO::FETCH_ASSOC);
       
        if ($templateData) {
            // If data exists in `student_marksheet_data`, include the student in the response
            $student_data = array_merge($student);
            $student_data['marksheet_data'] = json_decode($templateData['data'], true);
            $students_array[] = $student_data;
        }
    }

    $response['students_array'] = $students_array;

    // Load the appropriate template
    require_once $GLOBALS['base_path_to_learning_resources'] . "marksheet_template/template$template_id/output.php";

    // Generate and return the HTML template
    return htmlltemplate(
        $conn_rjllearning,
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $students_array,
        $examination_name,
        $students_array, // Use $students_array here instead of $students_array['marksheet_data']
        $academic_session,
        $class_info,
        $section_info,
        $template_id,
        $custom_stylesheet_id
    );
}
echo getMarksheetData($marksheet_id, $institution_id, $branch_id, $class_id, $section_id = null, $student_id , $conn_rjllearning, $conn_rjllearning_specific);
// function htmlltemplate($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $students_array, $examination_name, $student_data, $academic_session, $class_id, $section_id, $templateId , $custom_stylesheet_id)
// {
//     ob_start();
//     $institutions = getInstitution($conn_rjllearning, $institution_id);
//     $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id, ['address', 'pincode', 'branch_code', 'contact_number', 'email']);
//     $template_dynamic_function_id='template'.$templateId;
//     // Check if student data is an array
//     if (is_array($student_data)) {
//         // Iterate through each student's data and render a separate marksheet for each
//         foreach ($student_data as $student_marksheet) {
//             // For debugging purposes, you can print the marksheet data for each student
//             // print_r($student_marksheet);

//             ?>
//             <!doctype html>
//             <html>

//             <head>
//                 <meta charset="utf-8">
//                 <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">-->
//                 <title>View Marksheet - <?php echo $student_marksheet['name']; ?></title>
//                 <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
//                 <link href="<?php echo 'https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template' . $templateId . '/style_template' . $templateId . '.css?key=' . time(); ?>" type="text/css" rel="stylesheet">
//             </head>

//             <body>
//                 <?php echo $template_dynamic_function_id($institutions, $branch, [$student_marksheet], $examination_name, $student_marksheet['marksheet_data'], $academic_session, $class_id['class_name'], $section_id['section_name']) == null; ?>
//             </body>

//             </html>
//             <?php
//         }
//     }

//     return ob_get_clean();
// }

function htmlltemplate($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $students_array, $examination_name, $student_data, $academic_session, $class_id, $section_id, $templateId ,$custom_stylesheet_id)
{
    ob_start();
    $institutions = getInstitution($conn_rjllearning, $institution_id);
    $branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id, ['address', 'pincode', 'branch_code', 'contact_number', 'email']);
    global $workspace_id;
    
    $baseUrl = 'https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template';

    if (!empty($custom_stylesheet_id)) {
        // Try to fetch custom stylesheet name from DB
        $sql  = "SELECT custom_stylesheet_name FROM marksheet_custom_styling WHERE id = ?";
        $stmt = $conn_rjllearning->prepare($sql);
        $stmt->execute([$custom_stylesheet_id]);
        $custom_stylesheet = $stmt->fetchColumn();
    
        if ($custom_stylesheet) {
            // Custom stylesheet (template ID in the path + workspace folder + filename)
            $css_path = $baseUrl . $templateId
                      . '/custom_stylesheets/' . $workspace_id
                      . '/' . $custom_stylesheet
                      . '?key=' . time();
        } else {
            // Fallback to default template CSS (dynamic by templateId)
            $css_path = $baseUrl . $templateId
                      . '/style_template' . $templateId . '.css?key=' . time();
        }
    } else {
        // No custom stylesheet selected -> default dynamic template CSS
        $css_path = $baseUrl . $templateId
                  . '/style_template' . $templateId . '.css?key=' . time();
    }
    $template_dynamic_function_id='template'.$templateId;
    // Check if student data is an array
    if (is_array($student_data)) {
        // Iterate through each student's data and render a separate marksheet for each
        foreach ($student_data as $student_marksheet) {
            // For debugging purposes, you can print the marksheet data for each student
            // print_r($student_marksheet);

            ?>
            <!doctype html>
            <html>

            <head>
                <meta charset="utf-8">
                <!--<meta name="viewport" content="width=device-width, initial-scale=1.0">-->
                <title>View Marksheet - <?php echo $student_marksheet['name']; ?></title>
                <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
               <link href="<?= $css_path ?>" type="text/css" rel="stylesheet">

            </head>

            <body>
                <?php echo $template_dynamic_function_id($institutions, $branch, [$student_marksheet], $examination_name, $student_marksheet['marksheet_data'], $academic_session, $class_id['class_name'], $section_id['section_name']) ; ?>
            </body>

            </html>
            <?php
        }
    }

    return ob_get_clean();
}