<?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';
require_once $base_path_to_learning_resources . 'marksheet_template/template35/function.php';
// Get input data
$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 required fields are missing.");
}

validateApiSignature($postdata['api_signature']);

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

// Extract user details
$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
// Validate user access and get specific database name
$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'];

# Get full student info
$stmt = $conn_rjllearning_specific->prepare(
    "SELECT * FROM students WHERE institution_id = ? AND id = ?"
);
$stmt->execute([$institution_id, $student_id]);
$Resultstudents = $stmt->fetch(PDO::FETCH_ASSOC);

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

$branch_id  = $Resultstudents['branch_id'];

# Check if marksheet is locked (using branch_id)
$lock_sql = "SELECT class_id, section_id, student_list
             FROM lock_marksheet_cache 
             WHERE institution_id = ? 
             AND branch_id = ?
             AND marksheet_id = ?";

$lock_stmt = $conn_rjllearning_specific->prepare($lock_sql);
$lock_stmt->execute([$institution_id, $branch_id, $marksheet_id]);

$lock_rows = $lock_stmt->fetchAll(PDO::FETCH_ASSOC);

$locked_found = false;

if (!empty($lock_rows)) {

    foreach ($lock_rows as $lock_row) {

        $student_list = json_decode($lock_row['student_list'], true);

        if (in_array((string)$student_id, $student_list)) {

            # Student found in locked list
            $class_id   = $lock_row['class_id'];
            $section_id = $lock_row['section_id'];

            $locked_found = true;
            break;
        }
    }

    if (!$locked_found) {
        errorreturn("Student not allowed. Marksheet is locked.");
    }

} else {

    # Use student's actual class/section
    $class_id   = $Resultstudents['class_id'];
    $section_id = $Resultstudents['section_id'];
}

# Get class and section info
$class_info   = getClass($conn_rjllearning_specific, $institution_id, $class_id);
$section_info = getSection($conn_rjllearning_specific, $institution_id, $section_id);



$SqlTemplate = "SELECT * FROM academic_session WHERE institution_id = ? AND active_academic_session = ?";
$StmtTemplate = $conn_rjllearning_specific->prepare($SqlTemplate);
$StmtTemplate->execute([$institution_id, 1]);
$result = $StmtTemplate->fetchAll(PDO::FETCH_ASSOC); // Make sure to fetch associative array

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

// Fetch institution information
$institutions = getInstitution($conn_rjllearning, $institution_id);

// Define additional data fields
$additional_data = ['branch_code', 'address', 'pincode', 'contact_number', 'email'];

// Fetch branch information
$branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id, $additional_data);

// 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'];


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

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


// 🔹 Academic session dates (already fetched)
$session_start = $result[0]['startdate'];
$session_end = $result[0]['enddate'];

// 🔹 Fetch full day-wise attendance ONCE
$stmtAtt = $conn_rjllearning_specific->prepare("
    SELECT date, value
    FROM student_attendance_daywise
    WHERE institution_id = ?
      AND student_id = ?
      AND date BETWEEN ? AND ?
");
$stmtAtt->execute([
    $institution_id,
    $student_id,
    $session_start,
    $session_end
]);

$attendance_rows = $stmtAtt->fetchAll(PDO::FETCH_ASSOC);


// Get 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 && !empty($fetchmarksheet_data['data'])) {

    $decoded = json_decode($fetchmarksheet_data['data'], true);

    if (is_array($decoded)) {

        // ðŸ”‘ FIX: Reindex 1-based â†’ 0-based
        $decoded = array_values($decoded);

        if (count($decoded) === $cols) {

            // PERFECT MATCH â†’ USE DIRECTLY
            for ($i = 0; $i < $cols; $i++) {
                $array[$i] = $decoded[$i];
            }
        } else {

            // MISMATCH â†’ RESET SAFELY
            for ($i = 0; $i < $cols; $i++) {
                $array[$i] = null;
            }
        }
    } else {

        // INVALID JSON
        for ($i = 0; $i < $cols; $i++) {
            $array[$i] = null;
        }
    }
} else {

    // NO DATA â†’ FRESH ARRAY
    for ($i = 0; $i < $cols; $i++) {
        $array[$i] = null;
    }
}

