<?php
// school_admission/public/branch_view_applicants.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth_check.php';

requireRole(['branch_admin']); // Only Branch Admin can access this page

$message = '';
if (isset($_SESSION['message'])) {
    $message = $_SESSION['message'];
    unset($_SESSION['message']);
}

$current_branch_id = $_SESSION['branch_id'];

// --- Search and Filter Logic ---
$search_term = isset($_GET['search_term']) ? sanitize_input($_GET['search_term']) : '';
$filter_by = isset($_GET['filter_by']) ? sanitize_input($_GET['filter_by']) : 'name'; // Default filter by name
$status_filter = isset($_GET['status_filter']) ? sanitize_input($_GET['status_filter']) : 'all'; // Default filter by all statuses

$applicants = [];
$sql = "SELECT
            a.applicant_id,
            a.first_name,
            a.last_name,
            a.application_no,
            a.application_date,
            a.status,
            c.course_name
        FROM
            applicants a
        JOIN
            courses c ON a.course_id = c.course_id
        WHERE
            a.branch_id = ?";

$params = [$current_branch_id];
$types = "i";

// Add search conditions
if (!empty($search_term)) {
    $sql .= " AND (";
    if ($filter_by === 'app_no') {
        $sql .= "a.application_no LIKE ?";
        $params[] = '%' . $search_term . '%';
        $types .= "s";
    } elseif ($filter_by === 'name') {
        $sql .= "a.first_name LIKE ? OR a.last_name LIKE ? OR a.other_names LIKE ?";
        $params[] = '%' . $search_term . '%';
        $params[] = '%' . $search_term . '%';
        $params[] = '%' . $search_term . '%';
        $types .= "sss";
    } elseif ($filter_by === 'course') {
        $sql .= "c.course_name LIKE ?";
        $params[] = '%' . $search_term . '%';
        $types .= "s";
    }
    $sql .= ")";
}

// Add status filter
if ($status_filter !== 'all') {
    $sql .= " AND a.status = ?";
    $params[] = $status_filter;
    $types .= "s";
}

$sql .= " ORDER BY a.created_at DESC";

$stmt = $conn->prepare($sql);
if ($stmt) {
    // Dynamically bind parameters
    call_user_func_array([$stmt, 'bind_param'], array_merge([$types], $params));
    $stmt->execute();
    $result = $stmt->get_result();
    while ($row = $result->fetch_assoc()) {
        $applicants[] = $row;
    }
    $stmt->close();
} else {
    $message = "<div class='message error'>Error fetching applicants: " . $conn->error . "</div>";
}

include __DIR__ . '/../includes/header.php';
?>

<h2 class="mt-30">My Branch Applicants</h2>

<?php if (!empty($message)): ?>
    <?php echo $message; ?>
<?php endif; ?>

<div class="mb-20">
    <a href="branch_add_applicant.php" class="btn btn-success"><i class="fas fa-user-plus"></i> Add New Applicant</a>
</div>

<!-- Search and Filter Form -->
<form action="branch_view_applicants.php" method="GET" class="form-inline mb-30">
    <div class="form-group">
        <label for="search_term" class="sr-only">Search:</label>
        <input type="text" id="search_term" name="search_term" placeholder="Search..." value="<?php echo htmlspecialchars($search_term); ?>">
    </div>
    <div class="form-group">
        <label for="filter_by" class="sr-only">Filter By:</label>
        <select id="filter_by" name="filter_by">
            <option value="name" <?php echo ($filter_by === 'name') ? 'selected' : ''; ?>>Name</option>
            <option value="app_no" <?php echo ($filter_by === 'app_no') ? 'selected' : ''; ?>>Application No.</option>
            <option value="course" <?php echo ($filter_by === 'course') ? 'selected' : ''; ?>>Course</option>
        </select>
    </div>
    <div class="form-group">
        <label for="status_filter" class="sr-only">Status:</label>
        <select id="status_filter" name="status_filter">
            <option value="all" <?php echo ($status_filter === 'all') ? 'selected' : ''; ?>>All Statuses</option>
            <option value="pending_review" <?php echo ($status_filter === 'pending_review') ? 'selected' : ''; ?>>Pending Review</option>
            <option value="approved" <?php echo ($status_filter === 'approved') ? 'selected' : ''; ?>>Approved</option>
            <option value="rejected" <?php echo ($status_filter === 'rejected') ? 'selected' : ''; ?>>Rejected</option>
            <option value="admission_letter_generated" <?php echo ($status_filter === 'admission_letter_generated') ? 'selected' : ''; ?>>Letter Generated</option>
        </select>
    </div>
    <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Search</button>
    <a href="branch_view_applicants.php" class="btn btn-secondary">Reset</a>
