<link rel="icon" href="logo.jpg" type="image/jpg">
<?php
// File: boarders.php
require_once "db.php";
check_login();

$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$id      = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$view    = isset($_GET['view']) && $_GET['view'] === 'archived' ? 'archived' : 'active';

// --- Sorting parameters ---
$allowed_sorts = ['name', 'gender', 'birthday', 'civil_status', 'purok', 'voter'];
$sort = isset($_GET['sort']) && in_array($_GET['sort'], $allowed_sorts) ? $_GET['sort'] : 'name';
$dir  = isset($_GET['dir'])  && strtolower($_GET['dir']) === 'desc' ? 'desc' : 'asc';

// --- Search parameter (used for Active view) ---
$search = isset($_GET['search']) ? trim($_GET['search']) : '';

// helper for displaying sort arrow in header
function sort_icon($column, $currentSort, $currentDir) {
    if ($column !== $currentSort) {
        return '';
    }
    return $currentDir === 'asc' ? ' ▲' : ' ▼';
}

$message = '';
$message_type = 'success';

// Handle Add/Edit form submission
if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_POST['save_boarder'])) {
    $boarder_id   = (int)($_POST['id'] ?? 0);
    $first_name   = trim($_POST['first_name'] ?? '');
    $middle_name  = trim($_POST['middle_name'] ?? '');
    $last_name    = trim($_POST['last_name'] ?? '');
    $suffix       = trim($_POST['suffix'] ?? '');
    $gender       = trim($_POST['gender'] ?? '');
    $birthday     = trim($_POST['birthday'] ?? '');
    $civil_status = trim($_POST['civil_status'] ?? '');
    $purok        = trim($_POST['purok'] ?? '');
    $is_voter     = isset($_POST['is_voter']) ? 1 : 0;

    if ($boarder_id > 0) {
        // Update
        $sql = "UPDATE boarders 
                SET first_name = ?, middle_name = ?, last_name = ?, suffix = ?, 
                    gender = ?, birthday = ?, civil_status = ?, purok = ?, is_voter = ? 
                WHERE id = ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param(
            "ssssssssii",
            $first_name,
            $middle_name,
            $last_name,
            $suffix,
            $gender,
            $birthday,
            $civil_status,
            $purok,
            $is_voter,
            $boarder_id
        );
        if ($stmt->execute()) {
            $_SESSION['message'] = "Boarder record updated successfully!";
        } else {
            $_SESSION['message']      = "Error updating record: " . $stmt->error;
            $_SESSION['message_type'] = 'danger';
        }
    } else {
        // Insert
        $sql = "INSERT INTO boarders 
                (first_name, middle_name, last_name, suffix, gender, birthday, civil_status, purok, is_voter) 
                VALUES (?,?,?,?,?,?,?,?,?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param(
            "ssssssssi",
            $first_name,
            $middle_name,
            $last_name,
            $suffix,
            $gender,
            $birthday,
            $civil_status,
            $purok,
            $is_voter
        );
        if ($stmt->execute()) {
            $_SESSION['message'] = "Boarder added successfully!";
        } else {
            $_SESSION['message']      = "Error adding record: " . $stmt->error;
            $_SESSION['message_type'] = 'danger';
        }
    }

    if (isset($stmt)) {
        $stmt->close();
    }

    header("Location: boarders.php");
    exit;
}

// Handle Archive/Restore actions
if ($action === 'archive' && $id > 0) {
    $sql  = "UPDATE boarders SET is_archived = 1, date_archived = NOW() WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        $_SESSION['message'] = "Boarder record archived successfully.";
    } else {
        $_SESSION['message']      = "Error archiving record: " . $stmt->error;
        $_SESSION['message_type'] = 'danger';
    }
    $stmt->close();
    header("Location: boarders.php");
    exit;
}

if ($action === 'restore' && $id > 0) {
    $sql  = "UPDATE boarders SET is_archived = 0, date_archived = NULL WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        $_SESSION['message'] = "Boarder record restored successfully.";
    } else {
        $_SESSION['message']      = "Error restoring record: " . $stmt->error;
        $_SESSION['message_type'] = 'danger';
    }
    $stmt->close();
    header("Location: boarders.php?view=archived");
    exit;
}

