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

// Include 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.");
}

// Validate API signature and JWT
validateApiSignature($postdata['api_signature']);
$jwt_validate = authenticate_jwt($postdata['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);
}

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

// Fetch student details
$stmtStudent = $conn_rjllearning_specific->prepare("SELECT * FROM students WHERE institution_id=? AND id=?");
$stmtStudent->execute([$institution_id,$student_id]);
$student = $stmtStudent->fetch(PDO::FETCH_ASSOC);
if(!$student) errorreturn("Student does not exist.");

$branch_id = $student['branch_id'];
$class_id = $student['class_id'];
$section_id = $student['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=1");
$stmtSession->execute([$institution_id]);
$academic_session_data = $stmtSession->fetch(PDO::FETCH_ASSOC);
$academic_session = $academic_session_data['session_name'] ?? '';

// Fetch marksheet template
$stmtMarks = $conn_rjllearning_specific->prepare("SELECT * FROM marksheet WHERE institution_id=? AND id=?");
$stmtMarks->execute([$institution_id,$marksheet_id]);
$marksheet = $stmtMarks->fetch(PDO::FETCH_ASSOC);
if(!$marksheet) errorreturn("Examination does not exist.");

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

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

// Initialize $array for 35 fields
$array = [];
for($i=1;$i<=35;$i++) $array[$i]='';
if($marksheet_data){
    $data = json_decode($marksheet_data['data'], true);
    foreach($data as $key=>$value) $array[$key] = $value;
} else {
    $array[1] = 'default'; // stream
}
?>
<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Template 28 - Marks Upload</title>
        <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
        <!--<link href="style_template28.css" type="text/css" rel="stylesheet">-->
        <link href="custom_stylesheet/4/4_temp28.css" type="text/css" rel="stylesheet">
            <style>
            #success_div{color:green;margin-top:10px;}
            #error_div{color:red;margin-top:10px;}
            </style>
    </head>
<body>
<div class="container_marksheet_template">
<div class="content_container">
    <!-- Header & Student Info -->
    <div class="fullstretch header_template">
        <div class="logo_div"><img src="../../assets/rejoice_learning_no_text_logo.svg" alt="School Logo"></div>
        <div class="header_institution">
            <span class="heading_template">Garden Valley International School</span><br>
            <span class="heading_code_info">Affiliation Code :-</span><br>
            <span class="heading_address">Address:-</span><br>
            <span class="contact_info">Contact number:-</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>

    <div class="student_info_container">
        <div class="student_info_item"><label>Name:</label> <span class="student_data"><?php echo $student['name']; ?></span></div>
        <div class="student_info_item"><label>Admission Number:</label> <span class="student_data"><?php echo $student['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 $student['fathername']; ?></span></div>
        <div class="student_info_item"><label>Mother's Name:</label> <span class="student_data"><?php echo $student['mothername']; ?></span></div>
    </div>

    <!-- Marks Upload Form -->
    <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']; ?>">

        <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>
                    <option value="default" <?php if($array[1]=='default') echo 'selected'; ?>>Select Stream</option>
                    <option value="commerce" <?php if($array[1]=='commerce') echo 'selected'; ?>>Commerce</option>
                    <option value="humanities" <?php if($array[1]=='humanities') echo 'selected'; ?>>Humanities</option>
                    <option value="medical" <?php if($array[1]=='medical') echo 'selected'; ?>>Medical</option>
                    <option value="non-medical" <?php if($array[1]=='non-medical') echo 'selected'; ?>>Non-Medical</option>
                </select>
            </div>

            <table id="subjects-table" class="subjects-table">
                <thead>
                    <tr>
                        <th>Subject</th>
                        <th>Subject Type</th>
                        <th>Max Marks</th>
                        <th>Marks Obtained</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>

        <div class="summary-container">
            <div class="summary-item-inline">
                <label><strong>Attendance: </strong></label>
                <input type="text" name="34" value="<?php echo $array[34]; ?>" maxlength="3" required>
            </div>
            <div class="summary-item-inline">
                <label><strong>Remarks: </strong></label>
                <select name="35" required>
                    <option value="" disabled <?php if($array[35]=='') echo 'selected'; ?>>Select</option>
                    <option value="Excellent" <?php if($array[35]=='Excellent') echo 'selected'; ?>>Excellent</option>
                    <option value="Good" <?php if($array[35]=='Good') echo 'selected'; ?>>Good</option>
                    <option value="Keep it up" <?php if($array[35]=='Keep it up') echo 'selected'; ?>>Keep it up</option>
                    <option value="Dedicated" <?php if($array[35]=='Dedicated') echo 'selected'; ?>>Dedicated</option>
                    <option value="Worked hard" <?php if($array[35]=='Worked hard') echo 'selected'; ?>>Worked hard</option>
                    <option value="Capable of achieving a higher grade" <?php if($array[35]=='Capable of achieving a higher grade') echo 'selected'; ?>>Capable of achieving a higher grade</option>
                    <option value="Completes his/her work carefully and on time" <?php if($array[35]=='Completes his/her work carefully and on time') echo 'selected'; ?>>Completes his/her work carefully and on time</option>
                    <option value="Good conceptual clarity" <?php if($array[35]=='Good conceptual clarity') echo 'selected'; ?>>Good conceptual clarity</option>
                    <option value="Needs to focus a little more on concepts" <?php if($array[35]=='Needs to focus a little more on concepts') echo 'selected'; ?>>Needs to focus a little more on concepts</option>
                </select>
            </div>
        </div>

        <button type="submit" id="submit_marksheet" class="btn-upload">Upload Marksheet</button>
    </form>

    <div id="error_div" style="display:none;"></div>
    <div id="success_div" style="display:none;">Upload Successful!</div>
</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: 'Punjabi', type: 'M' },
            { name: 'History', type: 'M' },
            { name: 'Political Science', type: 'M' },
            { name: 'Physical Education', type: 'O' },
        ],
        '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': []
    };

    const currentStream = "<?= $array[1] ?? 'default' ?>";

    let counter = 2;

    function addSubjectRow(subject={name:'',type:'O',marks_obtained:''}) {
        const tableBody = $('#subjects-table tbody');
        if(tableBody.find('tr').length >= 8) return;
        const mandatorySelected = subject.type==='M'?'selected':'';
        const optionalSelected = subject.type==='O'?'selected':'';
        const row = `<tr>
            <td><input type="text" name="${counter++}" value="${subject.name}"></td>
            <td>
                <select name="${counter++}">
                    <option value="M" ${mandatorySelected}>Mandatory</option>
                    <option value="O" ${optionalSelected}>Optional</option>
                </select>
            </td>
            <td><input type="text" value="20" readonly></td>
            <td><input type="text" name="${counter++}" value="${subject.marks_obtained || ''}"></td>
        </tr>`;
        tableBody.append(row);
    }

    function loadSubjects(stream){
        counter=2;
        const subjects = defaultSubjects[stream] || [];
        $('#subjects-table tbody').empty();
        subjects.forEach(sub=>addSubjectRow(sub));
        for(let i=subjects.length;i<8;i++) addSubjectRow();
        $('#stream-select').val(stream);
    }

    loadSubjects(currentStream);

    $('#stream-select').on('change',function(){loadSubjects($(this).val());});
   // --- Populate the table based on stream ---
    // function loadSubjects(stream){
    //     counter = 2;
    //     const subjects = defaultSubjects[stream] || [];
    //     const tableBody = $('#subjects-table tbody');
    //     tableBody.empty();

    //     subjects.forEach(sub => addSubjectRow(sub));
    //     for(let i = subjects.length; i < 8; i++) addSubjectRow(); // fill empty rows
    //     $('#stream-select').val(stream);
    // }

    // // --- Clear marks, attendance, remarks ---
    // function clearFormValues(){
    //     // Clear only Marks Obtained column (4th td)
    //     $('#subjects-table tbody tr').each(function() {
    //         $(this).find('td').eq(3).find('input').val('');
    //     });

    //     // Clear attendance and remarks
    //     $('input[name="34"]').val('');
    //     $('select[name="35"]').val(''); // select default empty option

    //     // Reset stream select to default
    //     $('#stream-select').val('default');
    // }

    // // Initial load
    // loadSubjects(currentStream);
    // clearFormValues(); // only clears values, not the rows

    // // On stream change
    // $('#stream-select').on('change', function(){
    //     loadSubjects($(this).val());
    //     clearFormValues(); // optional: keep cleared values when changing stream
    // });

    $("#upload_marksheet_form").on('submit',function(e){
        e.preventDefault();
        const formData = new FormData(this);
        $.ajax({
            url:'https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template28/process.php',
            method:'POST',
            data:formData,
            contentType:false,
            processData:false,
            success:function(resp){
                $('#success_div').show();
                $('#error_div').hide();
            },
            error:function(){
                $('#error_div').show().text('Upload failed!');
                $('#success_div').hide();
            }
        });
    });
});
</script>
</body>
</html>
