<?php
// Function to delete a specific invoice by ID
function deleteTransfer($connection, $transferId) {
    $query = "DELETE FROM transfer_certificate WHERE id = ?";
    $stmt = $connection->prepare($query);
    $stmt->bind_param("s", $transferId); // Use "s" for string type since invoice_id is likely a string
    return $stmt->execute();
}

// Function to get all invoices from the database
function getTransferList($connection) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_transfer_id'])) {
        $transferId = trim($_POST['delete_transfer_id']);
        
        // Ensure t is valid before proceeding
        if (!empty($transferId)) {
            deleteTransfer($connection, $transferId);
        }
    }

    // Fetch all invoices
    $query = "SELECT id, date_issued, student_name, current_class, section, last_att_date, reg_number
              FROM transfer_certificate 
              ORDER BY id DESC";
    $result = $connection->query($query);
    $transferList = [];

    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $transferList[] = $row;
        }
    }
    return $transferList;
}
// Fetch all invoices
$transferList = getTransferList($connection);
?>

<?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) {
        $_SESSION['msg'] = "Section Field Required";
        $_SESSION['type'] = "error";
    } elseif (empty($studentName)) {
	        $_SESSION['msg'] = "Full Name Field Required";
	        $_SESSION['type'] = "error";
    }
        elseif(empty($reg_number)){
            $_SESSION['msg'] = "Admission Number Required";
	        $_SESSION['type'] = "error";
        }		
        elseif(empty($studentClass)){
	        $_SESSION['msg'] = "Student Class Field Required";
	        $_SESSION['type'] = "error";
        }
        elseif (empty($studentPassportSrc)) {
            $_SESSION['msg'] = "Student Passport not Provided";
	        $_SESSION['type'] = "error";
        }
        elseif(empty($studentDOB)){
            $_SESSION['msg'] = "Date of Birth Required";
	        $_SESSION['type'] = "error";
        }    
        elseif(empty($studentLGA)){
            $_SESSION['msg'] = "L.G.A Field Required";
	        $_SESSION['type'] = "error";
        }
        elseif(empty($studentParent)){
	        $_SESSION['msg'] = "Parent Name Field Required";
	        $_SESSION['type'] = "error";
        }		
        elseif(empty($studentState)){
           	$_SESSION['msg'] = "State Field Required";
	        $_SESSION['type'] = "error";
        }				
        elseif(empty($last_class)){
        	$_SESSION['msg'] = "Last Class Field Required";
	        $_SESSION['type'] = "error";
        }
        elseif(empty($date_of_last_class)){
        	$_SESSION['msg'] = "Date of Last Class Passed Field Required";
	        $_SESSION['type'] = "error";
        }
        elseif(empty($date_of_last_att)){
   	        $_SESSION['msg'] = "Date of Last Attendance Field Required";
	        $_SESSION['type'] = "error";
        }
        elseif(empty($indebtedness)){
        	$_SESSION['msg'] = "Indebtedness Field Required";
	        $_SESSION['type'] = "error";
        }
        elseif(empty($conduct)){
        	$_SESSION['msg'] = "Conduct Field Required";
	        $_SESSION['type'] = "error";
        }
        elseif(empty($cause_of_leaving)){
        	$_SESSION['msg'] = "Cause of leaving Field Required";
	        $_SESSION['type'] = "error";
        }
    // Add other validation checks here...
    
    // If no errors, insert into database
    if (empty($_SESSION['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) {
            $_SESSION['msg'] = "Transfer Certificate successfully generated for {$studentName} &nbsp|&nbsp Reg no: {$reg_number}";
            $_SESSION['type'] = "success";
            
        } else {
            $_SESSION['msg'] = "Transfer Certificate not successful.";
            $_SESSION['type'] = "error";                      
        }
    }
        // Redirect once after logic
    header("Location: modules.php?transfer_list");
    exit();
}
?>

