<?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, u.last_login 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 stats
$stats = [
    'total_students' => $pdo->query("SELECT COUNT(*) FROM students")->fetchColumn(),
    'active_students' => $pdo->query("SELECT COUNT(*) FROM students WHERE status = 'active'")->fetchColumn(),
    'pending_applications' => $pdo->query("SELECT COUNT(*) FROM applications WHERE application_status IN ('submitted', 'under_review')")->fetchColumn(),
    'pending_documents' => $pdo->query("SELECT COUNT(*) FROM student_documents WHERE status = 'pending'")->fetchColumn(),
    'total_applications' => $pdo->query("SELECT COUNT(*) FROM applications")->fetchColumn(),
    'total_revenue' => $pdo->query("SELECT SUM(amount) FROM payments WHERE status = 'completed'")->fetchColumn() ?: 0,
    'unpaid_invoices' => $pdo->query("SELECT SUM(amount) FROM invoices WHERE status = 'unpaid'")->fetchColumn() ?: 0,
    'total_counselors' => $pdo->query("SELECT COUNT(*) FROM counselors")->fetchColumn(),
];

// Get recent activities
$activities = $pdo->prepare("SELECT a.*, u.email, 
                           CASE 
                               WHEN u.user_type = 'student' THEN CONCAT(s.first_name, ' ', s.last_name)
                               WHEN u.user_type = 'counselor' THEN CONCAT(c.first_name, ' ', c.last_name)
                               WHEN u.user_type = 'admin' THEN CONCAT(ad.first_name, ' ', ad.last_name)
                               ELSE u.email
                           END as user_name,
                           u.user_type
                           FROM activities a
                           JOIN users u ON a.user_id = u.id
                           LEFT JOIN students s ON u.id = s.id
                           LEFT JOIN counselors c ON u.id = c.id
                           LEFT JOIN admins ad ON u.id = ad.id
                           ORDER BY a.created_at DESC LIMIT 8");
$activities->execute();
$activities = $activities->fetchAll();

// Get pending applications
$pending_apps = $pdo->prepare("SELECT a.id, a.application_status, a.submission_date,
                              s.first_name, s.last_name, p.name as program, u.name as university
                              FROM applications a
                              JOIN students s ON a.student_id = s.id
                              JOIN programs p ON a.program_id = p.id
                              JOIN universities u ON p.university_id = u.id
                              WHERE a.application_status IN ('submitted', 'under_review')
                              ORDER BY a.submission_date DESC LIMIT 5");
$pending_apps->execute();
$pending_apps = $pending_apps->fetchAll();

// Get pending documents
$pending_docs = $pdo->prepare("SELECT sd.id, sd.document_type, sd.created_at,
                              s.first_name, s.last_name
                              FROM student_documents sd
                              JOIN students s ON sd.student_id = s.id
                              WHERE sd.status = 'pending'
                              ORDER BY sd.created_at DESC LIMIT 5");
$pending_docs->execute();
$pending_docs = $pending_docs->fetchAll();

// Get recent students
$recent_students = $pdo->prepare("SELECT s.id, s.first_name, s.last_name, s.created_at, s.status
                                FROM students s
                                ORDER BY s.created_at DESC LIMIT 5");
$recent_students->execute();
$recent_students = $recent_students->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>Admin Dashboard - 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;
        }
        .stat-card .icon {
            font-size: 2rem;
            opacity: 0.2;
        }
        .table thead th {
            background-color: #f8f9fa;
            border-top: 0;
        }
        .activity-item {
            border-left: 3px solid #3fb7fe;
            padding-left: 15px;
            margin-bottom: 10px;
        }
        .revenue-card {
            background: linear-gradient(135deg, #28a745, #1e7e34);
            color: white;
        }
        .invoice-card {
            background: linear-gradient(135deg, #17a2b8, #117a8b);
            color: white;
        }
        .student-card {
            transition: all 0.3s;
        }
        .student-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .status-badge {
            padding: 5px 12px;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.9em;
        }
        .status-active {
            background: #d4edda;
            color: #155724;
        }
        .status-prospective {
            background: #fff3cd;
            color: #856404;
        }
        .status-admitted {
            background: #d1ecf1;
            color: #0c5460;
        }
        .status-rejected {
            background: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>

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

<div class="container-fluid bg-primary text-white py-5">
    <div class="container">
        <h1>Admin Dashboard</h1>
        <p>Welcome back, <?= htmlspecialchars($admin['first_name']) ?> | Administrator</p>
    </div>
</div>

<div class="container py-5">
    <div class="row">
        <div class="col-md-3 mb-4">
            <div class="card stat-card">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-users icon"></i></div>
                    <h5>Total Students</h5>
                    <h2><?= $stats['total_students'] ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card stat-card" style="border-left-color: #28a745;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-user-graduate icon" style="color: #28a745;"></i></div>
                    <h5>Active Students</h5>
                    <h2><?= $stats['active_students'] ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card stat-card" style="border-left-color: #ffc107;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-file-alt icon" style="color: #ffc107;"></i></div>
                    <h5>Pending Apps</h5>
                    <h2><?= $stats['pending_applications'] ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card stat-card" style="border-left-color: #dc3545;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-clock icon" style="color: #dc3545;"></i></div>
                    <h5>Pending Docs</h5>
                    <h2><?= $stats['pending_documents'] ?></h2>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-3 mb-4">
            <div class="card stat-card" style="border-left-color: #007bff;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-file-invoice icon" style="color: #007bff;"></i></div>
                    <h5>Total Apps</h5>
                    <h2><?= $stats['total_applications'] ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card revenue-card">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-dollar-sign icon"></i></div>
                    <h5>Total Revenue</h5>
                    <h2>$<?= number_format($stats['total_revenue'], 2) ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card invoice-card">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-exclamation-triangle icon"></i></div>
                    <h5>Unpaid Invoices</h5>
                    <h2>$<?= number_format($stats['unpaid_invoices'], 2) ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3 mb-4">
            <div class="card stat-card" style="border-left-color: #6c757d;">
                <div class="card-body">
                    <div class="float-right"><i class="fas fa-user-tie icon" style="color: #6c757d;"></i></div>
                    <h5>Counselors</h5>
                    <h2><?= $stats['total_counselors'] ?></h2>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-8">
            <!-- Pending Applications -->
            <div class="section-title position-relative mb-4">
                <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Pending Tasks</h6>
                <h1 class="display-5">Applications to Review</h1>
            </div>
            <div class="table-responsive mb-5">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Student</th>
                            <th>Program</th>
                            <th>University</th>
                            <th>Status</th>
                            <th>Submitted</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pending_apps as $app): ?>
                        <tr>
                            <td><?= htmlspecialchars($app['first_name'] . ' ' . $app['last_name']) ?></td>
                            <td><?= htmlspecialchars($app['program']) ?></td>
                            <td><?= htmlspecialchars($app['university']) ?></td>
                            <td><span class="status-badge" style="background: #ffc107; color: #856404;"><?= ucfirst($app['application_status']) ?></span></td>
                            <td><?= date('M j', strtotime($app['submission_date'])) ?></td>
                            <td>
                                <a href="admin-applications.php?id=<?= $app['id'] ?>" class="btn btn-sm btn-primary">Review</a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <!-- Pending Documents -->
            <div class="section-title position-relative mb-4">
                <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Document Verification</h6>
                <h1 class="display-5">Documents to Verify</h1>
            </div>
            <div class="table-responsive mb-5">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Student</th>
                            <th>Document</th>
                            <th>Uploaded</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($pending_docs as $doc): ?>
                        <tr>
                            <td><?= htmlspecialchars($doc['first_name'] . ' ' . $doc['last_name']) ?></td>
                            <td><?= ucfirst($doc['document_type']) ?></td>
                            <td><?= date('M j, Y', strtotime($doc['created_at'])) ?></td>
                            <td>
                                <div class="btn-group">
                                    <a href="#" class="btn btn-sm btn-primary">View</a>
                                    <a href="admin-documents.php" class="btn btn-sm btn-outline-primary">Verify</a>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="col-lg-4">
            <!-- Recent Students -->
            <div class="section-title position-relative mb-4">
                <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">New Students</h6>
                <h1 class="display-5">Recently Added</h1>
            </div>
            <div class="card">
                <div class="card-body">
                    <?php foreach ($recent_students as $s): ?>
                    <?php
                        // PHP 8-safe replacement of nested ternary => determine badge class
                        $statusClass = '';
                        switch ($s['status']) {
                            case 'active':
                                $statusClass = 'status-active';
                                break;
                            case 'prospective':
                                $statusClass = 'status-prospective';
                                break;
                            case 'admitted':
                                $statusClass = 'status-admitted';
                                break;
                            case 'rejected':
                                $statusClass = 'status-rejected';
                                break;
                            default:
                                $statusClass = '';
                                break;
                        }
                    ?>
                    <div class="activity-item">
                        <strong><?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?></strong>
                        <br>
                        <small class="text-muted">
                            <?= date('M j, H:i', strtotime($s['created_at'])) ?>
                        </small>
                        <div class="float-right">
                            <span class="status-badge <?= $statusClass ?>">
                                <?= ucfirst($s['status']) ?>
                            </span>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Recent Activities -->
            <div class="mt-4">
                <div class="section-title position-relative mb-4">
                    <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">System Activity</h6>
                    <h1 class="display-5">Recent Activities</h1>
                </div>
                <div class="card">
                    <div class="card-body">
                        <?php foreach ($activities as $act): ?>
                        <div class="activity-item">
                            <strong><?= htmlspecialchars($act['activity_type']) ?></strong>: 
                            <?= htmlspecialchars($act['description']) ?>
                            <br>
                            <small class="text-muted">
                                <?= htmlspecialchars($act['user_name'] ?: $act['email']) ?> 
                                • <?= date('M j, H:i', strtotime($act['created_at'])) ?>
                            </small>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Quick Actions -->
            <div class="mt-4">
                <div class="bg-light p-4 rounded">
                    <h6><i class="fas fa-bolt"></i> Quick Actions</h6>
                    <div class="row mt-3">
                        <div class="col-6 mb-3">
                            <a href="admin-students.php" class="text-decoration-none">
                                <div class="text-center p-3 bg-white shadow-sm rounded">
                                    <i class="fas fa-users card-icon text-primary"></i>
                                    <h6 class="small">Students</h6>
                                </div>
                            </a>
                        </div>
                        <div class="col-6 mb-3">
                            <a href="admin-applications.php" class="text-decoration-none">
                                <div class="text-center p-3 bg-white shadow-sm rounded">
                                    <i class="fas fa-file-alt card-icon text-primary"></i>
                                    <h6 class="small">Applications</h6>
                                </div>
                            </a>
                        </div>
                        <div class="col-6 mb-3">
                            <a href="admin-documents.php" class="text-decoration-none">
                                <div class="text-center p-3 bg-white shadow-sm rounded">
                                    <i class="fas fa-folder card-icon text-primary"></i>
                                    <h6 class="small">Documents</h6>
                                </div>
                            </a>
                        </div>
                        <div class="col-6 mb-3">
                            <a href="admin-messages.php" class="text-decoration-none">
                                <div class="text-center p-3 bg-white shadow-sm rounded">
                                    <i class="fas fa-comments card-icon text-primary"></i>
                                    <h6 class="small">Messages</h6>
                                </div>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </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>
    // Make sure there's an element with id="year" in footer.php; otherwise this line will throw.
    var yearEl = document.getElementById('year');
    if (yearEl) {
        yearEl.textContent = new Date().getFullYear();
    }
</script>
</body>
</html>
