<?php
ini_set('display_errors', 1);

// Include necessary files
require_once '../../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 . 'admin_api/academic_session/functions/validate_faculty.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/functions.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 . "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';

$postdata = $_GET;

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

validateApiSignature($postdata['api_signature']);
$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;

// Validate user access
$specific_db_name = validateUserAccess(
    $conn_rjllearning,
    $userid,
    $role,
    $workspace_id,
    ["superadmin","admin","principal","teacher"],
    null
);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

$api_signature  = $postdata['api_signature'];
$institution_id = $postdata['institution_id'];
$student_id     = $postdata['student_id'];
$marksheet_id   = $postdata['marksheet_id'];

// Student details
$stmtStudent = $conn_rjllearning_specific->prepare(
    "SELECT * FROM students WHERE institution_id = ? AND id=?"
);
$stmtStudent->execute([$institution_id, $student_id]);
$Resultstudents = $stmtStudent->fetch(PDO::FETCH_ASSOC);

if (!$Resultstudents) {
    errorreturn("Student does not exist.");
}

$branch_id = $Resultstudents['branch_id'];
$class_id  = $Resultstudents['class_id'];
$section_id= $Resultstudents['section_id'];

$class_info   = getClass($conn_rjllearning_specific, $institution_id, $class_id);
$section_info = getSection($conn_rjllearning_specific, $institution_id, $section_id);

// Academic session
$stmtSession = $conn_rjllearning_specific->prepare(
    "SELECT * FROM academic_session WHERE institution_id = ? AND active_academic_session = ?"
);
$stmtSession->execute([$institution_id, 1]);
$result = $stmtSession->fetchAll(PDO::FETCH_ASSOC);

if (count($result) < 1) {
    errorreturn("Academic session not found. Contact admin.");
}

// Institution & branch info
$institutions = getInstitution($conn_rjllearning, $institution_id);
$branch = getBranchInfo(
    $conn_rjllearning_specific,
    $institution_id,
    $branch_id,
    ['branch_code', 'address', 'pincode', 'contact_number', 'email']
);

// Marksheet
$ExecuteSqlTemplate = $conn_rjllearning_specific->prepare("SELECT examination_name,template_id,academic_session, custom_stylesheet_id FROM marksheet WHERE institution_id = ? and id=?");
$ExecuteSqlTemplate->execute([$institution_id, $marksheet_id]);
$ResultTemplates = $ExecuteSqlTemplate->fetch(PDO::FETCH_ASSOC);

if (!$ResultTemplates) {
  errorreturn("examination_name does not exist.");
}

$examination = $ResultTemplates['examination_name'];
$template_id = $ResultTemplates['template_id'];
$academic_session = $ResultTemplates['academic_session'];

$custom_stylesheet_id = $ResultTemplates['custom_stylesheet_id'];

// if not null then fetch the path, custom table -> id -> path
// path -> https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template23/ + custom_stylesheets/$workspace_id/filename.css
if ($custom_stylesheet_id !== null) {
    // ✅ ID exists → fetch custom stylesheet
    $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 path
        $css_path = "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template1/custom_stylesheets/"
                  . $workspace_id . "/" . $custom_stylesheet . "?key=" . time();
    } else {
        // Fallback to default if ID not found
        $css_path = "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template1/style_template1.css?key=" . time();
    }
} else {
    // ✅ No ID → use default stylesheet
    $css_path = "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template1/style_template1.css?key=" . time();
}

// Template info
$stmtTemplate = $conn_rjllearning->prepare(
    "SELECT cols, template_name FROM template_info WHERE id = ? "
);
$stmtTemplate->execute([$template_id]);
$ResultTemplate = $stmtTemplate->fetch(PDO::FETCH_ASSOC);

if (!$ResultTemplate) {
    errorreturn("Marksheet Template does not exist.");
}
$cols = $ResultTemplate['cols'];

// Fetch existing marksheet data
$stmt = $conn_rjllearning_specific->prepare(
    "SELECT data FROM student_marksheet_data WHERE student_id = ? AND marksheet_id = ? AND institution_id = ?"
);
$stmt->execute([$student_id, $marksheet_id, $institution_id]); 
$fetchmarksheet_data = $stmt->fetch(PDO::FETCH_ASSOC);