<!-- HTML Section -->
<div class='card'>
    <div class='panel panel-primary'>
        <div class='panel-heading'>
            <h4 class='text-center'>TRANSFER CERTIFICATES</h4>
        </div>
        
        <div class="row">
            <div class="col-md-12"> <!-- Full width table container -->
            <br />
            <!-- Button to trigger modal -->
            <div class='mb-3 text-right'>
				<button type="button" class="btn btn-sm btn-success" data-toggle="modal" data-target="#issueTransferModal">+ Issue Transfer</button>
			</div>			
                <?php if (!empty($transferList)) { ?>
                    <div class='table-responsive'>
                        <table class='table table-striped'>
                            <thead>
                                <tr>
                                    <!--th>S/N</th--> <!-- Added Serial Number Column -->
									<th>REF NO</th>
                                    <th>Date Issued</th>                                    
                                    <th>Student Name</th>
									<th>Adm NO</th>
                                    <th>Class</th>
                                    <th>Section</th>
                                    <!--th>Last Attendance</th-->                                    
                                    <th>Print</th>
									<!--th>Edit</th-->
                                    <th>Delete</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                $sn = 1; // Initialize serial number counter
                                foreach ($transferList as $transferDetails): ?>
                                    <tr>
                                        <!--td><?php echo $sn++; ?></td--> <!-- Increment and display S/N -->
                                        <td><?php echo htmlspecialchars($transferDetails["id"]); ?></td>
                                        <td><?php echo htmlspecialchars($transferDetails["date_issued"]); ?></td>
                                        <td><?php echo htmlspecialchars($transferDetails["student_name"]); ?></td>
										<td><?php echo htmlspecialchars($transferDetails["reg_number"]); ?></td>
										<td><?php echo htmlspecialchars($transferDetails["current_class"]); ?></td>
										<td><?php echo htmlspecialchars($transferDetails["section"]); ?></td>
										<!--td><?php echo htmlspecialchars($transferDetails["last_att_date"]); ?></td-->
                                        <td>
                                             <a href="print_certificate.php?id=<?php echo urlencode($transferDetails["id"]); ?>" title="Print Certificate">
												<i class="fa fa-print"></i>
											</a>
                                        </td>
										<!--td>
											<a href="modules.php?edit_transfer_certificate&update_id=<?php echo urlencode($transferDetails['id']); ?>" title="Edit Certificate">
												<i class="fa fa-edit"></i>
											</a>
										</td-->
                                        <td>
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="delete_transfer_id" value="<?php echo htmlspecialchars($transferDetails["id"]); ?>">
                                                <button type="submit" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to delete this TRANSFER CERTIFICATE???');">
                                                    <i class="fa fa-trash"></i>
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php } else { ?>
                    <div class="alert alert-warning text-center" role="alert">
                        <strong>No Transfer Certificates Found!</strong> Add New Certificates to display them here.
                    </div>
                <?php } ?>
            </div>
        </div>
    </div>
</div>


<!-- Modal -->
<div class="modal fade" id="issueTransferModal" tabindex="-1" role="dialog" aria-labelledby="issueTransferModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl" role="document"> <!-- modal-xl for wide form -->
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="issueTransferModalLabel">ISSUE TRANSFER</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>

      <div class="modal-body">
        <h5 class='text-center mb-4'>Please Fill the form to Issue a Transfer Certificate</h5>
        <form method='POST' action=''>
          <div class="text-center mb-3">
            <img src="image/user.png" alt="Student Passport" id="studentPassport"
              style="border-radius: 100px; border: 7px solid #ccc; width: 140px; height: 140px" />
          </div>
          <input type="hidden" name="studentPassportSrc" id="studentPassportSrc" />

          <div class="form-group">
            <label>ADMISSION NO</label>
            <input type="text" class="form-control" name="reg_number" id="reg_number"
              placeholder="Student Admission No" onchange="fetchStudentDetails(this.value)">
          </div>

          <div class="form-group">
            <label>FULL NAME</label>
            <input type="text" class="form-control" name="studentName" id="studentName" placeholder="Student Name">
          </div>

          <div class="form-group">
            <label>PARENT NAME</label>
            <input type="text" class="form-control" name="studentParent" id="studentParent" placeholder="Parent Name">
          </div>

          <div class="form-group">
            <label>STATE</label>
            <input type="text" class="form-control" name="studentState" id="studentState" placeholder="Student State">
          </div>

          <div class="form-group">
            <label>L.G.A</label>
            <input type="text" class="form-control" name="studentLGA" id="studentLGA" placeholder="Student L.G.A">
          </div>

          <div class="form-group">
            <label>DATE OF BIRTH</label>
            <input type="text" class="form-control datepicker" name="studentDOB" id="studentDOB" placeholder="Date of Birth">
          </div>

          <div class="form-group">
            <label>CURRENT CLASS</label>
            <input type="text" class="form-control" name="studentClass" id="studentClass" placeholder="Student Class">
          </div>

          <div class="form-group">
            <label>SECTION</label>
            <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>

          <div class="form-group">
            <label>LAST CLASS</label>
            <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>

          <div class="form-group">
            <label>DATE OF LAST CLASS PASSED</label>
            <input type="text" class="form-control datepicker" name="date_of_last_class" placeholder="">
          </div>

          <div class="form-group">
            <label>DATE OF LAST ATTENDANCE AT THE ABOVE SCHOOL</label>
            <input type="text" class="form-control datepicker" name="date_of_last_att" placeholder="">
          </div>

          <div class="form-group">
            <label>INDEBTEDNESS TO THE SCHOOL</label>
            <input type="text" class="form-control" name="indebtedness" placeholder="">
          </div>

          <div class="form-group">
            <label>CONDUCT</label>
            <textarea class="form-control" name="conduct" placeholder="If unsatisfactory, give reasons..."></textarea>
          </div>

          <div class="form-group">
            <label>CAUSE OF LEAVING</label>
            <textarea class="form-control" name="cause_of_leaving" placeholder="State cause of leaving"></textarea>
          </div>

          <div class="text-center">
            <input type="submit" name="issue_transfer_btn" value="Issue Transfer" class="btn btn-primary btn-lg">
          </div>
        </form>
      </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>