?>

<script>
    const ACADEMIC_SESSION = {
        start: "<?= $session_start ?>",
        end: "<?= $session_end ?>"
    };

    const STUDENT_ATTENDANCE = <?= json_encode($attendance_rows, JSON_HEX_TAG) ?>;
</script>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MARKS UPLOAD</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/template35/style_template35.css?key=' . time(); ?>"
        type="text/css" rel="stylesheet">
</head>

<body>

    <div class="report-card">
        <!-- Header -->
        <div class="header">
            <div class="logo">
                <img src="<?php echo $institutions['logo']; ?>" alt="School Logo">
            </div>
            <div class="school-details">
                <p class="sname"><?php echo $institutions['institution_name']; ?></p>
                <p><?php
                    echo $branch['address'];
                    if ($branch['pincode'] != "")
                        echo " - " . $branch['pincode'];
                    ?></p>
                <p class="affiliation">to be affiliated to CBSE,
                    New Delhi</p>
            </div>
        </div>

        <div class="term-box">
            Term II ( <?php echo $academic_session; ?> )
        </div>
        <!-- Student Info -->
        <div class="student-info">
            <div class="left">
                <p><strong>Student's Name : </strong><?php echo $Resultstudents['name']; ?></p>
                <p><strong>Father's Name : </strong><?php echo $Resultstudents['fathername']; ?></p>
                <p><strong>Mother's Name : </strong><?php echo $Resultstudents['mothername']; ?></p>
                <p><strong>D.O.B : </strong><?php echo $Resultstudents['dob']; ?></p>
            </div>
            <div class="right">
                <p><strong>Class : </strong><?php echo $class_info['class_name']; ?></p>
                <p><strong>Section : </strong><?php echo $section_info['section_name']; ?></p>
                <p><strong>Roll No : </strong></p>
                <p><strong>Admission No : </strong><?php echo $Resultstudents['admission_number']; ?></p>
            </div>
        </div>

        <form id="upload_marksheet_form" 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 $postdata['jwt_token']; ?>">
            <input type="hidden" name="api_signature" value="<?php echo $postdata['api_signature']; ?>">

            <!-- Scholastic Area -->
            <div class="table-title">
                Scholastic Area (Grading on 7 Point Scale)
            </div>
            <table>
                <thead>
                    <tr>
                        <th>Subjects</th>
                        <th>Periodic Test (10)</th>
                        <th>Subject Enrichment (5)</th>
                        <th>Notebook (5)</th>
                        <th>Yearly (80)</th>
                        <!-- <th>Total (100)</th> -->
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>English</td>
                        <td><input type="number" min="0" step="any" name="marks[0]" max="10" value="<?= $array[0] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[1]" max="5" value="<?= $array[1] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[2]" max="5" value="<?= $array[2] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[3]" max="80" value="<?= $array[3] ?? '' ?>"></td>
                        <!--<input type="hidden" name="marks[4]" value="">-->
                    </tr>
                    <tr>
                        <td>Hindi</td>
                        <td><input type="number" min="0" step="any" name="marks[5]" max="10" value="<?= $array[5] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[6]" max="5" value="<?= $array[6] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[7]" max="5" value="<?= $array[7] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[8]" max="80" value="<?= $array[8] ?? '' ?>"></td>
                        <!--<input type="hidden" name="marks[9]" value="">-->
                    </tr>
                    <tr>
                        <td>Punjabi</td>
                        <td><input type="number" min="0" step="any" name="marks[10]" max="10" value="<?= $array[10] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[11]" max="5" value="<?= $array[11] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[12]" max="5" value="<?= $array[12] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[13]" max="80" value="<?= $array[13] ?? '' ?>"></td>
                        <!--<input type="hidden" name="marks[14]" value="">-->
                    </tr>
                    <tr>
                        <td>Maths</td>
                        <td><input type="number" min="0" step="any" name="marks[15]" max="10" value="<?= $array[15] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[16]" max="5" value="<?= $array[16] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[17]" max="5" value="<?= $array[17] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[18]" max="80" value="<?= $array[18] ?? '' ?>"></td>
                        <!--<input type="hidden" name="marks[19]" value="">-->
                    </tr>
                    <tr>
                        <td>Social Science</td>
                        <td><input type="number" min="0" step="any" name="marks[20]" max="10" value="<?= $array[20] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[21]" max="5" value="<?= $array[21] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[22]" max="5" value="<?= $array[22] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[23]" max="80" value="<?= $array[23] ?? '' ?>"></td>
                        <!--<input type="hidden" name="marks[24]" value="">-->
                    </tr>
                    <tr>
                        <td>Science</td>
                        <td><input type="number" min="0" step="any" name="marks[25]" max="10" value="<?= $array[25] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[26]" max="5" value="<?= $array[26] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[27]" max="5" value="<?= $array[27] ?? '' ?>"></td>
                        <td><input type="number" min="0" step="any" name="marks[28]" max="80" value="<?= $array[28] ?? '' ?>"></td>
                        <!--<input type="hidden" name="marks[29]" value="">-->
                    </tr>
                </tbody>
            </table>

            <input type="hidden" name="marks[4]">
            <input type="hidden" name="marks[9]">
            <input type="hidden" name="marks[14]">
            <input type="hidden" name="marks[19]">
            <input type="hidden" name="marks[24]">
            <input type="hidden" name="marks[29]">

            <input type="hidden" name="marks[32]"> <!-- Grand Total -->
            <input type="hidden" name="marks[33]"> <!-- Percentage -->
            <input type="hidden" name="marks[34]">

            <div class="summary">
                <div>
                    Attendance :
                    <strong>
                        <input type="number" min="0" step="any"
                            name="marks[30]"
                            value="<?= $array[30] ?? '' ?>"
                            style="width:80px;">
                        <span> Out Of </span>
                        <input type="number" min="0" step="any"
                            name="marks[31]"
                            value="<?= $array[31] ?? '' ?>"
                            style="width:80px;">
                    </strong>
                </div>
            </div>

            <!-- Grade Subjects -->
            <div class="bottom-section">
                <div class="box">
                    <div class="table-title">
                        Grade Subjects Areas (on a 3 point grade
                        scale)
                    </div>
                    <table>
                        <tr>
                            <td>GK</td>
                            <td><?php ms35_grade_dropdown('marks[35]', $array[35] ?? ''); ?></td>
                        </tr>
                        <tr>
                            <td>ICT</td>
                            <td><?php ms35_grade_dropdown('marks[36]', $array[36] ?? ''); ?></td>
                        </tr>
                        <tr>
                            <td>Sports</td>
                            <td><?php ms35_grade_dropdown('marks[37]', $array[37] ?? ''); ?></td>
                        </tr>
                    </table>
                </div>

                <div class="box">
                    <div class="table-title">
                        Skill Subjects Areas (on a 3 point grade
                        scale)
                    </div>
                    <table>
                        <tr>
                            <td>Art</td>
                            <td><?php ms35_grade_dropdown('marks[38]', $array[38] ?? ''); ?></td>
                        </tr>
                        <tr>
                            <td>Speaking Skills</td>
                            <td><?php ms35_grade_dropdown('marks[39]', $array[39] ?? ''); ?></td>
                        </tr>
                        <tr>
                            <td>Overall Conduct</td>
                            <td><?php ms35_grade_dropdown('marks[40]', $array[40] ?? ''); ?></td>
                        </tr>
                    </table>
                </div>
            </div>

            <!-- Grade Scale -->
            <div class="grade-scale">
                <div class="table-title">
                    Grade Scale For Scholastic Areas
                </div>
                <table>
                    <tr>
                        <th>Marks Range (%)</th>
                        <td>91-100</td>
                        <td>81-90</td>
                        <td>71-80</td>
                        <td>61-70</td>
                        <td>51-60</td>
                        <td>41-50</td>
                        <td>33-40</td>
                        <td>0-32</td>
                    </tr>
                    <tr>
                        <th>Grade</th>
                        <td>A1</td>
                        <td>A2</td>
                        <td>B1</td>
                        <td>B2</td>
                        <td>C1</td>
                        <td>C2</td>
                        <td>D</td>
                        <td>E</td>
                    </tr>
                </table>
            </div>

            <!-- Remarks -->
            <div class="remarks">
                <strong>Remarks:</strong>
            </div>
            <div>
                <select class="form-control mt-2 mb-2"
                    id="remarks_marksheet"
                    name="marks[41]"
                    required>

                    <?php if (empty($array[41])) { ?>
                        <option disabled selected value="">Select</option>
                    <?php } ?>

                    <?php
                    $remarksOptions = [
                        "Excellent",
                        "Good",
                        "Keep it up",
                        "Dedicated",
                        "Worked hard",
                        "Capable of achieving a higher grade",
                        "Completes his/her work carefully and on time",
                        "Good conceptual clarity",
                        "Needs to focus a little more on concepts"
                    ];

                    foreach ($remarksOptions as $remark) {
                        $selected = (isset($array[41]) && $array[41] === $remark) ? "selected" : "";
                        echo "<option value=\"$remark\" $selected>$remark</option>";
                    }
                    ?>
                </select>
            </div>

            <!-- Signatures -->
            <div class="signatures">
                <div>Parent Signature</div>
                <div>Teacher Signature</div>
                <div>Principal Signature</div>
            </div>

            <div style="margin-top:20px; text-align:center;">
                <button type="submit" id="submit_marksheet">
                    Save Marksheet
                </button>
            </div>

            <div id="ms29SuccessMsg" style="display:none; color:green; text-align:center; margin-top:10px;">
                Marksheet saved successfully.
            </div>

            <div id="ms29ErrorMsg" style="display:none; color:red; text-align:center; margin-top:10px;"></div>

        </form>

    </div>