// Permanent delete (use with care)
if ($action === 'delete' && $id > 0) {
    $sql  = "DELETE FROM boarders WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    if ($stmt->execute()) {
        $_SESSION['message'] = "Boarder record deleted permanently.";
    } else {
        $_SESSION['message']      = "Error deleting record: " . $stmt->error;
        $_SESSION['message_type'] = 'danger';
    }
    $stmt->close();
    header("Location: boarders.php?view=" . $view);
    exit;
}

// Fetch data for editing (if any)
$boarder_to_edit = [
    'id'           => 0,
    'first_name'   => '',
    'middle_name'  => '',
    'last_name'    => '',
    'suffix'       => '',
    'gender'       => '',
    'birthday'     => '',
    'civil_status' => '',
    'purok'        => '',
    'is_voter'     => 0,
];

if ($action === 'edit' && $id > 0) {
    $sql  = "SELECT * FROM boarders WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result && $result->num_rows === 1) {
        $boarder_to_edit = $result->fetch_assoc();
    }
    $stmt->close();
}

// --- Build ORDER BY clause based on sort ---
switch ($sort) {
    case 'gender':
        $order_by = "gender";
        break;
    case 'birthday':
        $order_by = "birthday";
        break;
    case 'civil_status':
        $order_by = "civil_status";
        break;
    case 'purok':
        $order_by = "purok";
        break;
    case 'voter':
        $order_by = "is_voter";
        break;
    case 'name':
    default:
        $order_by = "last_name, first_name";
        break;
}

$sql_dir = ($dir === 'desc') ? 'DESC' : 'ASC';
$filter_archived = $view === 'archived' ? 1 : 0;

/*
 * EXPORT HANDLING (Excel / PDF)
 * NOTE: logic unchanged – only layout below is redesigned
 */
if ($action === 'export_excel' || $action === 'export_pdf') {
    if ($search !== '' && $view === 'active') {
        $sql_export = "SELECT * FROM boarders 
                       WHERE is_archived = ? AND (
                           first_name LIKE ? OR
                           middle_name LIKE ? OR
                           last_name LIKE ? OR
                           suffix LIKE ? OR
                           gender LIKE ? OR
                           civil_status LIKE ? OR
                           purok LIKE ?
                       )
                       ORDER BY $order_by $sql_dir";
        $stmt_export = $conn->prepare($sql_export);
        $like = '%' . $search . '%';
        $stmt_export->bind_param(
            "isssssss",
            $filter_archived,
            $like, $like, $like, $like, $like, $like, $like
        );
    } else {
        $sql_export = "SELECT * FROM boarders WHERE is_archived = ? ORDER BY $order_by $sql_dir";
        $stmt_export = $conn->prepare($sql_export);
        $stmt_export->bind_param("i", $filter_archived);
    }

    $stmt_export->execute();
    $result_export = $stmt_export->get_result();
    $title_suffix = $view === 'archived' ? 'Archived Boarders' : 'Active Boarders';

    if ($action === 'export_excel') {
        header("Content-Type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=\"boarders_".$view."_".date('Ymd_His').".xls\"");
        header("Pragma: no-cache");
        header("Expires: 0");

        echo "<table border='1'>";
        echo "<tr><th colspan='7'>Boarders Report - ".$title_suffix."</th></tr>";
        echo "<tr>";
        echo "<th>#</th>";
        echo "<th>Full Name</th>";
        echo "<th>Gender</th>";
        echo "<th>Birthday</th>";
        echo "<th>Civil Status</th>";
        echo "<th>Purok</th>";
        echo "<th>Voter</th>";
        echo "</tr>";

        $i = 1;
        while ($row = $result_export->fetch_assoc()) {
            $fullname = $row['last_name'] . ', ' . $row['first_name'] .
                        (!empty($row['middle_name']) ? ' ' . $row['middle_name'] : '') .
                        (!empty($row['suffix']) ? ' ' . $row['suffix'] : '');

            echo "<tr>";
            echo "<td>".$i++."</td>";
            echo "<td>".htmlspecialchars($fullname)."</td>";
            echo "<td>".htmlspecialchars($row['gender'])."</td>";
            echo "<td>".htmlspecialchars($row['birthday'])."</td>";
            echo "<td>".htmlspecialchars($row['civil_status'])."</td>";
            echo "<td>".htmlspecialchars($row['purok'])."</td>";
            echo "<td>".($row['is_voter'] ? 'Yes' : 'No')."</td>";
            echo "</tr>";
        }

        echo "</table>";

        $stmt_export->close();
        exit;
    }

    if ($action === 'export_pdf') {
        require_once "fpdf/fpdf.php";

        $pdf = new FPDF('L', 'mm', 'A4');
        $pdf->AddPage();
        $pdf->SetFont('Arial', 'B', 14);
        $pdf->Cell(0, 10, 'Boarders Report - ' . $title_suffix, 0, 1, 'C');
        $pdf->Ln(3);

        // Header
        $pdf->SetFont('Arial', 'B', 10);
        $pdf->Cell(10, 8, '#', 1, 0, 'C');
        $pdf->Cell(80, 8, 'Full Name', 1, 0, 'C');
        $pdf->Cell(25, 8, 'Gender', 1, 0, 'C');
        $pdf->Cell(30, 8, 'Birthday', 1, 0, 'C');
        $pdf->Cell(30, 8, 'Civil Status', 1, 0, 'C');
        $pdf->Cell(30, 8, 'Purok', 1, 0, 'C');
        $pdf->Cell(20, 8, 'Voter', 1, 1, 'C');

        $pdf->SetFont('Arial', '', 9);
        $i = 1;
        while ($row = $result_export->fetch_assoc()) {
            $fullname = $row['last_name'] . ', ' . $row['first_name'] .
                        (!empty($row['middle_name']) ? ' ' . $row['middle_name'] : '') .
                        (!empty($row['suffix']) ? ' ' . $row['suffix'] : '');

            $pdf->Cell(10, 7, $i++, 1, 0, 'C');
            $pdf->Cell(80, 7, utf8_decode($fullname), 1, 0, 'L');
            $pdf->Cell(25, 7, utf8_decode($row['gender']), 1, 0, 'C');
            $pdf->Cell(30, 7, utf8_decode($row['birthday']), 1, 0, 'C');
            $pdf->Cell(30, 7, utf8_decode($row['civil_status']), 1, 0, 'C');
            $pdf->Cell(30, 7, utf8_decode($row['purok']), 1, 0, 'C');
            $pdf->Cell(20, 7, $row['is_voter'] ? 'Yes' : 'No', 1, 1, 'C');
        }

        $stmt_export->close();
        $pdf->Output('D', 'boarders_'.$view.'_'.date('Ymd_His').'.pdf');
        exit;
    }
}