$array = [];
if ($fetchmarksheet_data) {
    $arrayfetch = json_decode($fetchmarksheet_data['data'], true);
    if (is_array($arrayfetch)) {
        $array = $arrayfetch;
    }
}

// Ensure defaults for missing fields
for ($i=1; $i <= $cols; $i++) {
    if (!isset($array[$i])) {
        $array[$i] = '';
    }
}
?>
<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Template 1 Marks Upload</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <link href="<?= $css_path ?>" type="text/css" rel="stylesheet">

</head>
<body>
<div class="container_marksheet_template1">
    <div class="content_container_template1">

        <!-- Header -->
        <div class="header_template1 flexbox-row-center-start">
            <div class="logo_div_img_template1">
                <img src="<?php echo htmlspecialchars($institutions['logo']); ?>" alt="School Logo">
            </div>
            <div class="header_institution">
                <h1><?php echo htmlspecialchars($institutions['institution_name']); ?></h1>
                <div class="header_details">
                    <p>Affiliation Code: <?php echo htmlspecialchars($branch['branch_code']); ?></p>
                    <p>Address: <?php echo htmlspecialchars($branch['address']); ?><?php if($branch['pincode']!=""){ echo " - ".$branch['pincode']; } ?></p>
                    <p>Contact: <?php echo htmlspecialchars($branch['contact_number']); ?><?php if($branch['email']!=""){ echo ", ".strtolower(htmlspecialchars($branch['email'])); } ?></p>
                </div>
            </div>
        </div>

        <h1 class="heading_report_template1">Progress Report</h1>
        <p class="aligncenter">Academic Session <?php echo $academic_session; ?></p>

        <!-- Student Info -->
        <table class="student_info_table_template1 transparent_table">
            <tr>
                <td><strong>Name :</strong></td>
                <td><?php echo htmlspecialchars($Resultstudents['name']); ?></td>
                <td><strong>Admission Number :</strong></td>
                <td><?php echo htmlspecialchars($Resultstudents['admission_number']); ?></td>
            </tr>
            <tr>
                <td><strong>Class :</strong></td>
                <td><?php echo htmlspecialchars($class_info['class_name']); ?></td>
                <td><strong>Section :</strong></td>
                <td><?php echo htmlspecialchars($section_info['section_name']); ?></td>
            </tr>
            <tr>
                <td><strong>Father's Name:</strong></td>
                <td><?php echo htmlspecialchars($Resultstudents['fathername']); ?></td>
                <td><strong>Mother's Name:</strong></td>
                <td><?php echo htmlspecialchars($Resultstudents['mothername']); ?></td>
            </tr>
        </table>

        <form id="upload_student_marksheet" method="POST">
            <input type="hidden" name="marksheet_id" value="<?php echo $marksheet_id; ?>">
            <input type="hidden" name="institution_id" value="<?php echo $institution_id; ?>">
            <input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
            <input type="hidden" name="jwt_token" value="<?php echo $jwttoken; ?>">
            <input type="hidden" name="api_signature" value="<?php echo $api_signature; ?>">

            <!-- Marks Table -->
            <table class="table1_template1 fullstretch">
                <thead>
                    <tr>
                        <th>SUBJECT</th>
                        <th>TH (40)</th>
                        <th>M.O.</th>
                        <th>PR (40)</th>
                        <th>M.O.</th>
                    </tr>
                </thead>
                <tbody>
                 <?php
                $base=1;
                $subjects=7;
                for($i=1;$i<=$subjects;$i++) {
                    $th_val = $array[$base+7] ?? '';
                    $pr_val = $array[$base+14] ?? '';
                ?>
                    <tr>
                        <td><input type="text" name="<?php echo $base; ?>" value="<?php echo htmlspecialchars($array[$base]??''); ?>" placeholder="Subject Name"></td>
                        <td>40</td>
                        <td><input type="number" name="<?php echo $base+7; ?>" value="<?php echo $th_val; ?>" min="0" max="40"></td>
                        <td>40</td>
                        <td><input type="number" name="<?php echo $base+14; ?>" value="<?php echo $pr_val; ?>" min="0" max="40"></td>
                    </tr>
                <?php $base++; } ?>
                </tbody>
            </table>
        <div class="margintop35 flex-row-info">
            <p><strong>Attendance:</strong> <input type="text" name="23" value="<?php echo htmlspecialchars($array[23]??''); ?>"></p>
            <p><strong>Remarks:</strong>
               <select name="24" required>
                    <?php if(empty($array[24])) { ?>
                        <option value="" disabled selected>Select</option>
                    <?php } else { ?>
                        <option value="<?php echo htmlspecialchars($array[24]); ?>" selected><?php echo htmlspecialchars($array[24]); ?></option>
                    <?php } ?>
                    <option value="Excellent">Excellent</option>
                    <option value="Good">Good</option>
                    <option value="Keep it up">Keep it up</option>
                    <option value="Dedicated">Dedicated</option>
                    <option value="Worked hard">Worked hard</option>
                    <option value="Capable of achieving a higher grade">Capable of achieving a higher grade</option>
                    <option value="Completes his/her work carefully and on time">Completes his/her work carefully and on time</option>
                    <option value="Good conceptual clarity">Good conceptual clarity</option>
                    <option value="Needs to focus a little more on concepts">Needs to focus a little more on concepts</option>
                </select>
            </p>
            <p><strong>Promoted to Class:</strong>
               <select name="25">
                    <option value="na" <?php echo ($array[25]??'')=='na'?'selected':''; ?>>Not Promoted</option>
                    <?php
                    $stmtClasses = $conn_rjllearning_specific->prepare("SELECT id, classname FROM class_info ORDER BY id ASC");
                    $stmtClasses->execute();
                    $classes = $stmtClasses->fetchAll(PDO::FETCH_ASSOC);
                    foreach ($classes as $cls) {
                        $selected = (!empty($array[25]) && $array[25]==$cls['id']) ? 'selected' : '';
                        echo '<option value="'.htmlspecialchars($cls['id']).'" '.$selected.'>'.htmlspecialchars($cls['classname']).'</option>';
                    }
                    ?>
                </select>
            </p>
            <p><strong>New Session Begins:</strong> <input type="date" name="26" value="<?php echo htmlspecialchars($array[26]??''); ?>"></p>
        </div>
            <button type="submit" id="submit_marksheet" class="btn-primary">Upload Marksheet</button>
        </form>

        <div id="error_div" style="display:none;color:red;"><span id="error_message"></span></div>
        <div id="displayadd_homework_success" style="display:none;color:green;"><span id="success_message"></span></div>
    </div>
