<?php
// Default null values
$error = [];
$date = date('d/M/Y');
$select = "--select--";
$time = date('h:i:s');

// Check if form is submitted
if (isset($_POST['issue_transfer_btn'])) {
    // Sanitize user inputs
    $reg_number = inject_checker($connection, $_POST['reg_number']);
    $studentName = inject_checker($connection, $_POST['studentName']);
    $studentClass = inject_checker($connection, $_POST['studentClass']);
    $studentParent = inject_checker($connection, $_POST['studentParent']);
    $studentDOB = inject_checker($connection, $_POST['studentDOB']);
    $studentLGA = inject_checker($connection, $_POST['studentLGA']);
    $studentState = inject_checker($connection, $_POST['studentState']);
    $section = inject_checker($connection, $_POST['section']);
    $date_of_last_class = inject_checker($connection, $_POST['date_of_last_class']);
    $date_of_last_att = inject_checker($connection, $_POST['date_of_last_att']);
    $last_class = inject_checker($connection, $_POST['last_class']);
    $indebtedness = inject_checker($connection, $_POST['indebtedness']);
    $conduct = inject_checker($connection, ucwords($_POST['conduct']));
    $cause_of_leaving = inject_checker($connection, ucwords($_POST['cause_of_leaving']));
    $studentPassportSrc = inject_checker($connection, $_POST['studentPassportSrc']);

    // Error checking
    if ($section === $select) {
        $msg = "<p class='text-danger'><b>Error: Section Field Required</b></p>";
    } elseif (empty($studentName)) {
        $msg = "<p class='text-danger'><b>Error: Full Name Field Required</b></p>";
    }
        elseif(empty($reg_number)){
            $msg = "<p class='text-danger'><b>Error: Admission Number Required</b></p>";
        }		
        elseif(empty($studentClass)){
            $msg = "<p class='text-danger'><b>Error: Student Class Field Required</b></p>";
        }
        elseif (empty($studentPassportSrc)) {
            $msg = "<p class='text-danger'><b>Error: Student Passport not provided.</b></p>";
        }
        elseif(empty($studentDOB)){
            $msg = "<p class='text-danger'><b>Error: Date of Birth Required</b></p>";
        }    
        elseif(empty($studentLGA)){
            $msg = "<p class='text-danger'><b>Error: LGA Field Required</b></p>";
        }
        elseif(empty($studentParent)){
            $msg = "<p class='text-danger'><b>Error: Parent Name Field Required</b></p>";
        }		
        elseif(empty($studentState)){
            $msg = "<p class='text-danger'><b>Error: State Field Required</b></p>";
        }				
        elseif(empty($last_class)){
            $msg = "<p class='text-danger'><b>Error: Last Class Field Required</b></p>";
        }
        elseif(empty($date_of_last_class)){
            $msg = "<p class='text-danger'><b>Error: Date of Last Class Passed Field Required</b></p>";
        }
        elseif(empty($date_of_last_att)){
            $msg = "<p class='text-danger'><b>Error: Date of Last Attendance Field Required</b></p>";
        }
        elseif(empty($indebtedness)){
            $msg = "<p class='text-danger'><b>Error: Indebtedness Field Required</b></p>";
        }
        elseif(empty($conduct)){
            $msg = "<p class='text-danger'><b>Error: Conduct Field Required</b></p>";
        }
        elseif(empty($cause_of_leaving)){
            $msg = "<p class='text-danger'><b>Error: Cause of leaving Field Required</b></p>";
        }
    // Add other validation checks here...
    
    // If no errors, insert into database
    if (empty($msg)) {
        $query = "INSERT INTO transfer_certificate (student_name, parent_name, state, lga, dob, reg_number, last_class, section, last_class_date, current_class, last_att_date, indebtedness, conduct, cause_of_leaving, passport, date_issued)
                  VALUES ('$studentName', '$studentParent', '$studentState', '$studentLGA', '$studentDOB', '$reg_number', '$last_class', '$section', '$date_of_last_class', '$studentClass', '$date_of_last_att', '$indebtedness', '$conduct', '$cause_of_leaving', '$studentPassportSrc', '$date')";

        $run_query = mysqli_query($connection, $query);

        if ($run_query) {
            $msg = "<div class='alert alert-success alert-dismissible' role='alert'>
                        <b>Transfer Certificate successfully generated for {$studentName} &nbsp|&nbsp Reg no: {$reg_number}</b>
                        <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>&times;</span>
                        </button>
                    </div>";
        } else {
            $msg = "<div class='alert alert-danger alert-dismissible' role='alert'>
                        <b>Error: Transfer Certificate not successful.</b>
                        <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                            <span aria-hidden='true'>&times;</span>
                        </button>
                    </div>";
        }
    }
}
?>