// Fetch list for page display (with optional search for active)
if ($search !== '' && $view === 'active') {
    $sql_list = "SELECT * FROM boarders 
                 WHERE is_archived = ? AND (
                     first_name LIKE ? OR
                     middle_name LIKE ? OR
                     last_name LIKE ? OR
                     suffix LIKE ? OR
                     gender LIKE ? OR
                     civil_status LIKE ? OR
                     purok LIKE ?
                 )
                 ORDER BY $order_by $sql_dir";
    $stmt_list = $conn->prepare($sql_list);
    $like = '%' . $search . '%';
    $stmt_list->bind_param("isssssss",
        $filter_archived,
        $like, $like, $like, $like, $like, $like, $like
    );
} else {
    $sql_list = "SELECT * FROM boarders WHERE is_archived = ? ORDER BY $order_by $sql_dir";
    $stmt_list = $conn->prepare($sql_list);
    $stmt_list->bind_param("i", $filter_archived);
}

$stmt_list->execute();
$boarders_result = $stmt_list->get_result();

if (isset($_SESSION['message'])) {
    $message      = $_SESSION['message'];
    $message_type = $_SESSION['message_type'] ?? 'success';
    unset($_SESSION['message'], $_SESSION['message_type']);
}

$page_title = "Boarder Management";
include 'header.php';
?>

