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

// Decode JSON input data
// $postdata = json_decode(file_get_contents("php://input"), true);
$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'];


$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'];
// Prepare the SQL statement

$class_info = getClass($conn_rjllearning_specific, $institution_id,$class_id );

$section_info = getSection($conn_rjllearning_specific, $institution_id, $section_id);



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

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

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

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

	// Fetch branch information
	$branch = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id, $additional_data);
	
$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) {
    // ✅ Fetch custom stylesheet if ID is provided
    $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) {
        $css_path = "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template12/custom_stylesheets/"
                    . $workspace_id . "/" . $custom_stylesheet . "?key=" . time();
    } else {
        // fallback if ID not found in DB
        $css_path = "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template12/style_template12.css?key=" . time();
    }
} else {
    // ✅ No ID provided → default CSS
    $css_path = "https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template12/style_template12.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.");
	}
	$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.");
        }
		// Initialize the array with default values
		for ($i = 1; $i <= $cols; $i++) {
			$array[$i] = 0; // Set all values to 0
		}

		// Set specific indexes to empty strings
		$array[7] = "";
		$array[14] = "";
		$array[21] = "";
		$array[28] = "";
		$array[35] = "";
		$array[42] = "";
		$array[49] = ""; // marks ended
		$array[53] = ""; // overall grade
		$array[54] = "";
		$array[55] = "";
		$array[56] = "";
		$array[57] = "";
		$array[58] = "";
		$array[59] = "";
		$array[60] = "";
		$array[61] = "";
		$array[62] = "";
		$array[63] = "";
		$array[64] = "";
		$array[65] = "";
		$array[66] = "";
		$array[67] = "";
		$array[68] = "";
		$array[69] = ""; // participation
		$array[70] = ""; // remarks
				$array[71] = ""; // promoted to class 
						$array[72] = ""; // new session begin from 


		
	} else {
		// If data count matches the expected column count, fill the array
		$array = array();
		$counter = 1;
		foreach ($arrayfetch as $element) {
			$array[$counter] = $element;
			$counter++;
		}
	}
} else {

	// If no data found, delete existing entries and initialize the array
	$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.");
	}

	// Initialize the array with default values
	for ($i = 1; $i <= $cols; $i++) {
		$array[$i] = 0; // Set all values to 0
	}

	// Set specific indexes to empty strings
	$array[7] = "";
	$array[14] = "";
	$array[21] = "";
	$array[28] = "";
	$array[35] = "";
	$array[42] = "";
	$array[49] = ""; // marks ended
	$array[53] = ""; // overall grade
	$array[54] = "";
	$array[55] = "";
	$array[56] = "";
	$array[57] = "";
	$array[58] = "";
	$array[59] = "";
	$array[60] = "";
	$array[61] = "";
	$array[62] = "";
	$array[63] = "";
	$array[64] = "";
	$array[65] = "";
	$array[66] = "";
	$array[67] = "";
	$array[68] = "";
	$array[69] = ""; // participation
	$array[70] = ""; // remarks
			$array[71] = ""; // promoted to class 
						$array[72] = ""; // new session begin from 
}
?>
<!doctype html>
<html>

<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Template 12 (template 33)</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">

</head>