<div class="page-title">
  <div>
    <h1><i class="fa fa-calendar"></i>Transfer Certificate</h1>
    <p>Issue Transfer Certificate</p>
  </div>
  <div>
    <ul class="breadcrumb">
      <li><a href='student_dashboard.php'><i class="fa fa-home fa-lg"></i></a></li>
      <li><a href="#">Transfer</a></li>
    </ul>
  </div>
</div>

<div class="card">
    <?php
        if(isset($msg)){
            echo $msg;
        }
    ?>
    <div class='row'>
        <div class='col-xs-12 col-sm-12 col-md-12'>
			<div class='panel panel-primary'>
                <div class='panel-heading'>
                    <h3 class='log-text'>Please Fill the form to Issue a Transfer Certificate</h3>
                </div>
                <div class='panel-body'>
                    <form method='POST' action=''>
                        <div class="row">
                        <div class="col-lg-12">
                            <center>
                                <img src="../uploads/students/none.jpg" alt="Student Passport" id="studentPassport" 
                                    style="border-radius: 100px; border: 7px solid #ccc; width: 140px; height: 140px" />
                            </center>
                        </div>
                        <input type="hidden" name="studentPassportSrc" id="studentPassportSrc" />

                        <br />           
                        <div class="input-group">
                            <span class='input-group-addon' id='basic-addon2'>ADMISSION NO</span>
                            <input type="text" class="form-control" name="reg_number" id="reg_number" 
                                placeholder="Student Admission No" onchange="fetchStudentDetails(this.value)">
                        </div>
                        <br />
                        <div class="input-group">
                            <span class='input-group-addon' id='basic-addon2'>FULL NAME</span>
                            <input type="text" class="form-control" name="studentName" id="studentName" 
                                placeholder="Student Name" class='form-control'>
                        </div>
                        <br />
                        <div class="input-group">
                            <span class='input-group-addon' id='basic-addon2'>PARENT NAME</span>
                            <input type="text" class="form-control" name="studentParent" id="studentParent" 
                                placeholder="Parent Name" class='form-control'>
                        </div>
                        <br />
                        <div class="input-group">
                            <span class='input-group-addon' id='basic-addon2'>STATE</span>
                            <input type="text" class="form-control" name="studentState" id="studentState" 
                                placeholder="Student State" class='form-control'>
                        </div>
                        <br />
                        <div class="input-group">
                            <span class='input-group-addon' id='basic-addon2'>L.G.A</span>
                            <input type="text" class="form-control" name="studentLGA" id="studentLGA" 
                                placeholder="Student L.G.A" class='form-control'>
                        </div>
                        <br />
                        <div class="input-group">
                            <span class='input-group-addon' id='basic-addon2'>DATE OF BIRTH</span>
                            <input type="text" class="form-control" name="studentDOB" id="studentDOB" 
                                placeholder="Student Name" class='form-control'>
                        </div>
                        <br />
                        <div class="input-group">
                            <span class='input-group-addon' id='basic-addon2'>CURRENT CLASS</span>
                            <input type="text" class="form-control" name="studentClass" id="studentClass" 
                                placeholder="Student Class" class='form-control'>
                        </div>
                        <br />

                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>SECTION</span>
                            <select class='form-control' name='section'>
                                <option selected><?php echo $select; ?></option>
                                <?php
                                    $section_array = array("NURSERY", "PRIMARY", "SECONDARY");
                                    foreach($section_array as $section){
                                        echo "<option>{$section}</option>";
                                    }
                                ?>
                            </select>
                        </div>
                        <br />                       
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>LAST CLASS</span>
                            <select class='form-control' name='last_class'>
                                <option selected><?php echo $select; ?></option>
                                    <?php
                                        $query = " SELECT * FROM `classes` ";
                                        $run_query = mysqli_query($connection, $query);
                                        if(mysqli_num_rows($run_query) > 0){
                                            while($result = mysqli_fetch_assoc($run_query)){
                                                $publish_result_classes = $result['classes'];
                                                echo"
                                                    <option>{$publish_result_classes}</option>
                                                ";
                                            }
                                        }
                                    ?>
                            </select>
                        </div>
                        <br />                        
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>DATE OF LAST CLASS PASSED</span>
                            <input type='text' name='date_of_last_class' placeholder='' class='form-control' />
                        </div>
                        <br />
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>DATE OF LAST ATTENDANCE AT THE ABOVE SCHOOL</span>
                            <input type='text' name='date_of_last_att' placeholder='' class='form-control' />
                        </div>
                        <br />
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>INDEBTEDNESS TO THE SCHOOL:</span>
                            <input type='text' name='indebtedness' class='form-control' />
                        </div>
                        <br />
                        <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>CONDUCT:</span>
                            <textarea class="form-control txt"  name="conduct" id="conduct" placeholder="If unsatisfactory, give reasons..."></textarea>
                        </div>
                        <br />
                         <div class='input-group'>
                            <span class='input-group-addon' id='basic-addon2'>CAUSE OF LEAVING:</span>
                            <textarea class="form-control txt" name="cause_of_leaving" id="cause_of_leaving" placeholder="State Cause of leaving"></textarea>
                        </div>
                        <br />
                        <p id='btnsubmit'><input type='submit' name='issue_transfer_btn' id='submit' value='Issue Transfer' class='btn btn-large btn-primary login_btn text-center' /></p>
                    </form>
                </div>		
            </div>
        </div>
    </div>