<!-- Redesigned layout styles (visual only, no functional change) -->
<style>
    .boarder-layout {
        padding-bottom: 30px;
    }
    .boarder-header-bar {
        display: flex;
        justify-content: space-between;
        align-items: flex-end;
        gap: 10px;
        margin-bottom: 10px;
    }
    .boarder-subtitle {
        margin: 0;
        color: #6c757d;
        font-size: 0.95rem;
    }
    .boarder-view-toggle .btn {
        min-width: 140px;
    }
    .boarder-card {
        background: #ffffff;
        border-radius: 8px;
        padding: 20px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.08);
        margin-bottom: 20px;
    }
    .boarder-card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
    }
    .boarder-card-header h2 {
        margin: 0;
        font-size: 1.25rem;
    }
    .boarder-toolbar {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
        justify-content: flex-end;
        align-items: center;
    }
    .boarder-toolbar .form-control {
        min-width: 220px;
    }
    /* Registered voter checkbox styling */
    .voter-check {
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }
    .voter-check input[type="checkbox"] {
        width: 18px;
        height: 18px;
        cursor: pointer;
    }
    .voter-check label {
        margin: 0;
        font-weight: 600;
    }
    @media (max-width: 768px) {
        .boarder-header-bar {
            flex-direction: column;
            align-items: flex-start;
        }
        .boarder-card-header {
            flex-direction: column;
            align-items: flex-start;
            gap: 10px;
        }
        .boarder-toolbar {
            width: 100%;
            justify-content: flex-start;
        }
    }
</style>

<div class="container boarder-layout">
    <!-- Top header & view toggle -->
    <div class="boarder-header-bar">
        <div>
            <h1 style="margin-bottom:4px;">Boarder Registration &amp; Management</h1>
            <p class="boarder-subtitle">
                Boarders are stored in a separate table and are not counted toward the total population.
            </p>
        </div>
        <div class="boarder-view-toggle">
            <a href="boarders.php"
               class="btn <?php echo $view === 'active' ? 'btn-primary' : 'btn-light'; ?>">
                Active Boarders
            </a>
            <a href="boarders.php?view=archived"
               class="btn <?php echo $view === 'archived' ? 'btn-primary' : 'btn-light'; ?>">
                Archived Boarders
            </a>
        </div>
    </div>

    <?php if (!empty($message)): ?>
        <div class="alert alert-<?php echo htmlspecialchars($message_type); ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <!-- FORM CARD (only for active view) -->
    <?php if ($view === 'active'): ?>
        <div class="boarder-card">
            <div class="boarder-card-header">
                <h2><?php echo $boarder_to_edit['id'] ? 'Edit Boarder' : 'Add New Boarder'; ?></h2>
                <?php if ($boarder_to_edit['id']): ?>
                    <span style="font-size:0.9rem;color:#6c757d;">
                        Updating record for: 
                        <strong>
                            <?php echo htmlspecialchars($boarder_to_edit['last_name'].', '.$boarder_to_edit['first_name']); ?>
                        </strong>
                    </span>
                <?php endif; ?>
            </div>

            <form method="post" action="boarders.php" class="user-form">
                <input type="hidden" name="id" value="<?php echo (int)$boarder_to_edit['id']; ?>">

                <div class="form-row">
                    <div class="form-group">
                        <label for="first_name">First Name</label>
                        <input
                            type="text"
                            id="first_name"
                            name="first_name"
                            class="form-control"
                            value="<?php echo htmlspecialchars($boarder_to_edit['first_name']); ?>"
                            required
                        >
                    </div>
                    <div class="form-group">
                        <label for="middle_name">Middle Name</label>
                        <input
                            type="text"
                            id="middle_name"
                            name="middle_name"
                            class="form-control"
                            value="<?php echo htmlspecialchars($boarder_to_edit['middle_name']); ?>"
                        >
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="last_name">Last Name</label>
                        <input
                            type="text"
                            id="last_name"
                            name="last_name"
                            class="form-control"
                            value="<?php echo htmlspecialchars($boarder_to_edit['last_name']); ?>"
                            required
                        >
                    </div>
                    <div class="form-group">
    <label for="suffix">Suffix</label>
    <select id="suffix" name="suffix" class="form-control">
        <option value="">-- Select Suffix --</option>
        <?php 
            $suffixes = ["Jr.", "Sr.", "III", "IV", "V"];
            foreach ($suffixes as $s) {
                $selected = ($boarder_to_edit['suffix'] === $s) ? 'selected' : '';
                echo "<option value=\"$s\" $selected>$s</option>";
            }
        ?>
    </select>
