<?php
// school_admission/public/admin_view_applications.php

// --- DEBUGGING LINES START ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// --- DEBUGGING LINES END ---

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(['super_admin']); // Only Super Admin can access this page

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

// --- 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
$branch_filter = isset($_GET['branch_filter']) ? (int)$_GET['branch_filter'] : 0; // Default filter by all branches

$applicants = [];
$sql = "SELECT
            a.applicant_id,
            a.first_name,
            a.last_name,
            a.application_no,
            a.application_date,
            a.status,
            c.course_name,
            b.branch_name
        FROM
            applicants a
        JOIN
            courses c ON a.course_id = c.course_id
        JOIN
            branches b ON a.branch_id = b.branch_id
        WHERE 1=1"; // Start with a true condition for easy appending of AND clauses

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

// 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";
    } elseif ($filter_by === 'branch') {
        $sql .= "b.branch_name LIKE ?";
        $params[] = '%' . $search_term . '%';
        $types .= "s";
    }
    $sql .= ")";
}

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

// Add branch filter (from dropdown)
if ($branch_filter !== 0) {
    $sql .= " AND a.branch_id = ?";
    $params[] = $branch_filter;
    $types .= "i";
}

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

$stmt = $conn->prepare($sql);
if ($stmt) {
    // Dynamically bind parameters only if there are any
    if (!empty($params)) {
        // --- FIX FOR "Argument #X must be passed by reference" WARNING ---
        $bind_args = [];
        $bind_args[] = $types; // The type definition string (passed by value here)

        // Add each parameter to the bind_args array BY REFERENCE
        foreach ($params as $key => $value) {
            $bind_args[] = &$params[$key]; // Pass by reference
        }
        // --- END FIX ---
        
        call_user_func_array([$stmt, 'bind_param'], $bind_args); // Line 98 will be here
    }
    $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>";
}

// Fetch all branches for the branch filter dropdown
$all_branches = [];
$branch_result = $conn->query("SELECT branch_id, branch_name FROM branches ORDER BY branch_name ASC");
if ($branch_result) {
    while ($row = $branch_result->fetch_assoc()) {
        $all_branches[] = $row;
    }
    $branch_result->free();
}

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

<h2 class="mt-30">All Applications</h2>

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

<!-- Search and Filter Form -->
<form action="admin_view_applications.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>
            <option value="branch" <?php echo ($filter_by === 'branch') ? 'selected' : ''; ?>>Branch Name</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>
    <div class="form-group">
        <label for="branch_filter" class="sr-only">Filter by Branch:</label>
        <select id="branch_filter" name="branch_filter">
            <option value="0" <?php echo ($branch_filter === 0) ? 'selected' : ''; ?>>All Branches</option>
            <?php foreach ($all_branches as $branch): ?>
                <option value="<?php echo htmlspecialchars($branch['branch_id']); ?>" <?php echo ($branch_filter == $branch['branch_id']) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($branch['branch_name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Search</button>
    <a href="admin_view_applications.php" class="btn btn-secondary">Reset</a>
</form>

<?php if (empty($applicants)): ?>
    <div class="message info">No applications found in the system matching the criteria.</div>
<?php else: ?>
    <table>
        <thead>
            <tr>
                <th>App No.</th>
                <th>Name</th>
                <th>Branch</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="Branch"><?php echo htmlspecialchars($applicant['branch_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>
                    <td data-label="Actions" class="action-links">
                        <a href="admin_application_details.php?id=<?php echo $applicant['applicant_id']; ?>" class="btn btn-info btn-sm"><i class="fas fa-eye"></i> View Details</a>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
<?php endif; ?>

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