<?php
$student = null;
$error = "";

// Fetch student details
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fetch_student_btn']) && !empty($_POST['reg_number'])) {
    $reg = $_POST['reg_number'];
    $stmt = $connection->prepare("SELECT * FROM students WHERE reg_number = ?");
    $stmt->bind_param("s", $reg);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $student = $result->fetch_assoc();
    } else {
        $_SESSION['msg'] = "No student found with that admission number.";
        $_SESSION['type'] = "error";
    }
    $stmt->close();
        
}

// Delete logic
function deleteTransfer($connection, $id) {
    $stmt = $connection->prepare("DELETE FROM transfer_certificate WHERE id = ?");
    $stmt->bind_param("i", $id);
    return $stmt->execute();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_transfer_id'])) {
    $transferId = intval($_POST['delete_transfer_id']);
    if (!empty($transferId)) {
        deleteTransfer($connection, $transferId);
        $_SESSION['msg'] = "Transfer Certificate Deleted Successfully";
        $_SESSION['type'] = "success";
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}

// Get list
function getTransferList($connection) {
    $query = "SELECT * FROM transfer_certificate ORDER BY id ASC";
    $result = $connection->query($query);
    $list = [];
    if ($result && $result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            $list[] = $row;
        }
    }
    return $list;
}

$transferList = getTransferList($connection);
?>
<?php
$error = [];
$date = date('Y-m-d'); // MySQL date format
$select = "--select--";
$time = date('H:i:s');

if (isset($_POST['issue_transfer_btn'])) {
    // Sanitize 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']);

    // Validation
    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'] = "LGA 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";
    } else {
        $stmt = $connection->prepare(
            "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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
        );

        if ($stmt) {
            $stmt->bind_param(
                "ssssssssssssssss",
                $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
            );

            if ($stmt->execute()) {
                $_SESSION['msg'] = "Transfer Certificate successfully generated for {$studentName} | Reg no: {$reg_number}";
                $_SESSION['type'] = "success";
            } else {
                $_SESSION['msg'] = "Transfer Certificate not successful: " . $stmt->error;
                $_SESSION['type'] = "error";
            }

            $stmt->close();
        } else {
            $_SESSION['msg'] = "Statement preparation failed: " . $connection->error;
            $_SESSION['type'] = "error";
        }
    }

    header("Location: transfer_list");
    exit();
}
?>


<!-- Student Search Form -->
<div class="card mb-4">
    <div class="card-body">
        <h5 class="text-center">Search for Student to Issue Transfer</h5>
        <form method="POST" class="form-inline justify-content-center">
            <div class="form-group mx-sm-3 mb-2">
                <input type="text" class="form-control" name="reg_number" placeholder="Enter Admission Number" required>
            </div>
            <button type="submit" name="fetch_student_btn" class="btn btn-primary mb-2">Fetch Student</button>
        </form>
    </div>
</div>

<!-- Transfer Certificate List 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">
                <br />                
                <?php if (!empty($transferList)) { ?>
                    <div class='table-responsive'>
                        <table class='table table-striped' id = 'myTable'>
                            <thead>
                                <tr>
                                    <th>REF NO</th>
                                    <th>Date Issued</th>
                                    <th>Student Name</th>
                                    <th>Adm NO</th>
                                    <th>Class</th>
                                    <th>Section</th>
                                    <th>Print</th>
                                    <th>Delete</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($transferList as $transferDetails): ?>
                                    <tr>
                                        <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>
                                            <a href="print_certificate.php?id=<?php echo urlencode($transferDetails["id"]); ?>" title="Print Certificate">
                                                <i class="fa fa-print"></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('Delete this 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>
                    </div>
                <?php } ?>
            </div>
        </div>
    </div>
</div>

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

            <div class="col-md-4 text-center mb-3">
              <img src="../<?php echo $student ? htmlspecialchars($student['passport']) : '../uploads/students/none.jpg'; ?>" alt="Passport" style="width:140px;height:140px;border-radius:50%;border:5px solid #ccc;" />
            </div>

            <div class="col-md-8">
              <div class="form-group">
                <label>Admission Number</label>
                <input type="text" class="form-control" name="reg_number" value="<?php echo $student['reg_number'] ?? ''; ?>" readonly>
              </div>
              <div class="form-group">
                <label>Full Name</label>
                <input type="text" class="form-control" name="studentName" value="<?php echo $student ? $student['firstname'].' '.$student['othername'].' '.$student['lastname'] : ''; ?>" readonly>
              </div>
              <div class="form-group">
                <label>Parent Name</label>
                <input type="text" class="form-control" name="studentParent" value="<?php echo $student['guardian_name'] ?? ''; ?>" readonly>
              </div>
              <div class="form-group">
                <label>State</label>
                <input type="text" class="form-control" name="studentState" value="<?php echo $student['state'] ?? ''; ?>" readonly>
              </div>
              <div class="form-group">
                <label>L.G.A</label>
                <input type="text" class="form-control" name="studentLGA" value="<?php echo $student['lga'] ?? ''; ?>" readonly>
              </div>
              <div class="form-group">
                <label>Date of Birth</label>
                <input type="text" class="form-control" name="studentDOB" value="<?php echo $student['dob'] ?? ''; ?>" readonly>
              </div>
              <div class="form-group">
                <label>Current Class</label>
                <input type="text" class="form-control" name="studentClass" value="<?php echo $student['class'] ?? ''; ?>" readonly>
              </div>
              <div class="form-group">
                <label>Section</label>
                <input type="text" class="form-control" name="section" value="<?php echo $student['level'] ?? ''; ?>" readonly>
              </div>
              <div class="form-group">
                <label>Last Class</label>
                <select class='form-control' name='last_class' required>
								<option selected disabled>Select Class</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)) {
										$attendance = $result['classes'];
										echo "<option value='{$attendance}'>{$attendance}</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="" required>
              </div>
              <div class="form-group">
                <label>Date of Last Attendance</label>
                <input type="text" class="form-control datepicker" name="date_of_last_att" placeholder="" required>
              </div>
              <div class="form-group">
                <label>Indebtedness</label>
                <input type="text" class="form-control" name="indebtedness" placeholder="" required>
              </div>
              <div class="form-group">
                <label>Conduct</label>
                <textarea class="form-control" name="conduct" placeholder="E.g., Excellent, Good..." required></textarea>
              </div>
              <div class="form-group">
                <label>Cause of Leaving</label>
                <textarea class="form-control" name="cause_of_leaving" required></textarea>
              </div>
              <input type="hidden" name="studentPassportSrc" value="<?php echo $student['passport'] ?? ''; ?>">
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="issue_transfer_btn" class="btn btn-primary btn-lg">Issue Transfer</button>
        </div>
      </form>
    </div>
  </div>
</div>

<?php if ($student): ?>
<script>
  document.addEventListener("DOMContentLoaded", function() {
    $('#issueTransferModal').modal('show');
  });
</script>
<?php endif; ?>

