<?php
session_start();
require_once 'inc/connect.php';

if (!isset($_SESSION['admin_id'])) {
    header('Location: admin_login.php');
    exit;
}

$feedback = '';

// Handle new student enrollment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['surname']) && !isset($_POST['update_serial'])) {
    $surname = trim($_POST['surname']);
    $middlename = trim($_POST['middlename']);
    $lastname = trim($_POST['lastname']);
    $gender = $_POST['gender'];
    $school_id = ($_POST['school_id']);
    $date_of_enrollment = $_POST['date_of_enrollment'];

    if ($surname && $lastname && $gender && $school_id && $date_of_enrollment) {
        $stmt = mysqli_prepare($mysqli, "INSERT INTO student_table (surname, middlename, lastname, school_id, gender, date_of_enrollment, generated_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
        mysqli_stmt_bind_param($stmt, 'sssssss', $surname, $middlename, $lastname, $school_id, $gender, $date_of_enrollment, $_SESSION['admin_id']);
        mysqli_stmt_execute($stmt);
        $feedback = "<div class='alert alert-success'>Student enrolled successfully.</div>";
    } else {
        $feedback = "<div class='alert alert-danger'>All required fields must be filled.</div>";
    }
}

// Handle student update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_serial'])) {
    $serial = intval($_POST['update_serial']);
    $surname = trim($_POST['surname']);
    $middlename = trim($_POST['middlename']);
    $lastname = trim($_POST['lastname']);
    $gender = $_POST['gender'];
    $school_id = ($_POST['school_id']);
    $date_of_enrollment = $_POST['date_of_enrollment'];
    $status = $_POST['status'];

    $stmt = mysqli_prepare($mysqli, "UPDATE student_table SET surname=?, middlename=?, lastname=?, gender=?, school_id=?, date_of_enrollment=?, status=? WHERE serial=?");
    mysqli_stmt_bind_param($stmt, 'ssssssi', $surname, $middlename, $lastname, $gender, $school_id, $date_of_enrollment, $status, $serial);
    mysqli_stmt_execute($stmt);
    $feedback = "<div class='alert alert-success'>Student updated successfully.</div>";
}

// Fetch students
$students = mysqli_query($mysqli, "SELECT * FROM student_table ORDER BY serial DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Manage Students</title>
  <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="/dist/css/adminlte.min.css">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
  <?php include 'inc/admin_nav.php'; ?>

  <div class="content-wrapper">
    <div class="content-header"><div class="container-fluid"><h1>Manage Students</h1></div></div>

    <section class="content">
      <div class="container-fluid">
        <?= $feedback ?>
        <button class="btn btn-primary mb-3" data-toggle="modal" data-target="#addStudentModal"><i class="fas fa-user-plus"></i> Enroll Student</button>

        <table id="studentTable" class="table table-bordered table-striped">
          <thead>
            <tr>
              <th>Full Name</th>
              <th>Gender</th>
              <th>School ID</th>
              <th>Enrolled</th>
              <th>Status</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <?php while ($row = mysqli_fetch_assoc($students)): ?>
              <tr>
                <td><?= htmlspecialchars("{$row['surname']} {$row['middlename']} {$row['lastname']}") ?></td>
                <td><?= ucfirst($row['gender']) ?></td>
                <td><?= htmlspecialchars($row['school_id']) ?></td>
                <td><?= htmlspecialchars($row['date_of_enrollment']) ?></td>
                <td><?= ucfirst($row['status']) ?></td>
                <td>
                  <button class="btn btn-sm btn-info" data-toggle="modal" data-target="#editModal<?= $row['serial'] ?>"><i class="fas fa-edit"></i> Edit</button>
                </td>
              </tr>

              <!-- Edit Modal -->
              <div class="modal fade" id="editModal<?= $row['serial'] ?>" tabindex="-1" role="dialog">
                <div class="modal-dialog" role="document">
                  <form method="POST" class="modal-content">
                    <input type="hidden" name="update_serial" value="<?= $row['serial'] ?>">
                    <div class="modal-header">
                      <h5 class="modal-title">Edit Student</h5>
                      <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
                    </div>
                    <div class="modal-body">
                      <div class="form-group">
                        <label>Surname *</label>
                        <input type="text" name="surname" class="form-control" value="<?= htmlspecialchars($row['surname']) ?>" required>
                      </div>
                      <div class="form-group">
                        <label>Middle Name</label>
                        <input type="text" name="middlename" class="form-control" value="<?= htmlspecialchars($row['middlename']) ?>">
                      </div>
                      <div class="form-group">
                        <label>Last Name *</label>
                        <input type="text" name="lastname" class="form-control" value="<?= htmlspecialchars($row['lastname']) ?>" required>
                      </div>
                      <div class="form-group">
                        <label>Gender *</label>
                        <select name="gender" class="form-control" required>
                          <option <?= $row['gender'] === 'male' ? 'selected' : '' ?> value="male">Male</option>
                          <option <?= $row['gender'] === 'female' ? 'selected' : '' ?> value="female">Female</option>
                          <option <?= $row['gender'] === 'other' ? 'selected' : '' ?> value="other">Other</option>
                        </select>
                      </div>
                      <div class="form-group">
                        <label>School ID *</label>
                        <input type="text" name="school_id" class="form-control" value="<?= $row['school_id'] ?>" required>
                      </div>
                      <div class="form-group">
                        <label>Date of Enrollment *</label>
                        <input type="date" name="date_of_enrollment" class="form-control" value="<?= $row['date_of_enrollment'] ?>" required>
                      </div>
                      <div class="form-group">
                        <label>Status</label>
                        <select name="status" class="form-control">
                          <option value="active" <?= $row['status'] === 'active' ? 'selected' : '' ?>>Active</option>
                          <option value="inactive" <?= $row['status'] === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                          <option value="suspended" <?= $row['status'] === 'suspended' ? 'selected' : '' ?>>Suspended</option>
                        </select>
                      </div>
                    </div>
                    <div class="modal-footer">
                      <button type="submit" class="btn btn-primary">Save</button>
                      <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                  </form>
                </div>
              </div>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    </section>
  </div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addStudentModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <form method="POST" class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Enroll New Student</h5>
        <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body">
        <div class="form-group"><label>Surname *</label><input type="text" name="surname" class="form-control" required></div>
        <div class="form-group"><label>Middle Name</label><input type="text" name="middlename" class="form-control"></div>
        <div class="form-group"><label>Last Name *</label><input type="text" name="lastname" class="form-control" required></div>
        <div class="form-group">
          <label>Gender *</label>
          <select name="gender" class="form-control" required>
            <option value="">Select gender</option>
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="other">Other</option>
          </select>
        </div>
        <div class="form-group"><label>School ID *</label><input type="text" name="school_id" class="form-control" required></div>
        <div class="form-group"><label>Date of Enrollment *</label><input type="date" name="date_of_enrollment" class="form-control" required></div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-success">Enroll</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
      </div>
    </form>
  </div>
</div>

<script src="/plugins/jquery/jquery.min.js"></script>
<script src="/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="/dist/js/adminlte.min.js"></script>
<script>
  $(function () {
    $('#studentTable').DataTable();
  });
</script>
</body>
</html>
