<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: admin-login.php');
    exit;
}

// Get admin data
$stmt = $pdo->prepare("SELECT a.*, u.email FROM admins a JOIN users u ON a.id = u.id WHERE a.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$admin) {
    die("Admin profile not found.");
}

// Get application filters
$status_filter = $_GET['status'] ?? '';
$student_filter = $_GET['student'] ?? '';
$counselor_filter = $_GET['counselor'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$sql = "SELECT a.*, s.first_name, s.last_name, us.email as student_email,
        p.name as program_name, p.degree_level,
        u.name as university_name, u.logo as university_logo,
        CONCAT(c.first_name, ' ', c.last_name) as counselor_name
        FROM applications a
        JOIN students s ON a.student_id = s.id
        JOIN users us ON s.id = us.id
        JOIN programs p ON a.program_id = p.id
        JOIN universities u ON p.university_id = u.id
        LEFT JOIN counselors c ON a.counselor_id = c.id";

$conditions = [];
$params = [];

if ($status_filter) {
    $conditions[] = "a.application_status = ?";
    $params[] = $status_filter;
}

if ($student_filter) {
    $conditions[] = "a.student_id = ?";
    $params[] = $student_filter;
}

if ($counselor_filter) {
    $conditions[] = "a.counselor_id = ?";
    $params[] = $counselor_filter;
}

if ($search) {
    $conditions[] = "(s.first_name LIKE ? OR s.last_name LIKE ? OR u.name LIKE ? OR p.name LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($conditions) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

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

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$applications = $stmt->fetchAll();

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM applications")->fetchColumn(),
    'submitted' => $pdo->query("SELECT COUNT(*) FROM applications WHERE application_status = 'submitted'")->fetchColumn(),
    'under_review' => $pdo->query("SELECT COUNT(*) FROM applications WHERE application_status = 'under_review'")->fetchColumn(),
    'accepted' => $pdo->query("SELECT COUNT(*) FROM applications WHERE application_status = 'accepted'")->fetchColumn(),
    'rejected' => $pdo->query("SELECT COUNT(*) FROM applications WHERE application_status = 'rejected'")->fetchColumn(),
];

// Get students for filter
$students = $pdo->query("SELECT id, first_name, last_name FROM students ORDER BY last_name, first_name")->fetchAll();

// Get counselors for filter
$counselors = $pdo->query("SELECT id, first_name, last_name FROM counselors ORDER BY last_name, first_name")->fetchAll();

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: admin-login.php');
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Applications - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .stat-card {
            border-left: 5px solid #3fb7fe;
            margin-bottom: 20px;
        }
        .university-logo {
            height: 40px;
            object-fit: contain;
            background: white;
            padding: 3px;
            border-radius: 5px;
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-submitted {
            background: #fff3cd;
            color: #856404;
        }
        .status-under_review {
            background: #cce5ff;
            color: #004085;
        }
        .status-accepted {
            background: #d4edda;
            color: #155724;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        .status-draft {
            background: #d6d8d9;
            color: #383d41;
        }
    </style>
</head>
<body>

<?php include 'admin-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Application Management</h6>
        <h1 class="display-5">Manage Applications</h1>
    </div>

    <!-- Search and Filter -->
    <div class="row mb-4">
        <div class="col-lg-8">
            <form method="GET" class="d-flex">
                <div class="flex-grow-1 mr-2">
                    <input type="text" name="search" class="form-control" placeholder="Search by student, university, or program" 
                           value="<?= htmlspecialchars($search) ?>">
                </div>
                <button type="submit" class="btn btn-primary">Search</button>
            </form>
        </div>
        <div class="col-lg-4">
            <div class="row">
                <div class="col-md-6 mb-2">
                    <select name="status" class="form-control" onchange="window.location='admin-applications.php?status='+this.value<?= $student_filter ? '&student='.urlencode($student_filter) : '' ?><?= $counselor_filter ? '&counselor='.urlencode($counselor_filter) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Statuses (<?= $stats['total'] ?>)</option>
                        <option value="submitted" <?= $status_filter === 'submitted' ? 'selected' : '' ?>>Submitted (<?= $stats['submitted'] ?>)</option>
                        <option value="under_review" <?= $status_filter === 'under_review' ? 'selected' : '' ?>>Under Review (<?= $stats['under_review'] ?>)</option>
                        <option value="accepted" <?= $status_filter === 'accepted' ? 'selected' : '' ?>>Accepted (<?= $stats['accepted'] ?>)</option>
                        <option value="rejected" <?= $status_filter === 'rejected' ? 'selected' : '' ?>>Rejected (<?= $stats['rejected'] ?>)</option>
                    </select>
                </div>
                <div class="col-md-6 mb-2">
                    <select name="student" class="form-control" onchange="window.location='admin-applications.php<?= $status_filter ? '&status='.urlencode($status_filter) : '' ?>&student='+this.value<?= $counselor_filter ? '&counselor='.urlencode($counselor_filter) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Students</option>
                        <?php foreach ($students as $s): ?>
                        <option value="<?= $s['id'] ?>" <?= $student_filter == $s['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-2 mb-3">
            <div class="stat-card">
                <div class="card-body">
                    <h6>Total</h6>
                    <h3><?= $stats['total'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-3">
            <div class="stat-card" style="border-left-color: #ffc107;">
                <div class="card-body">
                    <h6>Submitted</h6>
                    <h3><?= $stats['submitted'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-3">
            <div class="stat-card" style="border-left-color: #007bff;">
                <div class="card-body">
                    <h6>Under Review</h6>
                    <h3><?= $stats['under_review'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-3">
            <div class="stat-card" style="border-left-color: #28a745;">
                <div class="card-body">
                    <h6>Accepted</h6>
                    <h3><?= $stats['accepted'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-3">
            <div class="stat-card" style="border-left-color: #dc3545;">
                <div class="card-body">
                    <h6>Rejected</h6>
                    <h3><?= $stats['rejected'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-3">
            <div class="text-right">
                <a href="admin-create-application.php" class="btn btn-primary btn-lg">
                    <i class="fas fa-plus"></i> Create Application
                </a>
            </div>
        </div>
    </div>

    <!-- Applications Table -->
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Student</th>
                    <th>University</th>
                    <th>Program</th>
                    <th>Status</th>
                    <th>Submitted</th>
                    <th>Counselor</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($applications as $app): ?>
                <tr>
                    <td><?= htmlspecialchars($app['first_name'] . ' ' . $app['last_name']) ?></td>
                    <td>
                        <div class="d-flex align-items-center">
                            <img src="<?= htmlspecialchars($app['university_logo'] ?: 'img/university-placeholder.png') ?>" 
                                 alt="<?= htmlspecialchars($app['university_name']) ?>" class="university-logo mr-2">
                            <?= htmlspecialchars($app['university_name']) ?>
                        </div>
                    </td>
                    <td><?= htmlspecialchars($app['degree_level'] . ' in ' . $app['program_name']) ?></td>
                    <td>
                        <span class="status-badge status-<?= $app['application_status'] ?>">
                            <?= ucfirst(str_replace('_', ' ', $app['application_status'])) ?>
                        </span>
                    </td>
                    <td><?= $app['submission_date'] ? date('M j, Y', strtotime($app['submission_date'])) : 'Not submitted' ?></td>
                    <td><?= htmlspecialchars($app['counselor_name'] ?? 'Not assigned') ?></td>
                    <td>
                        <div class="btn-group">
                            <a href="admin-application-review.php?id=<?= $app['id'] ?>" class="btn btn-sm btn-primary">Review</a>
                            <a href="admin-messages.php?student_id=<?= $app['student_id'] ?>" class="btn btn-sm btn-outline-primary">Message</a>
                            <button class="btn btn-sm btn-danger delete-application" data-id="<?= $app['id'] ?>">Delete</button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    $('.delete-application').on('click', function() {
        const appId = $(this).data('id');
        if (confirm('Are you sure you want to delete this application? This action cannot be undone.')) {
            alert('In a real application, this would delete the application from the database.');
        }
    });
</script>
</body>
</html>