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

// 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] = "";
		}
	} else {
		$array = array();
		$counter = 1;
		foreach ($arrayfetch as $element) {
			$array[$counter] = $element;
			$counter++;
		}
	}
} else {
	//deleting any pre entries
	// 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.");
	}
	for ($i = 1; $i <= $cols; $i++) {
		$array[$i] = "";
	}
}
?>
<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Template 11</title>
	     <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
	<link href="<?php echo 'https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template11/style_template11.css?key=' . time(); ?>" type="text/css" rel="stylesheet">

</head>
<body>
    <div class="container_marksheet_template1">
        <div class="content_container_template1">
          <div class="header_template1">
            <div class="logo_div_img_template1">
              <img class="images"  src="<?php echo $institutions['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['branch_code']; ?></span><?php if($branch['branch_code'] != ""){
                ?><br><?php
              }
              ?>
              <span class="heading_address_template1"><?php echo $branch['address'];
              if($branch['pincode']!="")
              {
                echo " - ".$branch['pincode'];  
              }
              ?></span><br>
              <span class="contact_template1"><?php echo $branch['contact_number'];
              if($branch['email']!="")
              {
                echo ", &nbsp;".strtolower($branch['email']);
              }
              ?></span>
            </div>
          </div>

          <div class="header_info_container">
              <div class="heading_report_template1">Progress Report</div>
              <div class="year_template1">Academic Session <?php echo $academic_session;?></div>
          </div>

          <!-- Student Info -->
          <div class="student-info-container">
              <table class="student_info_table_template1">
                <tbody>
                  <tr>
                    <td class="info-label">Name</td>
                    <td class="info-colon">:</td>
                    <td class="info-value"><?php echo $Resultstudents['name']; ?></td>
                    <td class="info-label">Admission Number</td>
                    <td class="info-colon">:</td>
                    <td class="info-value"><?php echo $Resultstudents['admission_number']; ?></td>
                  </tr>
                  <tr>
                    <td class="info-label">Father's Name</td>
                    <td class="info-colon">:</td>
                    <td class="info-value"><?php echo $Resultstudents['fathername']; ?></td>
                    <td class="info-label">Class</td>
                    <td class="info-colon">:</td>
                    <td class="info-value"><?php echo $class_info['class_name']; ?></td>
                  </tr>
                  <tr>
                    <td class="info-label">Mother's Name</td>
                    <td class="info-colon">:</td>
                    <td class="info-value"><?php echo $Resultstudents['mothername']; ?></td>
                    <td class="info-label">Section</td>
                    <td class="info-colon">:</td>
                    <td class="info-value"><?php echo $section_info['section_name']; ?></td>
                  </tr>
                </tbody>
              </table>
			    </div>

          <form name="upload_student_marksheet"   id="upload_student_marksheet">
    	      <input type="hidden" name="marksheet_id" value="<?php echo $marksheet_id; ?>">
              <input type="hidden" name="institution_id" value="<?php echo $institution_id; ?>">
              <input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
              <input type="hidden" name="jwt_token" value="<?php echo $jwttoken; ?>">
              <input type="hidden" name="api_signature" value="<?php echo $api_signature;?>">

            <div class="evaluation-container">
                <table class="evaluation_table" border="1">
                    <thead>
                        <tr>
							<th colspan="3" class="report-title">Half Yearly</th>
						</tr>
                        <tr>
                            <th colspan="2">Subject</th>
                            <th>Evaluation</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <th colspan="2" class="subject-header">English</th>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can write neatly</td>
                            <td><input type="text" name="1" value="<?php echo $array[1];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can narrate stories effectively</td>
                            <td><input type="text" name="2" value="<?php echo $array[2];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can recite poems with expressions</td>
                            <td><input type="text" name="3" value="<?php echo $array[3];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can recognize and read properly</td>
                            <td><input type="text" name="4" value="<?php echo $array[4];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <th colspan="2" class="subject-header">Mathematics</th>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can identify the numbers correctly</td>
                            <td><input type="text" name="5" value="<?php echo $array[5];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can grasp the combination of numbers</td>
                            <td><input type="text" name="6" value="<?php echo $array[6];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can count and write in sequence</td>
                            <td><input type="text" name="7" value="<?php echo $array[7];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <th colspan="2" class="subject-header">Punjabi</th>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can express the word</td>
                            <td><input type="text" name="8" value="<?php echo $array[8];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can write properly</td>
                            <td><input type="text" name="9" value="<?php echo $array[9];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <th colspan="2" class="subject-header">E.V.S. / General Knowledge</th>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can identify</td>
                            <td><input type="text" name="10" value="<?php echo $array[10];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can write properly</td>
                            <td><input type="text" name="11" value="<?php echo $array[11];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can express / understand the word / pictures</td>
                            <td><input type="text" name="12" value="<?php echo $array[12];?>" required class="values"></td>
                        </tr>
                        <tr>
                            <th colspan="2" class="subject-header">Conversation</th>
                            <td></td>
                        </tr>
                        <tr>
                            <td colspan="2">Can give conversation answer</td>
                            <td><input type="text" name="13" value="<?php echo $array[13];?>" required class="values"></td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="remarks-container">
                <div class="remarks-box">
                    <strong>Remarks:
                      <select class="form-control" id="remarks_marksheet" required name="14">
                        <?php if($array[14]=="")
                        {
                          ?><option disabled selected>Select</option><?php
                        }
                        else
                        {
                          ?><option value="<?php echo $array[14];?>" selected><?php echo $array[14];?></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>
                    </strong>
                </div>
            </div>

            <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="date-container">
                <div class="date_footer">Date:
                 <?php echo date('d-m-Y'); ?>
                </div>
            </div>
 
            <div class="disclaimer">
              * Incase of any discrepancies in marksheet, please contact school administration.
            </div>
                
            <div class="submit">
                <button type="submit" id="submit_marksheet">Upload Marksheet</button>
            </div>
          </form><br>
            <!--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>
</body>
</html>

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

        // Create a new FormData object to handle all form fields
        var formData = new FormData(this);

        $.ajax({
            type: 'POST',
            url: 'https://rejoicebilldesk.in/rjllearning_development/resources/marksheet_template/template11/process.php',
            data: formData, // Use FormData object
            contentType: false,
            cache: false,
            processData: false, // Important to prevent jQuery from processing the data
            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); 
                $("#submit_marksheet").html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Uploading...');
            },
            success: function(resp) {
                // Parse and handle the response
                try {
                    var response = JSON.parse(resp);
                    if (response.status === 1) { 
                        // Re-enable form fields and submit button on success
                        $(".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');

                        // Display success message
                        $("#success_message").text("Upload successful.");
                        $("#displayadd_homework_success").fadeIn(300);
                        setTimeout(function() {
                            $("#displayadd_homework_success").fadeOut(300);
                        }, 3000);
                    } else {
                        throw new Error(response.response || 'Unknown error');
                    }
                } catch (e) {
                    handleFormError(e);
                }
            },
            error: function(xhr, status, error) {
                handleFormError(error);
            }
        });
    });

    function handleFormError(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');

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

</script>