</div>

                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="gender">Gender</label>
                        <select id="gender" name="gender" class="form-control" required>
                            <option value="">-- Select Gender --</option>
                            <option value="Male"   <?php if($boarder_to_edit['gender'] === 'Male')   echo 'selected'; ?>>Male</option>
                            <option value="Female" <?php if($boarder_to_edit['gender'] === 'Female') echo 'selected'; ?>>Female</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="birthday">Birthday</label>
                        <input
                            type="date"
                            id="birthday"
                            name="birthday"
                            class="form-control"
                            value="<?php echo htmlspecialchars($boarder_to_edit['birthday']); ?>"
                            required
                        >
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label for="civil_status">Civil Status</label>
                        <select id="civil_status" name="civil_status" class="form-control" required>
                            <?php $cs = $boarder_to_edit['civil_status']; ?>
                            <option value="">-- Select Civil Status --</option>
                            <option value="Single"    <?php if($cs === 'Single')    echo 'selected'; ?>>Single</option>
                            <option value="Married"   <?php if($cs === 'Married')   echo 'selected'; ?>>Married</option>
                            <option value="Widowed"   <?php if($cs === 'Widowed')   echo 'selected'; ?>>Widowed</option>
                            <option value="Separated" <?php if($cs === 'Separated') echo 'selected'; ?>>Separated</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label for="purok">Purok</label>
                        <select id="purok" name="purok" class="form-control" required>
                            <option value="">-- Select Purok --</option>
                            <?php 
                                $purok_options = [
                                    "Purok 1", "Purok 2", "Purok 3",
                                    "Purok 4", "Purok 5", "Purok 6", "Purok 7"
                                ];
                                foreach ($purok_options as $p) {
                                    $selected = ($boarder_to_edit['purok'] === $p) ? 'selected' : '';
                                    echo "<option value=\"$p\" $selected>$p</option>";
                                }
                            ?>
                        </select>
                    </div>
                </div>

                <!-- Fixed Registered Voter block -->
                <div class="form-group" style="margin-top:15px;">
                    <div class="voter-check">
                        <input
                            type="checkbox"
                            id="is_voter"
                            name="is_voter"
                            value="1"
                            <?php if(!empty($boarder_to_edit['is_voter'])) echo 'checked'; ?>
                        >
                        <label for="is_voter">Registered Voter</label>
                    </div>
                </div>

                <div class="form-group" style="margin-top:10px;">
                    <button type="submit" name="save_boarder" class="btn btn-primary">
                        <?php echo $boarder_to_edit['id'] ? 'Update Boarder' : 'Save Boarder'; ?>
                    </button>
                </div>
            </form>
        </div>
    <?php endif; ?>

    <!-- LIST CARD -->
    <div class="boarder-card">
        <div class="boarder-card-header">
            <h2 style="margin-bottom:0;">
                <?php echo $view === 'archived' ? 'Archived Boarders' : 'Active Boarders'; ?>
            </h2>

            <div class="boarder-toolbar">
                <!-- Export buttons for both views -->
                <div class="btn-group" role="group" aria-label="Export">
                    <a href="boarders.php?view=<?php echo $view; ?>&sort=<?php echo urlencode($sort); ?>&dir=<?php echo urlencode($dir); ?>&search=<?php echo urlencode($search); ?>&action=export_excel"
                       class="btn btn-secondary btn-sm">Excel</a>
                    <a href="boarders.php?view=<?php echo $view; ?>&sort=<?php echo urlencode($sort); ?>&dir=<?php echo urlencode($dir); ?>&search=<?php echo urlencode($search); ?>&action=export_pdf"
                       class="btn btn-secondary btn-sm">PDF</a>
                </div>

                <!-- Search only for active view -->
                <?php if ($view === 'active'): ?>
                    <form method="get" action="boarders.php" style="display:flex;gap:8px;align-items:center;">
                        <input type="hidden" name="view" value="active">
                        <input type="hidden" name="sort" value="<?php echo htmlspecialchars($sort); ?>">
                        <input type="hidden" name="dir" value="<?php echo htmlspecialchars($dir); ?>">

                        <input
                            type="text"
                            name="search"
                            class="form-control"
                            placeholder="Search name, gender, status, purok..."
                            value="<?php echo htmlspecialchars($search); ?>"
                        >
                        <button type="submit" class="btn btn-secondary btn-sm">Search</button>
                        <?php if ($search !== ''): ?>
                            <a href="boarders.php?view=active" class="btn btn-light btn-sm">Clear</a>
                        <?php endif; ?>
                    </form>
                <?php endif; ?>
            </div>
        </div>

        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th>#</th>
                        <th>
                            <a href="boarders.php?view=<?php echo $view; ?>&search=<?php echo urlencode($search); ?>&sort=name&dir=<?php echo ($sort === 'name' && $dir === 'asc') ? 'desc' : 'asc'; ?>">
                                Full Name<?php echo sort_icon('name', $sort, $dir); ?>
                            </a>
                        </th>
                        <th>
                            <a href="boarders.php?view=<?php echo $view; ?>&search=<?php echo urlencode($search); ?>&sort=gender&dir=<?php echo ($sort === 'gender' && $dir === 'asc') ? 'desc' : 'asc'; ?>">
                                Gender<?php echo sort_icon('gender', $sort, $dir); ?>
                            </a>
                        </th>
                        <th>
                            <a href="boarders.php?view=<?php echo $view; ?>&search=<?php echo urlencode($search); ?>&sort=birthday&dir=<?php echo ($sort === 'birthday' && $dir === 'asc') ? 'desc' : 'asc'; ?>">
                                Birthday<?php echo sort_icon('birthday', $sort, $dir); ?>
                            </a>
                        </th>
                        <th>
                            <a href="boarders.php?view=<?php echo $view; ?>&search=<?php echo urlencode($search); ?>&sort=civil_status&dir=<?php echo ($sort === 'civil_status' && $dir === 'asc') ? 'desc' : 'asc'; ?>">
                                Civil Status<?php echo sort_icon('civil_status', $sort, $dir); ?>
                            </a>
                        </th>
                        <th>
                            <a href="boarders.php?view=<?php echo $view; ?>&search=<?php echo urlencode($search); ?>&sort=purok&dir=<?php echo ($sort === 'purok' && $dir === 'asc') ? 'desc' : 'asc'; ?>">
                                Purok<?php echo sort_icon('purok', $sort, $dir); ?>
                            </a>
                        </th>
                        <th>
                            <a href="boarders.php?view=<?php echo $view; ?>&search=<?php echo urlencode($search); ?>&sort=voter&dir=<?php echo ($sort === 'voter' && $dir === 'asc') ? 'desc' : 'asc'; ?>">
                                Voter<?php echo sort_icon('voter', $sort, $dir); ?>
                            </a>
                        </th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php if ($boarders_result->num_rows > 0): ?>
                    <?php $i = 1; while ($row = $boarders_result->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo $i++; ?></td>
                            <td>
                                <?php
                                    echo htmlspecialchars(
                                        $row['last_name'] . ', ' . $row['first_name'] .
                                        (!empty($row['middle_name']) ? ' ' . $row['middle_name'] : '') .
                                        (!empty($row['suffix']) ? ' ' . $row['suffix'] : '')
                                    );
                                ?>
                            </td>
                            <td><?php echo htmlspecialchars($row['gender']); ?></td>
                            <td><?php echo htmlspecialchars($row['birthday']); ?></td>
                            <td><?php echo htmlspecialchars($row['civil_status']); ?></td>
                            <td><?php echo htmlspecialchars($row['purok']); ?></td>
                            <td><?php echo $row['is_voter'] ? 'Yes' : 'No'; ?></td>
                            <td>
                                <?php if ($view === 'active'): ?>
                                    <a href="boarders.php?action=edit&id=<?php echo $row['id']; ?>" class="btn btn-small">Edit</a>

                                    <a href="boarders.php?action=archive&id=<?php echo $row['id']; ?>"
                                       class="btn btn-danger btn-small"
                                       onclick="return confirm('Archive this boarder record?');">
                                       Archive
                                    </a>
                                <?php else: ?>
                                    <a href="boarders.php?action=restore&id=<?php echo $row['id']; ?>"
                                       class="btn btn-small"
                                       onclick="return confirm('Restore this boarder record?');">
                                       Restore
                                    </a>

                                    <a href="boarders.php?action=delete&id=<?php echo $row['id']; ?>"
                                       class="btn btn-danger btn-small"
                                       onclick="return confirm('Permanently delete this boarder record? This cannot be undone.');">
                                       Delete
                                    </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="8" style="text-align:center;">No records found.</td>
                    </tr>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php
$stmt_list->close();
include 'footer.php';
?>
