<?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 students with filtering
$status_filter = $_GET['status'] ?? '';
$counselor_filter = $_GET['counselor'] ?? '';
$search = $_GET['search'] ?? '';

$sql = "SELECT s.*, u.email, u.last_login,
        CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
        c.id as counselor_id
        FROM students s
        JOIN users u ON s.id = u.id
        LEFT JOIN counselors c ON s.assigned_counselor_id = c.id";

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

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

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

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

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

$sql .= " ORDER BY s.last_name, s.first_name";

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

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM students")->fetchColumn(),
    'prospective' => $pdo->query("SELECT COUNT(*) FROM students WHERE status = 'prospective'")->fetchColumn(),
    'active' => $pdo->query("SELECT COUNT(*) FROM students WHERE status = 'active'")->fetchColumn(),
    'admitted' => $pdo->query("SELECT COUNT(*) FROM students WHERE status = 'admitted'")->fetchColumn(),
    'rejected' => $pdo->query("SELECT COUNT(*) FROM students WHERE status = 'rejected'")->fetchColumn(),
];

// 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>Students - 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;
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-prospective {
            background: #fff3cd;
            color: #856404;
        }
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        .status-admitted {
            background: #d1ecf1;
            color: #0c5460;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
        .status-alumni {
            background: #d6d8d9;
            color: #383d41;
        }
        .profile-img {
            width: 40px;
            height: 40px;
            object-fit: cover;
            border-radius: 50%;
            margin-right: 10px;
        }
    </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">Student Management</h6>
        <h1 class="display-5">Manage Students</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 students by name or email" 
                           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-students.php?status='+this.value<?= $counselor_filter ? '&counselor='.urlencode($counselor_filter) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Statuses (<?= $stats['total'] ?>)</option>
                        <option value="prospective" <?= $status_filter === 'prospective' ? 'selected' : '' ?>>Prospective (<?= $stats['prospective'] ?>)</option>
                        <option value="active" <?= $status_filter === 'active' ? 'selected' : '' ?>>Active (<?= $stats['active'] ?>)</option>
                        <option value="admitted" <?= $status_filter === 'admitted' ? 'selected' : '' ?>>Admitted (<?= $stats['admitted'] ?>)</option>
                        <option value="rejected" <?= $status_filter === 'rejected' ? 'selected' : '' ?>>Rejected (<?= $stats['rejected'] ?>)</option>
                    </select>
                </div>
                <div class="col-md-6 mb-2">
                    <select name="counselor" class="form-control" onchange="window.location='admin-students.php<?= $status_filter ? '&status='.urlencode($status_filter) : '' ?>&counselor='+this.value<?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Counselors</option>
                        <?php foreach ($counselors as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= $counselor_filter == $c['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['first_name'] . ' ' . $c['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>Prospective</h6>
                    <h3><?= $stats['prospective'] ?></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>Active</h6>
                    <h3><?= $stats['active'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-2 mb-3">
            <div class="stat-card" style="border-left-color: #17a2b8;">
                <div class="card-body">
                    <h6>Admitted</h6>
                    <h3><?= $stats['admitted'] ?></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-student.php" class="btn btn-primary btn-lg">
                    <i class="fas fa-plus"></i> Add Student
                </a>
            </div>
        </div>
    </div>

    <!-- Students Table -->
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Education Level</th>
                    <th>Status</th>
                    <th>Counselor</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($students as $s): ?>
                <tr>
                    <td>
                        <div class="d-flex align-items-center">
                            <img src="<?= htmlspecialchars($s['profile_photo'] ?: 'img/profile-placeholder.jpg') ?>" 
                                 alt="<?= htmlspecialchars($s['first_name']) ?>" class="profile-img">
                            <?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?>
                        </div>
                    </td>
                    <td><?= htmlspecialchars($s['email']) ?></td>
                    <td><?= htmlspecialchars($s['phone'] ?? 'Not set') ?></td>
                    <td><?= htmlspecialchars($s['education_level'] ?? 'Not specified') ?></td>
                    <td>
                        <span class="status-badge status-<?= $s['status'] ?>">
                            <?= ucfirst($s['status']) ?>
                        </span>
                    </td>
                    <td><?= htmlspecialchars($s['counselor_name'] ?? 'Not assigned') ?></td>
                    <td>
                        <div class="btn-group">
                            <a href="admin-student-profile.php?id=<?= $s['id'] ?>" class="btn btn-sm btn-primary">View</a>
                            <a href="admin-messages.php?student_id=<?= $s['id'] ?>" class="btn btn-sm btn-outline-primary">Message</a>
                            <button class="btn btn-sm btn-danger delete-student" data-id="<?= $s['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-student').on('click', function() {
        const studentId = $(this).data('id');
        if (confirm('Are you sure you want to delete this student? This action cannot be undone.')) {
            alert('In a real application, this would delete the student from the database.');
        }
    });
</script>
</body>
</html>