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

$required_fields = [
    'institution_id',
    'student_id',
    'marksheet_id',
    'api_signature',
    'jwt_token'
];

foreach ($required_fields as $field) {
    if (!isset($postdata[$field])) {
    errorreturn("All * fields are required. $field");
}
}
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'];

// Fetch student data
$ExecuteSqlTemplate = $conn_rjllearning_specific->prepare("SELECT * FROM students WHERE institution_id = ? and id=?");
$ExecuteSqlTemplate->execute([$institution_id, $student_id]);
$Resultstudents = $ExecuteSqlTemplate->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'];

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

// Get academic session
$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'];

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

// Get marksheet template info
$ExecuteSqlTemplate = $conn_rjllearning_specific->prepare("SELECT examination_name,template_id,academic_session 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'];

// 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]);
$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[12] = "";
        $array[13] = "";
    } 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[12] = "";
    $array[13] = "";
}

?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Result - <?php echo $institutions['institution_name']; ?></title>
    <link href="https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template26/style_template26.css?key=<?php echo time(); ?>" type="text/css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <style>
        .form-control {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-family: 'Poppins', sans-serif;
        }
        
        .columns_number, .columns_text {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            text-align: center;
            font-family: 'Poppins', sans-serif;
        }
        
        #submit_marksheet {
            background-color: var(--primary-color);
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1rem;
            margin-top: 20px;
            transition: background-color 0.3s;
        }
        
        #submit_marksheet:hover {
            background-color: var(--secondary-color);
        }
        
        #error_div, #displayadd_homework_success {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            text-align: center;
        }
        
        #error_div {
            background-color: #ffebee;
            color: #d32f2f;
        }
        
        #displayadd_homework_success {
            background-color: #e8f5e9;
            color: #2e7d32;
        }
    </style>
</head>