<body>
	<div class="container_marksheet_template1">

		<div class="border_template1"><!--border template is not being used-->

			<div class="content_container_template1">

				<!--template 1 logo-->
				<div class="fullstretch header_template1" align="center">
					<div class="logo_div_img_template1">
						<img class="images" src="<?php echo $institutions['logo']; ?>">
					</div>
					<div class="header_institution">
						<span class="fullstretch heading_template1"><?php echo $institutions['institution_name']; ?></span><br>
						<span class="heading_code_info_template1"><?php echo $branch['branch_code']; ?></span><br>
						<span class="heading_address_template1"><?php echo $branch['address']; ?></span><br>
						<span class="heading_address_template1" style="text-transform: none;"><?php echo $branch['contact_number']; ?></span>
					</div>
				</div>

				<div class="fullstretch header_info_container margintop10" align="center">
					<div class="fullstretch heading_report_template1">Holistic Progress Card</div>
					<div class="year_template1"><?php echo "Academic Session: " . $academic_session; ?></div>
				</div>

				<!--template 1 student info-->
				<div class="fullstretch margintop5" align="center">
					<div class="student_info_template1">
						<table class="student_info_table_template1">
							<tr>
								<td class="head1">Name</td>
								<td>-&nbsp;</td>
								<td class="head1"><?php echo $Resultstudents['name']; ?></td>
							</tr>
							<tr>
								<td class="head1">Class</td>
								<td>-&nbsp;</td>
								<td class="head1"><?php echo $class_info['class_name']; ?></td>
							</tr>
							<tr>
								<td class="head1">Father's Name</td>
								<td>-&nbsp;</td>
								<td class="head1"><?php echo $Resultstudents['fathername']; ?></td>
							</tr>
						</table>
					</div>

					<div class="student_info_template1">
						<table class="student_info_table_template1">
							<tr>
								<td class="head1">Admission Number</td>
								<td>-&nbsp;</td>
								<td class="head1"><?php echo $Resultstudents['admission_number']; ?></td>
							</tr>
							<tr>
								<td class="head1">Section</td>
								<td>-&nbsp;</td>
								<td class="head1"><?php echo $section_info['section_name']; ?></td>
							</tr>
							<tr>
								<td class="head1">Mother's Name</td>
								<td>-&nbsp;</td>
								<td class="head1"><?php echo $Resultstudents['mothername']; ?></td>
							</tr>
						</table>
					</div>
				</div>
				<div class="section">
					<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="table_container mt-5 fullstretch">
							<table id="template_table_edit" class="table table-striped">
								<tr>
									<th>&nbsp;</th>
									<th colspan="6">Scholastic Area</th>
								</tr>
								<tr>
									<th class="alignleft">subjects</th>
									<th>Periodic Test (5)</th>
									<th>Portfolio (5)</th>
									<th>Multiple Assessment (5)</th>
									<th>Subject Enrichment Activity (5)</th>
									<th><?php echo $examination; ?> Examination (80)</th>

								</tr>



								<tr>
									<?php $temp_count = 0; ?>
									<th class="texttransformupper alignleft">English</th>

									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>

									<td class="code"><input type="number" min="0" max="80" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>


								</tr>

								<tr>
									<?php $temp_count = 7; ?>
									<th class="texttransformupper alignleft">Punjabi</th>

									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>

									<td class="code"><input type="number" min="0" max="80" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>


								</tr>

								<tr>
									<?php $temp_count = 14; ?>
									<th class="texttransformupper alignleft">Hindi</th>

									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>

									<td class="code"><input type="number" min="0" max="80" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>


								</tr>

								<tr>
									<?php $temp_count = 21; ?>
									<th class="texttransformupper alignleft">Mathematics</th>

									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>

									<td class="code"><input type="number" min="0" max="80" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>


								</tr>

								<tr>
									<?php $temp_count = 28; ?>
									<th class="texttransformupper alignleft">E.V.S.</th>

									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>

									<td class="code"><input type="number" min="0" max="80" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>


								</tr>

								<tr>
									<?php $temp_count = 35; ?>
									<th class="texttransformupper alignleft"> General Knowledge</th>

									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>

									<td class="code"><input type="number" min="0" max="80" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>


								</tr>

								<tr>
									<?php $temp_count = 42; ?>
									<th class="texttransformupper alignleft">Computer Education</th>

									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>
									<td class="code"><input type="number" min="0" max="5" autofocus required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>

									<td class="code"><input type="number" min="0" max="80" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" class="columns_number" value="<?php echo $array[$temp_count]; ?>"></td>


								</tr>

							</table>
						</div>
						<?php $temp_count = 49; ?>
						<div class="margintop20 marginbottom10 fullstretch flexbox-row-spacearound-start" align="center">
							<table class="table">
								<tr>
									<th class="alignleft">Attendance</th>
									<th class="alignleft">
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</th>
								</tr>
							</table>
							<?php
							$temp_count++;
							$temp_count++;
							$temp_count++;
							?>


						</div>


						<div class="table1_container_template1 fullstretch margintop0 table-responsive" align="center">
							<table class="table table-striped" border="1">
								<tr>
									<th colspan="2">
										Co - Scholastic Final
									</th>
									<th colspan="2">
										Personality and Social Traits
									</th>
								</tr>
								<tr>
									<th>Particulars</th>
									<th>Term Exam</th>
									<th>Particulars</th>
									<th>Term Exam</th>
								</tr>
								<tr>
									<td>General Awareness</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									<td>Team Spirit</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
								</tr>
								<tr>
									<td>Computer Science</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
									<td>Neatness</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
								</tr>
								<tr>
									<td>Sports Discipline</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
									<td>Courtesy</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
								</tr>
								<tr>
									<td>Art & Craft</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
									<td>Confidence</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
								</tr>
								<tr>
									<td>Club Activities</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
									<td>Punctuality</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
								</tr>
								<tr>
									<td>Performing Art > Dance & Music</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
									<td>Social & Emotional Development</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
								</tr>
								<tr>
									<td>Work Education</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
									<td>Conversation & Communication</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
								</tr>
								<tr>
									<td>Value Education</td>
									<td class="code"><input type="text" required name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>" value="<?php echo $array[$temp_count]; ?>"></td>
									</td>
									<td>&nbsp;</td>
									<td>&nbsp;</td>
								</tr>
							</table>
						</div>

						<div class="table1_container_template1 fullstretch" align="center">
							<table class="table table-striped" border="1">
								<tr>
									<th>Specific Participation</th>
								</tr>
								<tr>
									<td>
										<b>Participation / Positions in various competitions:</b>
										<br>
										<textarea class="form-control mt-2" name="<?php echo ++$temp_count; ?>" id="col<?php echo $temp_count; ?>"><?php echo $array[$temp_count]; ?></textarea>

										<br>
										<b>Remarks:</b>
										<br>
										<select class="form-control mt-2 mb-2" id="remarks_marksheet" required name="<?php echo ++$temp_count; ?>">
											<?php if ($array[$temp_count] == "") {
											?><option disabled selected value="">Select</option><?php
																							} else {
																								?><option value="<?php echo $array[$temp_count]; ?>" selected><?php echo $array[$temp_count]; ?></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 class="table1_container_template1 fullstretch" align="center">
                    <label for="class_id">Promoted to Class</label><br>
                    <select class="form-control" id="class_id" name="<?php echo ++$temp_count; ?>">
                        <?php
                        // Default "Not Promoted" option
                        if (!isset($array[$temp_count]) || $array[$temp_count] === "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[$temp_count]) && $array[$temp_count] == $rowclass['id']) ? 'selected' : '';
                            echo '<option value="' . htmlspecialchars($rowclass['id']) . '" ' . $selected . '>'
                                 . htmlspecialchars($rowclass['classname']) . '</option>';
                        }
                        ?>
                    </select>
  
                    <label for="new_session_date">New session begins from: </label><br>
                    <input 
                        type="date"
                       class="form-control"
                       id="new_session_date"
                       name="<?php echo ++$temp_count; ?>"
                       value="<?php echo isset($array[$temp_count]) ? htmlspecialchars($array[$temp_count]) : ''; ?>"
                    ><br><br>
                    
                    <button type="submit" id="submit_marksheet">Upload Marksheet</button>
                </div>

                <!-- Display messages -->
                <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>
</body>
</div>

</html>
<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/template12/process.php', // Directly using the URL
				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);
					$("#remarks_marksheet").attr('readonly', true);
					$("#attendance_marksheet").attr('readonly', true);
					$("#submit_marksheet").prop('disabled', true); // Ensure you're targeting the correct button

					// 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);
					$("#remarks_marksheet").attr('readonly', false);
					$("#attendance_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);
							$("#remarks_marksheet").attr('readonly', false);
							$("#attendance_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);
						$("#remarks_marksheet").attr('readonly', false);
						$("#attendance_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>