<?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 counselors
$stmt = $pdo->prepare("SELECT c.*, u.email, u.last_login, u.is_active,
                      JSON_UNQUOTE(JSON_EXTRACT(c.specialization, '$')) as specialization_text
                      FROM counselors c
                      JOIN users u ON c.id = u.id
                      ORDER BY c.last_name, c.first_name");
$counselors = $stmt->fetchAll();

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM counselors")->fetchColumn(),
    'active' => $pdo->query("SELECT COUNT(*) FROM counselors c JOIN users u ON c.id = u.id WHERE u.is_active = 1")->fetchColumn(),
    'inactive' => $pdo->query("SELECT COUNT(*) FROM counselors c JOIN users u ON c.id = u.id WHERE u.is_active = 0")->fetchColumn(),
];

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Manage Counselors - 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;
        }
        .profile-img {
            width: 40px;
            height: 40px;
            object-fit: cover;
            border-radius: 50%;
            margin-right: 10px;
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        .status-inactive {
            background: #f8d7da;
            color: #721c24;
        }
        .specialization {
            font-size: 0.9em;
            color: #6c757d;
        }
    </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">Counselor Management</h6>
        <h1 class="display-5">Manage Counselors</h1>
    </div>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card">
                <div class="card-body">
                    <h6>Total Counselors</h6>
                    <h3><?= $stats['total'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 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-3 mb-3">
            <div class="stat-card" style="border-left-color: #dc3545;">
                <div class="card-body">
                    <h6>Inactive</h6>
                    <h3><?= $stats['inactive'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-3">
            <div class="text-right">
                <a href="admin-create-counselor.php" class="btn btn-primary btn-lg">
                    <i class="fas fa-plus"></i> Create New Counselor
                </a>
            </div>
        </div>
    </div>

    <!-- Counselors Table -->
    <div class="table-responsive">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Specialization</th>
                    <th>Capacity</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($counselors as $c): ?>
                <tr>
                    <td>
                        <div class="d-flex align-items-center">
                            <img src="<?= htmlspecialchars($c['profile_photo'] ?: 'img/profile-placeholder.jpg') ?>" 
                                 alt="<?= htmlspecialchars($c['first_name']) ?>" class="profile-img">
                            <?= htmlspecialchars($c['first_name'] . ' ' . $c['last_name']) ?>
                        </div>
                    </td>
                    <td><?= htmlspecialchars($c['email']) ?></td>
                    <td><?= htmlspecialchars($c['phone'] ?? 'Not set') ?></td>
                    <td>
                        <div class="specialization">
                            <?= htmlspecialchars($c['specialization_text'] ?: 'Not specified') ?>
                        </div>
                    </td>
                    <td><?= $c['current_students'] ?? 0 ?> / <?= $c['max_students'] ?></td>
                    <td>
                        <span class="status-badge status-<?= $c['is_active'] ? 'active' : 'inactive' ?>">
                            <?= $c['is_active'] ? 'Active' : 'Inactive' ?>
                        </span>
                    </td>
                    <td>
                        <div class="btn-group">
                            <a href="admin-counselor-profile.php?id=<?= $c['id'] ?>" class="btn btn-sm btn-primary">View</a>
                            <a href="admin-messages.php?counselor_id=<?= $c['id'] ?>" class="btn btn-sm btn-outline-primary">Message</a>
                            <button class="btn btn-sm btn-danger delete-counselor" data-id="<?= $c['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-counselor').on('click', function() {
        const counselorId = $(this).data('id');
        if (confirm('Are you sure you want to delete this counselor? This action cannot be undone.')) {
            alert('In a real application, this would delete the counselor from the database.');
        }
    });
</script>
</body>
</html>