</body>

</html>

<script>
    $(document).ready(function() {

        $("#upload_marksheet_form").on("submit", function(e) {
            e.preventDefault();

            var form = this;
            var formData = new FormData(form);

            $.ajax({
                url: "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template35/process.php",
                type: "POST",
                data: formData,
                processData: false,
                contentType: false,
                cache: false,

                beforeSend: function() {
                    $("#submit_marksheet")
                        .prop("disabled", true)
                        .text("Saving...");
                },

                success: function(resp) {
                    try {
                        var response = JSON.parse(resp);

                        if (response.status == 1) {
                            $("#ms29SuccessMsg").fadeIn(300);
                            $("#ms29ErrorMsg").hide();

                            setTimeout(function() {
                                $("#ms29SuccessMsg").fadeOut(300);
                            }, 3000);
                        } else {
                            showError(response.message || "Save failed");
                        }

                    } catch (e) {
                        showError("Unexpected response from server.");
                    }

                    $("#submit_marksheet")
                        .prop("disabled", false)
                        .text("Save Marksheet");
                },

                error: function() {
                    showError("Server error. Please try again.");
                    $("#submit_marksheet")
                        .prop("disabled", false)
                        .text("Save Marksheet");
                }
            });
        });

        function showError(msg) {
            $("#ms29ErrorMsg")
                .text(msg)
                .fadeIn(300);

            setTimeout(function() {
                $("#ms29ErrorMsg").fadeOut(300);
            }, 5000);
        }

    });
</script>