<?php
// index served started as 1 for array
//fetching table of cols from marksheeet_data

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', 'city', 'state', 'country', 'pincode', 'contact_number', 'email', 'affiliation_code'];

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

$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/template22/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/template22/style_template22.css?key=" . time();
    }
} else {
    // ✅ No ID → use default stylesheet
    $css_path = "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template22/style_template22.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] = "";
        }
        $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] = "";
    }
    $array[30] = "";
    $array[31] = "";
    $array[32] = "";
}

?>
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <!--<meta name="viewport" content="width=device-width, initial-scale=1.0" />-->
    <title>Template 22</title>
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <link href="<?= $css_path ?>" type="text/css" rel="stylesheet">
    <!--<link href="style_template22.css" type="text/css" rel="stylesheet" />-->

</head>

<body>
    <div class="container_marksheet_template1">
        <div class="border_template1">
            <div class="content_container_template1">
                <!-- Header -->
                <div class="header_template1">
                    <div class="logo_div_img_template1">
                        <img src="<?php echo $institutions['logo']; ?>" alt="School Logo">
                    </div>
                    <div class="header_institution">
                        <span class="heading_template1"><?php echo $institutions['institution_name']; ?></span><br>
                        <span class="heading_code_info_template1"><?php echo $branch['affiliation_code']; ?></span><br>
                        <span class="heading_address_template1">
                        <?php 
                        echo $branch['address'];
                        if ($branch['pincode'] != "" || $branch['city'] != "" || $country_state['country_name'] != "" || $country_state['state_name'] != "") {
                            echo ", " . $branch['city'] . ", " . $country_state['state_name'] . ", " . $country_state['country_name'] . " - " . $branch['pincode'];
                        }
                        ?>
                        </span><br>
                        <span class="contact_template1"><?php echo $branch['contact_number'];
                                                        if ($branch['email'] != "") {
                                                            echo ", " . strtolower($branch['email']);
                                                        }
                                                        ?></span>
                    </div>
                </div>

                <!-- Report Title -->
                <div class="header_info_container">
                    <div class="heading_report_template1">Holistic Progress Card</div>
                    <div class="year_template1">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; ?>">

                    <!-- Student Info -->
                    <div class="student-info-container">
                        <div class="student_info_template1">
                            <table class="student_info_table_template1">
                                <tr>
                                    <td>Name</td>
                                    <td><?php echo $Resultstudents['name']; ?></td>
                                </tr>
                                <tr>
                                    <td>Admission No.</td>
                                    <td><?php echo $Resultstudents['admission_number']; ?></td>
                                </tr>
                                <tr>
                                    <td>Father's Name</td>
                                    <td><?php echo $Resultstudents['fathername']; ?></td>
                                </tr>
                                <tr>
                                    <td>D.O.B.</td>
                                    <td>
                                        <?php echo !empty($Resultstudents['dob']) ? date("d-m-Y", strtotime($Resultstudents['dob'])) : ""; ?>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="student_info_template1">
                            <table class="student_info_table_template1">
                                <tr>
                                    <td>Class</td>
                                    <td>
                                        <?php echo $class_info['class_name']; ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td>Section</td>
                                    <td>
                                        <?php echo $section_info['section_name']; ?>
                                    </td>
                                </tr>
                                <tr>
                                    <td>Height</td>
                                    <td><input type="text" name="1" value="<?php echo isset($array[1]) ? $array[1] : ''; ?>" maxlength="10" required></td>
                                </tr>
                                <tr>
                                    <td>Weight</td>
                                    <td><input type="text" name="2" value="<?php echo isset($array[2]) ? $array[2] : ''; ?>" maxlength="10" required></td>
                                </tr>
                            </table>
                        </div>
                    </div>



                    <!-- Assessment Tables -->
                    <div class="assessment-container">
                        <div>
                            <table class="assessment-table">
                                <tr>
                                    <th colspan="2">ASSESSMENTS</th>
                                </tr>
                                <tr class="subject-header">
                                    <td colspan="2">ENGLISH</td>
                                </tr>
                                <tr>
                                    <td>Can write neatly</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="3" value="<?php echo $array[3]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Can narrate stories effectively</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="4" value="<?php echo $array[4]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Can recite poems with expressions</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="5" value="<?php echo $array[5]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Can recognize and read properly</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="6" value="<?php echo $array[6]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Written</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="33" value="<?php echo $array[33]; ?>" maxlength="3"></td>
                                </tr>
                                <tr>
                                    <td>Oral</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="34" value="<?php echo $array[34]; ?>" maxlength="3"></td>
                                </tr>

                                <tr class="subject-header">
                                    <td colspan="2">MATHEMATICS</td>
                                </tr>
                                <tr>
                                    <td>Can identify the numbers correctly</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="7" value="<?php echo $array[7]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Can grasp the combination of numbers</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="8" value="<?php echo $array[8]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Can count and write in sequence</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="9" value="<?php echo $array[9]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Written</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="35" value="<?php echo $array[35]; ?>" maxlength="3"></td>
                                </tr>
                                <tr>
                                    <td>Oral</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="36" value="<?php echo $array[36]; ?>" maxlength="3"></td>
                                </tr>

                                <tr class="subject-header">
                                    <td colspan="2">PUNJABI</td>
                                </tr>
                                <tr>
                                    <td>Can express the word</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="10" value="<?php echo $array[10]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Can write properly</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="11" value="<?php echo $array[11]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Written</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="37" value="<?php echo $array[37]; ?>" maxlength="3"></td>
                                </tr>
                                <tr>
                                    <td>Oral</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="38" value="<?php echo $array[38]; ?>" maxlength="3"></td>
                                </tr>

                                <tr class="subject-header">
                                    <td colspan="2">E.V.S. / GENERAL KNOWLEDGE</td>
                                </tr>
                                <tr>
                                    <td>Can identify</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="12" value="<?php echo $array[12]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Can write properly</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="13" value="<?php echo $array[13]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Can express / understand the word / pictures</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="14" value="<?php echo $array[14]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Written</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="39" value="<?php echo $array[39]; ?>" maxlength="3"></td>
                                </tr>
                                <tr>
                                    <td>Oral</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="40" value="<?php echo $array[40]; ?>" maxlength="3"></td>
                                </tr>

                                <tr class="subject-header">
                                    <td colspan="2">ART & CRAFT</td>
                                </tr>
                                <tr>
                                    <td>Enjoys drawing, colouring & pasting</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="15" value="<?php echo $array[15]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Follows instructions carefully</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="16" value="<?php echo $array[16]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr class="subject-header">
                                    <td colspan="2">RHYMES</td>
                                </tr>
                                <tr>
                                    <td>GRADE</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="41" value="<?php echo $array[41]; ?>" maxlength="3"></td>
                                </tr>
                                <tr>
                                    <td>Oral</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="42" value="<?php echo $array[42]; ?>" maxlength="3"></td>
                                </tr>
                                <tr class="subject-header">
                                    <td colspan="2">STORY</td>
                                </tr>
                                <tr>
                                    <td>GRADE</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="43" value="<?php echo $array[43]; ?>" maxlength="3"></td>
                                </tr>
                                <tr>
                                    <td>Oral</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="44" value="<?php echo $array[44]; ?>" maxlength="3"></td>
                                </tr>
                                <tr class="subject-header">
                                    <td colspan="2">CONVERSATION</td>
                                </tr>
                                <tr>
                                    <td>GRADE</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="45" value="<?php echo $array[45]; ?>" maxlength="3"></td>
                                </tr>
                                <tr>
                                    <td>Oral</td>
                                    <td><input type="number" class="forms_cp_inputtext texttransformupper" name="46" value="<?php echo $array[46]; ?>" maxlength="3"></td>
                                </tr>

                                <tr class="subject-header">
                                    <td colspan="1">ATTENDANCE:</td>
                                    <td>
                                        <input type="text" class="forms_cp_inputtext texttransformupper" name="17" value="<?php echo $array[17]; ?>" required>
                                    </td>
									<?php /*<input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="form-control" value="<?php echo $array[$temp_count]; ?>">*/ ?>
                                </tr>
                                <tr class="subject-header">
                                    <td colspan="1">GENERAL REMARKS: </td>
                                    <td>
                                        <select class="forms_cp_inputtext texttransformupper" id="remarks_marksheet" required name="30">
                                            <?php if ($array[30] == "") { ?>
                                                <option disabled selected value="">Select</option>
                                            <?php } else { ?>
                                                <option value="<?php echo $array[30]; ?>" selected><?php echo $array[30]; ?></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>
                                    </td>
                                </tr>
                            </table>
                        </div>

                        <div>
                            <table class="assessment-table">
                                <tr>
                                    <th colspan="2">COMPETENCIES</th>
                                </tr>
                                <tr class="subject-header">
                                    <td colspan="2">PHYSICAL DEVELOPMENT</td>
                                </tr>

                                <tr class="section-header">
                                    <td colspan="2">PART-I (HEALTHY & SAFE HABITS)</td>
                                </tr>
                                <tr>
                                    <td>Shows a liking for and understanding of nutritious food and does not waste food</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="18" value="<?php echo $array[18]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Practices basic self- care and hygiene</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="19" value="<?php echo $array[19]; ?>" maxlength="3" required></td>
                                </tr>

                                <tr class="section-header">
                                    <td colspan="2">PART-II (SENSORIAL PERCEPTIONS)</td>
                                </tr>
                                <tr>
                                    <td>Differentiates between shapes, colours and their shades</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="20" value="<?php echo $array[20]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Differentiates multiple smells and tastes</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="21" value="<?php echo $array[21]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Develops discriminations in the sense of touch</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="22" value="<?php echo $array[22]; ?>" maxlength="3" required></td>
                                </tr>

                                <tr class="section-header">
                                    <td colspan="2">PART-III (PHYSICAL FITNESS)</td>
                                </tr>
                                <tr>
                                    <td>Shows balance, coordination and flexibility in various physical activities</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="23" value="<?php echo $array[23]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Shows precision and control in working with their hands and fingers</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="24" value="<?php echo $array[24]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Shows strength and endurance in carrying, walking and running</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="25" value="<?php echo $array[25]; ?>" maxlength="3" required></td>
                                </tr>

                                <tr class="subject-header">
                                    <td colspan="2">SOCIO-EMOTIONAL & ETHICAL DEVELOPMENT</td>
                                </tr>

                                <tr class="section-header">
                                    <td colspan="2">PART-I (EMOTIONAL INTELLIGENCE)</td>
                                </tr>
                                <tr>
                                    <td>Recognises 'self' as an individual belong to a family and community</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="26" value="<?php echo $array[26]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Recognises different emotions and makes deliberate efforts to regulate them</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="27" value="<?php echo $array[27]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Interacts comfortably with other children and adults</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="28" value="<?php echo $array[28]; ?>" maxlength="3" required></td>
                                </tr>
                                <tr>
                                    <td>Shows kindness and helpfulness to others</td>
                                    <td><input type="text" class="forms_cp_inputtext texttransformupper" name="29" value="<?php echo $array[29]; ?>" maxlength="3" required></td>
                                </tr>
                            </table>
                        </div>
                    </div>

                    <!-- Signatures -->
                    <div class="signature-container">
                        <div class="signature-box">
                            <div class="signature-line"></div>
                            <div class="signature-title">Class Incharge</div>
                        </div>
                        <div class="signature-box">
                            <div class="signature-line"></div>
                            <div class="signature-title">Principal / Headmistress</div>
                        </div>
                        <div class="signature-box">
                            <div class="signature-line"></div>
                            <div class="signature-title">Parent</div>
                        </div>
                    </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="31">
                                        <?php
                                        // Default "Not Promoted" option
                                        if (!isset($array[31]) || $array[31] === "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[31]) && $array[31] == $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="32"
                                        value="<?php echo isset($array[32]) ? htmlspecialchars($array[32]) : ''; ?>">
                                </td>
                            </tr>
                        </table>
                    </div>

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

                </form>

                <!--display Success Error-->
                <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>
        </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/template22/process.php',
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function() {
                        // Disable form fields and the submit button
                        $(".forms_cp_inputtext").attr('readonly', true);
                        $("#remarks_marksheet").attr('disabled', 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
                        $(".forms_cp_inputtext").attr('readonly', false);
                        $("#remarks_marksheet").attr('disabled', false);
                        $("#submit_marksheet").prop('disabled', false);
                        $("#submit_marksheet").html('Upload Marksheet');

                        // 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
                                $(".forms_cp_inputtext").attr('readonly', false);
                                $("#remarks_marksheet").attr('disabled', false);
                                $("#submit_marksheet").prop('disabled', false);
                                $("#submit_marksheet").html('Upload Marksheet');

                                // 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
                            $(".forms_cp_inputtext").attr('readonly', false);
                            $("#remarks_marksheet").attr('disabled', false);
                            $("#submit_marksheet").prop('disabled', false);
                            $("#submit_marksheet").html('Upload Marksheet');

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