<?php
session_start();
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit;
}

$conn = new mysqli("localhost", "root", "", "school_checkin");
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// --- CLEAR STUDENTS FUNCTIONALITY ---
if (isset($_POST['clear_students'])) {
    $conn->query("TRUNCATE TABLE students"); // Mas safe ug paspas ang TRUNCATE kaysa DELETE
    $msg = "All students cleared!";
}

// Handle delete (using LRN key)
if (isset($_GET['delete'])) {
    $lrn = $conn->real_escape_string($_GET['delete']);
    $conn->query("DELETE FROM students WHERE lrn = '$lrn'");
    header("Location: students.php");
    exit;
}

// Fetch students
$students = [];

// --- FINAL NGA SOLUSYON ---
// I-specify ang tanan column names para sigurado nga sakto ang data nga makuha
$sql = "SELECT 
            lrn, last_name, first_name, middle_name, sex, birthday, 
            contact, grade, address, mother, father, municipality, 
            religion, mothertongue, relationship 
        FROM students 
        ORDER BY grade ASC, last_name ASC, first_name ASC";

$result = $conn->query($sql);

// I-check kung naay error ang SQL query
if (!$result) {
    // Kung naay error, ipakita kung unsa ang sayop.
    die("SQL Query Error: " . $conn->error);
}

while($row = $result->fetch_assoc()) {
    $students[] = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Student List - SDAESI</title>
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
    <style>
        body {
            background: #121212;
            color: #fff;
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        .main-box {
            background: #1e1e1e;
            margin: 32px auto 0 auto;
            padding: 25px 20px 32px 20px;
            border-radius: 18px;
            max-width: 1150px;
            width: 98vw;
        }
        h2 { margin-top: 0; }
        .btn-back {
            background: #6c757d;
            color: #fff;
            padding: 8px 20px;
            border: none;
            border-radius: 6px;
            text-decoration: none;
            font-size: 1em;
            margin-bottom: 10px;
            display: inline-block;
        }
        .btn-back:hover { background: #444; }
        .btn-clear {
            background: #e74c3c;
            color: #fff;
            padding: 8px 20px;
            border: none;
            border-radius: 6px;
            margin-left: 8px;
            font-size: 1em;
            cursor: pointer;
            margin-bottom: 10px;
        }
        .btn-add {
            background:rgb(10, 255, 112);
            color: #fff;
            padding: 8px 20px;
            border: none;
            border-radius: 6px;
            margin-left: 8px;
            font-size: 1em;
            cursor: pointer;
            margin-bottom: 10px;
        }
        .btn-add a {
            text-decoration: none;
            color: #fff;
        }
        .btn-clear:hover { background: #b92d1c; }
        table {
            border-collapse: collapse;
            width: 100%;
            background: #232323;
            margin-top: 12px;
        }
        th, td {
            border: 1px solid #444;
            padding: 8px 5px;
            text-align: center;
            font-size: 0.96em;
        }
        th {
            background: #007bff;
            color: #fff;
        }
        .student-name {
            text-align: left;
        }
        .btn-delete {
            background: #e74c3c;
            color: #fff;
            border: none;
            border-radius: 5px;
            padding: 5px 12px;
            cursor: pointer;
            font-size: 1em;
        }
        .btn-delete:hover { background: #b92d1c; }
        .msg-success {
            color: #00e676;
            font-weight: bold;
            margin-bottom: 10px;
        }
        @media (max-width:900px){
            .main-box { padding: 5px; }
            table, th, td { font-size: 0.88em; }
        }
        @media (max-width:600px){
            table, th, td { font-size: 0.73em; }
        }
    </style>
</head>
<body>
<div class="main-box">
    <h2>👨‍🎓 Student List</h2>
    <a href="dashboard.php" class="btn-back">← Back to Dashboard</a>
    <button class="btn-add"><a href='generate_qr.php'>Add Student</a></button>
    <form method="post" style="display:inline-block;">
        <button type="submit" name="clear_students" class="btn-clear" onclick="return confirm('Are you sure you want to CLEAR ALL STUDENTS?')">🧹 Clear Students</button>
    </form>
    <?php if (!empty($msg)): ?>
        <div class="msg-success"><?= htmlspecialchars($msg) ?></div>
    <?php endif; ?>
    <div style="overflow: scroll;">
        <table id="studentTable" class="display" style="width: 100%">
        <thead>
        <tr>
            <th>LRN</th>
            <th>Name</th>
            <th>Sex</th>
            <th>Birthday</th>
            <th>Contact</th>
            <th>Grade</th>
            <th>Address</th>
            <th>Mother</th>
            <th>Father</th>
            <th>Municipality</th>
            <th>Religion</th>
            <th>Mother Tongue</th>
            <th>Relationship</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody>
        <?php if($students): ?>
            <?php foreach($students as $stud): ?>
                <?php
                    $lname = !empty($stud['last_name']) ? strtoupper(trim($stud['last_name'])) : '';
                    $fname = !empty($stud['first_name']) ? strtoupper(trim($stud['first_name'])) : '';
                    $mname = !empty($stud['middle_name']) ? strtoupper(trim($stud['middle_name'])) : '';
                    $full = ($lname || $fname) ? trim("$lname, $fname $mname") : '';
                ?>
                <tr>
                    <td><?= htmlspecialchars($stud['lrn']) ?></td>
                    <td class="student-name"><?= htmlspecialchars($full) ?></td>
                    <td><?= htmlspecialchars($stud['sex']) ?></td>
                    <td><?= htmlspecialchars($stud['birthday']) ?></td>
                    <td><?= htmlspecialchars($stud['contact']) ?></td>
                    <td><?= htmlspecialchars($stud['grade']) ?></td>
                    <td><?= htmlspecialchars($stud['address']) ?></td>
                    <td><?= htmlspecialchars($stud['mother']) ?></td>
                    <td><?= htmlspecialchars($stud['father']) ?></td>
                    <td><?= htmlspecialchars($stud['municipality']) ?></td>
                    <td><?= htmlspecialchars($stud['religion']) ?></td>
                    <td><?= htmlspecialchars($stud['mothertongue']) ?></td>
                    <td><?= htmlspecialchars($stud['relationship']) ?></td>
                    <td>
                        <a href="?delete=<?= urlencode($stud['lrn']) ?>"
                           onclick="return confirm('Are you sure you want to delete this student: <?= htmlspecialchars($full) ?>?')">
                            <button class="btn-delete" type="button">Delete</button>
                        </a>
                    </td>
                </tr>
            <?php endforeach; ?>
        <?php else: ?>
            <tr><td colspan="14">No students found.</td></tr>
        <?php endif; ?>
        </tbody>
        </table>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
<script>
  $(document).ready(function () {
    $('#studentTable').DataTable();
  });
</script>
</body>
</html>