<?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']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}
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;

// 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);

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', 'affiliation_code'];

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

$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) {
    // ✅ If we have an ID, try to 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) {
        // Build dynamic path to custom stylesheet
        $css_path = "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template27/custom_stylesheets/"
            . $workspace_id . "/" . $custom_stylesheet . "?key=" . time();
    } else {
        // Fallback to default if no DB match
        $css_path = "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template27/style_template27.css?key=" . time();
    }
} else {
    // ✅ No ID → use default stylesheet
    $css_path = "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template27/style_template27.css?key=" . time();
}


$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.1");
}
$cols = $ResultTemplate['cols'];

// Fetching 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]);

// Fetch the result as an associative array
$fetchmarksheet_data = $stmt->fetch(PDO::FETCH_ASSOC);

if ($fetchmarksheet_data) {
    // Unserialize the 'data' column
    $arrayfetch = json_decode($fetchmarksheet_data['data'], true);

    // Check the number of columns in the fetched data
    if (count($arrayfetch) != $cols) {
        // Deleting any pre-existing entries
        $deleteExistingData = $conn_rjllearning_specific->prepare("DELETE FROM student_marksheet_data WHERE student_id = ? AND marksheet_id = ?");
        if (!$deleteExistingData->execute([$student_id, $marksheet_id])) {
            errorreturn("Failed to delete existing data.");
        }
        for ($i = 1; $i <= $cols; $i++) {
            $array[$i] = 0;
        }
        // $array[30] = "";
        // $array[31] = "";
        // $array[32] = "";
    } else {
        $array = array();
        $counter = 1;
        foreach ($arrayfetch as $element) {
            $array[$counter] = $element;
            $counter++;
        }
    }
} else {
    $deleteExistingData = $conn_rjllearning_specific->prepare("DELETE FROM student_marksheet_data WHERE student_id = ? AND marksheet_id = ?");
    if (!$deleteExistingData->execute([$student_id, $marksheet_id])) {
        errorreturn("Failed to delete existing data.");
    }
    for ($i = 1; $i <= $cols; $i++) {
        $array[$i] = 0;
    }
    // $array[30] = "";
    // $array[31] = "";
    // $array[32] = "";
}

?>

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>Template 27 - XI, XII</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <!--<link href="style_template27.css" type="text/css" rel="stylesheet">-->
    <link href="<?php echo $css_path ?>" type="text/css" rel="stylesheet">
</head>

