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

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

foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || empty($postdata[$field])) {
        errorreturn("All * fields are required.$field");
    }
}

validateApiSignature($postdata['api_signature']);
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract user details from JWT token
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

// Validate user access and get specific database name
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["superadmin","admin","principal","teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

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

// Fetch student data
$ExecuteSqlTemplate = $conn_rjllearning_specific->prepare("SELECT * FROM students WHERE institution_id = ? and id=?");
$ExecuteSqlTemplate->execute([$institution_id, $student_id]);
$Resultstudents = $ExecuteSqlTemplate->fetch(PDO::FETCH_ASSOC);

if (!$Resultstudents) {
    errorreturn("student does not exist.");
}

$branch_id = $Resultstudents['branch_id'];
$class_id = $Resultstudents['class_id'];
$section_id = $Resultstudents['section_id'];

$class_info = getClass($conn_rjllearning_specific, $institution_id, $class_id);
$section_info = getSection($conn_rjllearning_specific, $institution_id, $section_id);

// Fetch academic session
$SqlTemplate = "SELECT * FROM academic_session WHERE institution_id = ? AND active_academic_session = ?";
$StmtTemplate = $conn_rjllearning_specific->prepare($SqlTemplate);
$StmtTemplate->execute([$institution_id, 1]);
$result = $StmtTemplate->fetchAll(PDO::FETCH_ASSOC);

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

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

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

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

// Fetch marksheet template info
$ExecuteSqlTemplate = $conn_rjllearning_specific->prepare("SELECT examination_name,template_id,academic_session FROM marksheet WHERE institution_id = ? and id=?");
$ExecuteSqlTemplate->execute([$institution_id,$marksheet_id]);
$ResultTemplates = $ExecuteSqlTemplate->fetch(PDO::FETCH_ASSOC);

if (!$ResultTemplates) {
    errorreturn("examination_name does not exist.");
}

$examination = $ResultTemplates['examination_name'];
$template_id = $ResultTemplates['template_id'];
$academic_session = $ResultTemplates['academic_session'];

// Fetch template columns info
$ExecuteSqlTemplate = $conn_rjllearning->prepare("SELECT cols, template_name FROM template_info WHERE id = ? ");
$ExecuteSqlTemplate->execute([$template_id]);
$ResultTemplate = $ExecuteSqlTemplate->fetch(PDO::FETCH_ASSOC);

if (!$ResultTemplate) {
    errorreturn("Marksheet Template does not exist.");
}

$cols = $ResultTemplate['cols'];

// Fetching marksheet data
$stmt = $conn_rjllearning_specific->prepare("SELECT data FROM student_marksheet_data WHERE student_id = ? AND marksheet_id = ? AND institution_id = ?");
$stmt->execute([$student_id, $marksheet_id, $institution_id]); 
$fetchmarksheet_data = $stmt->fetch(PDO::FETCH_ASSOC);

if ($fetchmarksheet_data) {
    // Unserialize the 'data' column
    $arrayfetch = json_decode($fetchmarksheet_data['data'], true);

    // Check the number of columns in the fetched data
    if (count($arrayfetch) != $cols) {
        // Deleting any pre-existing entries
        $deleteExistingData = $conn_rjllearning_specific->prepare("DELETE FROM student_marksheet_data WHERE student_id = ? AND marksheet_id = ?");
        if (!$deleteExistingData->execute([$student_id, $marksheet_id])) {
            errorreturn("Failed to delete existing data.");
        }
		for($i=1;$i<=$cols;$i++)
		{
			$array[$i]=0;
		}
		$array[5]="";
		$array[6]="";
	}
	else
	{
		$array=array();
		$counter=1;
		foreach($arrayfetch as $element)
		{
			$array[$counter]=$element;
			$counter++;
		}
	}
}
else
{
	$deleteExistingData = $conn_rjllearning_specific->prepare("DELETE FROM student_marksheet_data WHERE student_id = ? AND marksheet_id = ?");
	if (!$deleteExistingData->execute([$student_id, $marksheet_id])) {
		errorreturn("Failed to delete existing data.");
	}
	for ($i = 1; $i <= $cols; $i++) {
		$array[$i] = 0;
	}
	$array[5]="";
	$array[6]="";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Template 18 Marks Upload</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/template18/style_template18.css?key=' . time(); ?>" type="text/css" rel="stylesheet">
    <style>
        /* Additional styles for better form presentation */
        .form-container {
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-control {
            width: 100%;
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .marks-input {
            width: 80px;
            text-align: center;
            padding: 6px;
        }
        .subject-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #eee;
        }
        .subject-name {
            flex: 1;
            font-weight: 500;
        }
        .subject-marks {
            width: 120px;
            text-align: center;
        }
        #submit_marksheet {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 15px;
            width: 100%;
        }
        #submit_marksheet:hover {
            background-color: #45a049;
        }
        .remarks-container {
            margin: 20px 0;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 4px;
        }
        .message-container {
            margin: 15px 0;
            padding: 10px;
            border-radius: 4px;
            text-align: center;
        }
        .error-message {
            background-color: #ffebee;
            color: #c62828;
        }
        .success-message {
            background-color: #e8f5e9;
            color: #2e7d32;
        }
    </style>
</head>
<body>
    <div class="container_marksheet_template1">
        <div class="content_container_template1">
            
            <!-- Header with logo and school information -->
            <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="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 endif; ?>
                    <span class="heading_address_template1"><?php echo $branch['address'];
                    if($branch['pincode']!="") {
                        echo " - ".$branch['pincode'];  
                    }
                    ?></span><br>
                    <span class="contact_template1" style="text-transform: lowercase;"><?php echo $branch['contact_number'];
                    if($branch['email']!="") {
                        echo ", &nbsp;".strtolower($branch['email']);
                    }
                    ?></span>
                </div>
            </div>
            
            <!-- Report heading and academic year -->
            <div class="fullstretch header_info_container" align="center">
                <div class="fullstretch heading_report_template1">Progress Report</div>
                <div class="year_template1">Academic Session <?php echo $academic_session;?></div>
            </div>
            
            <!-- Student information section -->
            <div class="fullstretch" align="center">
                <div class="student_info_template1">
                    <table class="student_info_table_template1">
                        <tr>
                            <td>Name</td>
                            <td><?php echo $Resultstudents['name']; ?></td>
                        </tr>
                        <tr>
                            <td>Class</td>
                            <td><?php echo $class_info['class_name']; ?></td>
                        </tr>
                        <tr>
                            <td>Father's Name</td>
                            <td><?php echo $Resultstudents['fathername']; ?></td>
                        </tr>
                    </table>
                </div>
                <div class="student_info_template1">
                    <table class="student_info_table_template1">
                        <tr>
                            <td>Admission Number</td>
                            <td><?php echo $Resultstudents['admission_number']; ?></td>
                        </tr>
                        <tr>
                            <td>Section</td>
                            <td><?php echo $section_info['section_name'];?></td>
                        </tr>
                        <tr>
                            <td>Mother's Name</td>
                            <td><?php echo $Resultstudents['mothername']; ?></td>
                        </tr>
                    </table>
                </div>
            </div>
            
            <!-- Enhanced Marks form -->
            <div class="form-container">
                <form name="upload_student_marksheet" action="" method="post" id="upload_student_marksheet">
                    <input type="hidden" name="marksheet_id" value="<?php echo $marksheet_id; ?>">
                    <input type="hidden" name="institution_id" value="<?php echo $institution_id; ?>">
                    <input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
                    <input type="hidden" name="jwt_token" value="<?php echo $jwttoken; ?>">
                    <input type="hidden" name="api_signature" value="<?php echo $api_signature;?>">
                    
                    <h3 style="text-align: center; margin-bottom: 20px;">Term Examination Marks</h3>
                    
                    <div class="marks-table">
                        <div style="display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 2px solid #ddd; font-weight: bold;">
                            <div style="flex: 1;">Subject</div>
                            <div style="width: 120px; text-align: center;">Marks Obtained (Max: 20)</div>
                        </div>
                        
                        <div class="subject-row">
                            <div class="subject-name">English</div>
                            <div class="subject-marks">
                                <input type="number" min="0" max="20" autofocus required name="1" id="col1" class="marks-input" value="<?php echo $array[1];?>">
                            </div>
                        </div>
                        
                        <div class="subject-row">
                            <div class="subject-name">Mathematics</div>
                            <div class="subject-marks">
                                <input type="number" min="0" max="20" required name="2" id="col2" class="marks-input" value="<?php echo $array[2];?>">
                            </div>
                        </div>
                        
                        <div class="subject-row">
                            <div class="subject-name">E.V.S.</div>
                            <div class="subject-marks">
                                <input type="number" min="0" max="20" required name="3" id="col3" class="marks-input" value="<?php echo $array[3];?>">
                            </div>
                        </div>
                        
                        <div class="subject-row">
                            <div class="subject-name">Punjabi</div>
                            <div class="subject-marks">
                                <input type="number" min="0" max="20" required name="4" id="col4" class="marks-input" value="<?php echo $array[4];?>">
                            </div>
                        </div>
                    </div>
                    
                    <div class="remarks-container">
                        <label for="remarks_marksheet" style="display: block; margin-bottom: 8px; font-weight: bold;">Remarks</label>
                        <select class="form-control" id="remarks_marksheet" required name="6">
                            <?php if($array[6] == ""): ?>
                                <option disabled selected value="">Select Remarks</option>
                            <?php else: ?>
                                <option value="<?php echo $array[6];?>" selected><?php echo $array[6];?></option>
                            <?php endif; ?>
                            <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>
                    </div>
                    
                    <button type="submit" id="submit_marksheet">Upload Marksheet</button>
                    
                    <!-- Display messages -->
                    <div id="error_div" class="message-container error-message" style="display:none;">
                        <span id="error_message"></span>
                    </div>
                    <div id="displayadd_homework_success" class="message-container success-message" style="display:none;">
                        <span id="success_message"></span>
                    </div>
                </form>
            </div>
            
            <!-- Signature section -->
            <div class="fullstretch margintop50" align="center">
                <div class="student_info_template1">
                    <table class="student_info_table_template1">
                        <tr>
                            <td>Class Incharge</td>
                        </tr>
                    </table>
                </div>
                <div class="student_info_template1">
                    <table class="student_info_table_template1">
                        <tr>
                            <td>Principal / Headmistress</td>
                        </tr>
                    </table>
                </div>
            </div>
            
            <!-- Date and footer -->
            <div class="date_footer fullstretch margintop50" align="left">
                <?php echo date('Y-m-d');?>
            </div>
            
            <div class="fullstretch margintop20" align="center" style="color:red;font-size:10pt;">
                * Incase of any discrepancies in marksheet, please contact school administration.
            </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/template18/process.php',
                    data: new FormData(this),
                    contentType: false,
                    cache: false,
                    processData: false,
                    beforeSend: function() {
                        // Disable form fields and the submit button
                        $(".marks-input").attr('readonly', true);
                        $("#remarks_marksheet").attr('disabled', true);
                        $("#submit_marksheet").prop('disabled', true);
                        $("#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
                        $(".marks-input").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").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
                                $(".marks-input").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
                            $(".marks-input").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").fadeIn(300);
                            setTimeout(function() {
                                $("#error_div").fadeOut(300);
                            }, 5000);
                        }
                    }
                });
            });
        });
    </script>
</body>
</html>