</div>

<script>
$(function(){
    $("#upload_student_marksheet").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template1/process.php',
            data: new FormData(this),
            contentType: false,
            cache: false,
            processData: false,
            beforeSend: function(){
                $("#upload_student_marksheet :input").prop('disabled', true);
                $("#submit_marksheet").html('<span class="spinner-border spinner-border-sm"></span> Uploading...');
            },
            success: function(resp){
                try {
                    var response = JSON.parse(resp);
                    if (response.status==1) {
                        $("#success_message").text("Upload successful.");
                        $("#displayadd_homework_success").fadeIn(300).delay(3000).fadeOut(300);
                    } else {
                        throw new Error(response.response || "Unknown error");
                    }
                } catch(e) {
                    $("#error_message").text(e.message || "Upload failed.");
                    $("#error_div").fadeIn(300).delay(5000).fadeOut(300);
                }
                $("#upload_student_marksheet :input").prop('disabled', false);
                $("#submit_marksheet").html('Upload Marksheet');
            },
            error: function(){
                $("#upload_student_marksheet :input").prop('disabled', false);
                $("#submit_marksheet").html('Upload Marksheet');
                $("#error_message").text("Marks upload failed, please try again later.");
                $("#error_div").fadeIn(300).delay(5000).fadeOut(300);
            }
        });
    });
});
</script>
</body>
</html>