<body>
    <div class="container_marksheet_template">
        <div class="content_container">
            <div class="fullstretch header_template">
                <div class="logo_div">
                    <img src="<?php echo $institutions['logo']; ?>" alt="School Logo">
                </div>
                <div class="header_institution">
                    <span class="heading_template"><?php echo $institutions['institution_name']; ?></span><br>
                    <span class="heading_code_info"><?php echo $branch['affiliation_code']; ?></span><br>
                    <span class="heading_address">
                        <?php echo $branch['address'];
                        if ($branch['pincode'] != "") {
                            echo " - " . $branch['pincode'];
                        }
                        ?>
                    </span><br>
                    <span class="contact_info">
                        <?php echo $branch['contact_number'];
                        if ($branch['email'] != "") {
                            echo ", " . strtolower($branch['email']);
                        }
                        ?>
                    </span>
                </div>
            </div>

            <div class="fullstretch report_header">
                <h2 class="heading_report">Progress Report</h2>
                <div class="academic_session">Academic Session <?php echo $academic_session; ?></div>
            </div>

            <form name="upload_student_marksheet" id="upload_student_marksheet">
                <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; ?>">

                <div class="student_info_container">
                    <div class="student_info_item">
                        <label>Name:</label>
                        <span class="student_data"><?php echo $Resultstudents['name']; ?></span>
                    </div>
                    <div class="student_info_item">
                        <label>Admission Number:</label>
                        <span class="student_data"><?php echo $Resultstudents['admission_number']; ?></span>
                    </div>
                    <div class="student_info_item">
                        <label>Class:</label>
                        <span class="student_data"><?php echo $class_info['class_name']; ?></span>
                    </div>
                    <div class="student_info_item">
                        <label>Section:</label>
                        <span class="student_data"><?php echo $section_info['section_name']; ?></span>
                    </div>
                    <div class="student_info_item">
                        <label>Father's Name:</label>
                        <span class="student_data"><?php echo $Resultstudents['fathername']; ?></span>
                    </div>
                    <div class="student_info_item">
                        <label>Mother's Name:</label>
                        <span class="student_data"><?php echo $Resultstudents['mothername']; ?></span>
                    </div>
                </div>

                <div class="form-container">
                    <div class="stream-selector">
                        <label for="stream-select">Select Stream:</label>
                        <select id="stream-select" class="form-control" name="1" required>
                            <?php if ($array[1] === "default") { ?>
                                <option disabled selected value="default">Select Stream</option>
                            <?php } else { ?>
                                <option value="<?php echo $array[1]; ?>" selected><?php echo $array[1]; ?></option>
                            <?php } ?>
                            <option value="commerce">Commerce</option>
                            <option value="humanities">Humanities</option>
                            <option value="medical">Medical</option>
                            <option value="non-medical">Non-Medical</option>
                        </select>
                    </div>

                    <table id="subjects-table" class="subjects-table">
                        <thead>
                            <tr>
                                <th rowspan="2">Subject</th>
                                <th rowspan="2">Subject Type</th>
                                <th colspan="2">Theory</th>
                                <!-- <th colspan="2">Practical</th> -->
                            </tr>
                            <tr>
                                <th>TH.</th>
                                <th>M.O.</th>
                                <!-- <th>PR.</th>
                                <th>M.O.</th> -->
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Subject rows will be dynamically added here by jQuery -->
                        </tbody>
                    </table>
                </div>

                <div class="summary-item">
                    <p>
                        <label for="attendance-input"><strong>Attendance: </strong></label><br>
                        <input type="text" id="attendance-input" class="form-control" name="34" value="<?php echo htmlspecialchars($array[34] ?? ''); ?>" placeholder="Enter Attendance" maxlength="20" required>
                    </p>
                    <p>
                        <label for="remarks-select"><strong>Remarks: </strong></label><br>
                        <select id="remarks-select" class="form-control" name="35" required>
                            <?php if (empty($array[35])) { ?>
                                <option disabled selected value="">Select</option>
                            <?php } else { ?>
                                <option value="<?php echo htmlspecialchars($array[35]); ?>" selected><?php echo htmlspecialchars($array[35]); ?></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>
                </div>

                <div class="promotion-container">
                    <table class="promotion-table">
                        <tr>
                            <td class="promotion-label">
                                <label for="class_id">Promoted to Class: </label>
                            </td>
                            <td>
                                <select class="form-control" id="class_id" name="52">
                                    <?php
                                    // Default "Not Promoted" option
                                    if (!isset($array[36]) || $array[36] === "na") {
                                        echo '<option value="na" selected>Not Promoted</option>';
                                    } else {
                                        echo '<option value="na">Not Promoted</option>';
                                    }

                                    // Fetch BOTH id and class_name
                                    $ExecuteSqlTemplate = $conn_rjllearning_specific->prepare(
                                        "SELECT id, classname FROM class_info ORDER BY id ASC"
                                    );
                                    $ExecuteSqlTemplate->execute();
                                    $classRows = $ExecuteSqlTemplate->fetchAll(PDO::FETCH_ASSOC);

                                    if (!$classRows) {
                                        errorreturn("Class does not exist.");
                                    }

                                    // Show class_name but send id
                                    foreach ($classRows as $rowclass) {
                                        $selected = (!empty($array[36]) && $array[36] == $rowclass['id']) ? 'selected' : '';
                                        echo '<option value="' . htmlspecialchars($rowclass['id']) . '" ' . $selected . '>'
                                            . htmlspecialchars($rowclass['classname']) . '</option>';
                                    }
                                    ?>
                                </select>
                            </td>
                        </tr>

                        <tr>
                            <td class="promotion-label">
                                <label for="new_session_date">New session begins from: </label>
                            </td>
                            <td>
                                <input type="date"
                                    class="form-control"
                                    id="new_session_date"
                                    name="53"
                                    value="<?php echo isset($array[37]) ? htmlspecialchars($array[37]) : ''; ?>">
                            </td>
                        </tr>
                    </table>
                </div>

                <div class="signature_container">
                    <div class="signature_div">
                        <div class="signature-line"></div>
                        <span>Class Incharge</span>
                    </div>
                    <div class="signature_div">
                        <div class="signature-line"></div>
                        <span>Principal / Headmistress</span>
                    </div>
                    <div class="signature_div">
                        <div class="signature-line"></div>
                        <span>Parent</span>
                    </div>
                </div>

                <div class="submit-row">
                    <button id="submit-btn" class="btn-primary">Upload Marksheet</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            const defaultSubjects = {
                'commerce': [{
                        name: 'English',
                        type: 'M'
                    },
                    {
                        name: 'Economics',
                        type: 'M'
                    },
                    {
                        name: 'Business Studies',
                        type: 'M'
                    },
                    {
                        name: 'Accountancy',
                        type: 'M'
                    },
                    {
                        name: 'Physical Education',
                        type: 'O'
                    }
                ],
                'humanities': [{
                        name: 'English',
                        type: 'M'
                    },
                    {
                        name: 'Physical Education',
                        type: 'O'
                    },
                    {
                        name: 'Punjabi',
                        type: 'M'
                    },
                    {
                        name: 'Political Science',
                        type: 'M'
                    },
                    {
                        name: 'History',
                        type: 'M'
                    }
                ],
                'medical': [{
                        name: 'English',
                        type: 'M'
                    },
                    {
                        name: 'Physics',
                        type: 'M'
                    },
                    {
                        name: 'Chemistry',
                        type: 'M'
                    },
                    {
                        name: 'Biology',
                        type: 'M'
                    },
                    {
                        name: 'Physical Education',
                        type: 'O'
                    }
                ],
                'non-medical': [{
                        name: 'English',
                        type: 'M'
                    },
                    {
                        name: 'Physics',
                        type: 'M'
                    },
                    {
                        name: 'Chemistry',
                        type: 'M'
                    },
                    {
                        name: 'Mathematics',
                        type: 'M'
                    },
                    {
                        name: 'Physical Education',
                        type: 'O'
                    }
                ],
                'default': []
            };

            // This variable holds the data fetched from the database, or null if no data exists.
            const savedMarksheetData = <?php echo json_encode($arrayfetch ?? null); ?>;

            const addSubjectRow = (index, subjectName, subjectType, theoryMax, theoryMarks) => {
                const tableBody = $('#subjects-table tbody');
                const mandatorySelected = subjectType === 'M' ? 'selected' : '';
                const optionalSelected = subjectType === 'O' ? 'selected' : '';
                const additionalSelected = subjectType === 'A' ? 'selected' : '';

                const newRow = `
            <tr>
                <td><input type="text" name="${index}" value="${subjectName}" class="subject-name-input" placeholder="Subject Name"></td>
                <td>
                    <select name="${index+1}" class="subject-type-select">
                        <option value="M" ${mandatorySelected}>Mandatory</option>
                        <option value="A" ${additionalSelected}>Additional</option>
                        <option value="O" ${optionalSelected}>Optional</option>
                    </select>
                </td>
                <td><input type="text" name="${index+2}" value="${theoryMax}" class="theory-marks-max" placeholder="80"></td>
                <td><input type="text" name="${index+3}" value="${theoryMarks}" class="theory-marks-obtained" placeholder="0"></td>
            </tr>
        `;
                tableBody.append(newRow);
            };

            const loadSubjects = (stream) => {
                $('#subjects-table tbody').empty();

                // This is the key logic change: we check for saved data first.
                if (savedMarksheetData && savedMarksheetData['2']) {
                    // Use the saved data from the database
                    for (let i = 2; i <= 30; i += 4) {
                        // If a subject name exists at this key, add the row
                        if (savedMarksheetData[String(i)]) {
                            addSubjectRow(
                                i,
                                savedMarksheetData[String(i)],
                                savedMarksheetData[String(i + 1)],
                                savedMarksheetData[String(i + 2)],
                                savedMarksheetData[String(i + 3)],
                                savedMarksheetData[String(i + 4)],
                                savedMarksheetData[String(i + 5)]
                            );
                        }
                    }
                } else {
                    // No saved data, so we fall back to the default predefined subjects
                    const subjects = defaultSubjects[stream] || [];
                    let index = 2;
                    subjects.forEach(sub => {
                        addSubjectRow(
                            index,
                            sub.name,
                            sub.type,
                            '80', ''
                        );
                        index += 4;
                    });
                }

                // Ensure there are always 8 rows in the table
                while ($('#subjects-table tbody tr').length < 8) {
                    let index = 2 + ($('#subjects-table tbody tr').length * 4);
                    addSubjectRow(
                        index,
                        '', 'O', '80'
                    );
                }
            };

            // Initial load: determine which data to use
            const currentStream = "<?php echo $array[1] ? $array[1] : "default"; ?>";
            if (currentStream && currentStream !== "default") {
                $('#stream-select').val(currentStream);
            }
            loadSubjects(currentStream);

            // Event listener for stream changes
            $('#stream-select').on('change', function() {
                const selectedStream = $(this).val();
                // When the stream is manually changed, revert to the default subjects for that stream
                loadSubjects(selectedStream);
            });

            // FORM SUBMISSION HANDLER
            $("#upload_student_marksheet").on('submit', function(e) {
                e.preventDefault();

                // Basic validation
                let isValid = true;
                let errorMessage = '';

                if ($('#stream-select').val() === 'default') {
                    isValid = false;
                    errorMessage = 'Please select a stream.';
                }

                const hasSubjects = $('.subject-name-input').filter(function() {
                    return $(this).val().trim() !== '';
                }).length > 0;

                if (!hasSubjects) {
                    isValid = false;
                    errorMessage = 'Please add at least one subject.';
                }

                if (!isValid) {
                    alert(errorMessage);
                    return;
                }

                const disabledElements = $(':disabled');
                disabledElements.prop('disabled', false);

                const formData = new FormData(this);

                disabledElements.prop('disabled', true);

                // UI feedback
                $(".subject-name-input, .theory-marks-max, .theory-marks-obtained").prop('readonly', true);
                $(".subject-type-select, #remarks-select").prop('disabled', true);
                $("#attendance-input").prop('readonly', true);
                $("#stream-select").prop('disabled', true);
                $("#class_id").prop('disabled', true);
                $("#new_session_date").prop('readonly', true);
                $("#submit-btn").prop('disabled', true);
                $("#submit-btn").html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Uploading...');

                $.ajax({
                    type: 'POST',
                    url: 'https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template27/process.php',
                    data: formData,
                    contentType: false,
                    cache: false,
                    processData: false,
                    success: function(resp) {
                        try {
                            var response = JSON.parse(resp);
                            if (response.status === 1) {
                                alert("Upload successful: " + response.response);
                            } else {
                                throw new Error(response.response || 'Unknown error');
                            }
                        } catch (e) {
                            alert('Upload failed: ' + e.message);
                        }
                    },
                    error: function(xhr, status, error) {
                        alert('Marks upload failed, please try again later. Error: ' + error);
                    },
                    complete: function() {
                        // Re-enable all form elements
                        $(".subject-name-input, .theory-marks-max, .theory-marks-obtained").prop('readonly', false);
                        $(".subject-type-select, #remarks-select").prop('disabled', false);
                        $("#attendance-input").prop('readonly', false);
                        $("#stream-select").prop('disabled', false);
                        $("#class_id").prop('disabled', false);
                        $("#new_session_date").prop('readonly', false);
                        $("#submit-btn").prop('disabled', false);
                        $("#submit-btn").html('Upload Marksheet');
                    }
                });
            });
        });
    </script>

</body>

</html>