<body>
    <div class="container_marksheet">
        <form name="upload_student_marksheet" action="" method="post" 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="header">
                <div class="logo">
                    <img src="<?php echo $institutions['logo']; ?>" alt="School Logo" />
                </div>
                <div class="school-info">
                    <h1 class="school-name"><?php echo $institutions['institution_name']; ?></h1>
                    <div class="school-details">
                        <div>Affiliation Code: <?php echo $branch['branch_code']; ?></div>
                        <div><?php echo $branch['address']; if ($branch['pincode'] != "") { echo " - " . $branch['pincode']; } ?></div>
                        <div>Contact: <?php echo $branch['contact_number']; if ($branch['email'] != "") { echo " | Email: " . strtolower($branch['email']); } ?></div>
                    </div>
                </div>
            </div>

            <div class="report-title">
                <h1>Progress Report</h1>
                <div class="session">Academic Session <?php echo $academic_session; ?></div>
            </div>

            <div class="student-info">
                <div class="info-box">
                    <div class="info-row">
                        <div class="info-label">Name:</div>
                        <div class="info-value"><?php echo $Resultstudents['name']; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Class:</div>
                        <div class="info-value"><?php echo $class_info['class_name']; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Father's Name:</div>
                        <div class="info-value"><?php echo $Resultstudents['fathername']; ?></div>
                    </div>
                </div>

                <div class="info-box">
                    <div class="info-row">
                        <div class="info-label">Admission Number:</div>
                        <div class="info-value"><?php echo $Resultstudents['admission_number']; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Section:</div>
                        <div class="info-value"><?php echo $section_info['section_name']; ?></div>
                    </div>
                    <div class="info-row">
                        <div class="info-label">Mother's Name:</div>
                        <div class="info-value"><?php echo $Resultstudents['mothername']; ?></div>
                    </div>
                </div>
            </div>

            <table class="marks-table">
                <thead>
                    <tr>
                        <th>Subject</th>
                        <th>M.M. (THEORY)</th>
                        <th>MARKS OBTAINED</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>English</td>
                        <td>40</td>
                        <td><input type="number" min="0" max="40" required name="5" id="col5" class="columns_number" value="<?php echo $array[5]; ?>"></td>
                    </tr>
                    <tr>
                        <td>Physical Education</td>
                        <td>40</td>
                        <td><input type="number" min="0" max="40" required name="6" id="col6" class="columns_number" value="<?php echo $array[6]; ?>"></td>
                    </tr>
                    <tr>
                        <td><input type="text" required name="1" id="col1" class="columns_text" placeholder="Enter Subject" value="<?php echo $array[1]; ?>"></td>
                        <td>40</td>
                        <td><input type="number" min="0" max="40" required name="7" id="col7" class="columns_number" value="<?php echo $array[7]; ?>"></td>
                    </tr>
                    <tr>
                        <td><input type="text" required name="2" id="col2" class="columns_text" placeholder="Enter Subject" value="<?php echo $array[2]; ?>"></td>
                        <td>40</td>
                        <td><input type="number" min="0" max="40" required name="8" id="col8" class="columns_number" value="<?php echo $array[8]; ?>"></td>
                    </tr>
                    <tr>
                        <td><input type="text" required name="3" id="col3" class="columns_text" placeholder="Enter Subject" value="<?php echo $array[3]; ?>"></td>
                        <td>40</td>
                        <td><input type="number" min="0" max="40" required name="9" id="col9" class="columns_number" value="<?php echo $array[9]; ?>"></td>
                    </tr>
                    <tr>
                        <td><input type="text" required name="4" id="col4" class="columns_text" placeholder="Enter Subject" value="<?php echo $array[4]; ?>"></td>
                        <td>40</td>
                        <td><input type="number" min="0" max="40" required name="10" id="col10" class="columns_number" value="<?php echo $array[10]; ?>"></td>
                    </tr>
                    <tr>
                        <td>Information Technology</td>
                        <td>40</td>
                        <td><input type="number" min="0" max="40" required name="11" id="col11" class="columns_number" value="<?php echo $array[11]; ?>"></td>
                    </tr>
                </tbody>
            </table>

            <div class="additional-info">
                <div class="info-box-large">
                    <h3>Remarks:</h3>
                    <select class="form-control" id="remarks_marksheet" required name="13">
                        <?php if ($array[13] == ""): ?>
                            <option disabled selected value="">Select</option>
                        <?php else: ?>
                            <option value="<?php echo $array[13]; ?>" selected><?php echo $array[13]; ?></option>
                        <?php endif; ?>
                        <option value="Excellent">Excellent</option>
                        <option value="Very Good">Very Good</option>
                        <option value="Good">Good</option>
                        <option value="Satisfactory">Satisfactory</option>
                        <option value="Needs Improvement">Needs Improvement</option>
                        <option value="Has shown significant progress">Has shown significant progress</option>
                        <option value="Capable of achieving higher grades">Capable of achieving higher grades</option>
                        <option value="Should focus more on core subjects">Should focus more on core subjects</option>
                        <option value="Needs to work on time management">Needs to work on time management</option>
                    </select>
                </div>
            </div>

            <div class="signatures">
                <div class="signature-box">
                    <div>Class Incharge</div>
                    <div class="signature-line"></div>
                </div>
                <div class="signature-box">
                    <div>Principal / Headmistress</div>
                    <div class="signature-line"></div>
                </div>
                <div class="signature-box">
                    <div>Parent's Signature</div>
                    <div class="signature-line"></div>
                </div>
            </div>

            <div class="footer-note">
                * In case of any discrepancies in marksheet, please contact school administration.
            </div>

            <button type="submit" id="submit_marksheet">Upload Marksheet</button>
        </form>

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

    <script>
        $(document).ready(function() {
            $("#upload_student_marksheet").on('submit', function(e) {
                e.preventDefault(); // Prevent the default form submission

                $.ajax({
                    type: 'POST',
                    url: 'https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template26/process.php',
                    data: new FormData(this), // Capture all form data including file uploads
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function() {
                        // Disable form fields and the submit button
                        $(".columns_number").attr('readonly', true);
                        $(".columns_text").attr('readonly', true);
                        $("#remarks_marksheet").attr('readonly', true);
                        $("#submit_marksheet").prop('disabled', true);

                        // Append loader to the submit button
                        $("#submit_marksheet").html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Uploading...');
                    },
                    error: function(xhr, status, error) {
                        // Re-enable form fields and submit button in case of error
                        $(".columns_number").attr('readonly', false);
                        $(".columns_text").attr('readonly', false);
                        $("#remarks_marksheet").attr('readonly', false);
                        $("#submit_marksheet").prop('disabled', false);
                        $("#submit_marksheet").html('Upload Marksheet'); // Reset submit button text

                        // Show error message
                        $("#error_message").text('Marks upload failed, please try again later.');
                        $("#error_div").css('color', 'red').fadeIn(300);
                        setTimeout(function() {
                            $("#error_div").fadeOut(300);
                        }, 5000);
                    },
                    success: function(resp) {
                        try {
                            var response = JSON.parse(resp);

                            if (response.status === 1) { // Success
                                // Re-enable form fields and submit button
                                $(".columns_number").attr('readonly', false);
                                $(".columns_text").attr('readonly', false);
                                $("#remarks_marksheet").attr('readonly', false);
                                $("#submit_marksheet").prop('disabled', false);
                                $("#submit_marksheet").html('Upload Marksheet'); // Reset submit button text

                                // Show success message
                                $("#success_message").text("Upload successful.");
                                $("#displayadd_homework_success").fadeIn(300);
                                setTimeout(function() {
                                    $("#displayadd_homework_success").fadeOut(300);
                                }, 3000);
                            } else { // Failure response from the server
                                throw new Error(response.response || 'Unknown error');
                            }
                        } catch (e) {
                            // If there's an error parsing or in the response
                            $(".columns_number").attr('readonly', false);
                            $(".columns_text").attr('readonly', false);
                            $("#remarks_marksheet").attr('readonly', false);
                            $("#submit_marksheet").prop('disabled', false);
                            $("#submit_marksheet").html('Upload Marksheet'); // Reset submit button text

                            // Show server error message
                            $("#error_message").text(e.message || 'Upload failed.');
                            $("#error_div").css('color', 'red').fadeIn(300);
                            setTimeout(function() {
                                $("#error_div").fadeOut(300);
                            }, 5000);
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>