</form>

<?php if (empty($applicants)): ?>
    <div class="message info">No applicants found for your branch matching the criteria.</div>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>App No.</th>
                <th>Name</th>
                <th>Course</th>
                <th>Application Date</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($applicants as $applicant): ?>
                <tr>
                    <td data-label="App No."><?php echo htmlspecialchars($applicant['application_no']); ?></td>
                    <td data-label="Name"><?php echo htmlspecialchars($applicant['first_name'] . ' ' . $applicant['last_name']); ?></td>
                    <td data-label="Course"><?php echo htmlspecialchars($applicant['course_name']); ?></td>
                    <td data-label="App Date"><?php echo date('d-M-Y', strtotime($applicant['application_date'])); ?></td>
                    <td data-label="Status">
                        <span class="status-<?php echo strtolower(str_replace(' ', '-', $applicant['status'])); ?>">
                            <?php echo htmlspecialchars(ucwords(str_replace('_', ' ', $applicant['status']))); ?>
                        </span>
                    <td data-label="Actions" class="action-links">
                        <a href="print_application_data.php?id=<?php echo $applicant['applicant_id']; ?>" target="_blank" class="btn btn-secondary btn-sm"><i class="fas fa-file-invoice"></i> Print Data</a>
                        <a href="branch_edit_applicant.php?id=<?php echo $applicant['applicant_id']; ?>" class="btn btn-info btn-sm"><i class="fas fa-edit"></i> View/Edit</a>
                        <?php if ($applicant['status'] === 'pending_review'): ?>
                            <a href="branch_delete_applicant_action.php?id=<?php echo $applicant['applicant_id']; ?>" class="btn btn-danger btn-sm confirm-delete"><i class="fas fa-trash-alt"></i> Delete</a>
                        <?php else: ?>
                            <button class="btn btn-secondary btn-sm" disabled><i class="fas fa-trash-alt"></i> Delete</button>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>

<style>
/* Basic styling for status badges in tables */
.status-pending-review {
    background-color: #ffc107; /* Yellow */
    color: #333;
    padding: 5px 8px;
    border-radius: 5px;
    font-size: 0.8em;
    font-weight: bold;
}
.status-approved {
    background-color: #28a745; /* Green */
    color: white;
    padding: 5px 8px;
    border-radius: 5px;
    font-size: 0.8em;
    font-weight: bold;
}
.status-rejected {
    background-color: #dc3545; /* Red */
    color: white;
    padding: 5px 8px;
    border-radius: 5px;
    font-size: 0.8em;
    font-weight: bold;
}
.status-admission-letter-generated {
    background-color: #007bff; /* Blue */
    color: white;
    padding: 5px 8px;
    border-radius: 5px;
    font-size: 0.8em;
    font-weight: bold;
}

/* Styles for search/filter form */
.form-inline {
    display: flex;
    flex-wrap: wrap; /* Allow wrapping on smaller screens */
    gap: 15px; /* Spacing between elements */
    background-color: #ffffff;
    padding: 20px;
    border-radius: 10px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.05);
    border: 1px solid #e0e0e0;
}

.form-inline .form-group {
    flex: 1; /* Allow items to grow and shrink */
    min-width: 180px; /* Minimum width before wrapping */
}

.form-inline label.sr-only {
    position: absolute;
    width: 1px;
    height: 1px;
    padding: 0;
    margin: -1px;
    overflow: hidden;
    clip: rect(0, 0, 0, 0);
    white-space: nowrap;
    border: 0;
}

.form-inline input[type="text"],
.form-inline select {
    width: 100%;
    padding: 10px 12px;
    border: 1px solid #ced4da;
    border-radius: 6px;
    font-size: 0.95em;
}

.form-inline button, .form-inline .btn-secondary {
    padding: 10px 18px;
    font-size: 0.95em;
    align-self: flex-end; /* Align buttons to the bottom if other inputs are taller */
    min-width: 100px;
}

@media (max-width: 768px) {
    .form-inline {
        flex-direction: column; /* Stack items vertically on mobile */
    }
    .form-inline .form-group {
        min-width: 100%; /* Full width for form groups */
    }
    .form-inline button, .form-inline .btn-secondary {
        width: 100%;
    }
}
</style>

<?php
include __DIR__ . '/../includes/footer.php';
$conn->close();
?>