</div>

<script>
// Update the hidden input with the image source
const studentPassport = document.getElementById('studentPassport');
const studentPassportSrc = document.getElementById('studentPassportSrc');

// Update hidden field whenever image src is set dynamically
studentPassport.addEventListener('load', () => {
    studentPassportSrc.value = studentPassport.src;
});

function fetchStudentDetails(regNumber) {
    if (regNumber !== "") {
        // Create AJAX request
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "../fetch_student_details.php", true); // Update with the correct path to your PHP script
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                var response = JSON.parse(xhr.responseText); // Parse JSON response
                
                if (response.status === "success") {
                    // Populate fields with student details
                    document.getElementById("studentName").value = response.fullname;
                    document.getElementById("studentClass").value = response.class;
					document.getElementById("studentState").value = response.state;
					document.getElementById("studentLGA").value = response.lga;
					document.getElementById("studentDOB").value = response.date_of_birth;
					document.getElementById("studentParent").value = response.guardian_name;
					document.getElementById("studentPassport").src = response.passport;
                } else {
                    // Handle errors
                    alert(response.message);
                    document.getElementById("studentName").value = "";
                    document.getElementById("studentClass").value = "";
					document.getElementById("studentState").value = "";
					document.getElementById("studentLGA").value = "";
					document.getElementById("studentDOB").value = "";
					document.getElementById("studentParent").value = "";
					document.getElementById("studentPassport").src = "";
                }
            }
        };

        // Send request with reg_number
        xhr.send("reg_number=" + encodeURIComponent(regNumber));
    } else {
        alert("Please enter a registration number.");
        document.getElementById("studentName").value = "";
        document.getElementById("studentClass").value = "";
		document.getElementById("studentState").value = "";
		document.getElementById("studentLGA").value = "";
		document.getElementById("studentDOB").value = "";
		document.getElementById("studentParent").value = "";
		document.getElementById("studentPassport").src = "";
    }
}
</script>
