<?php
session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_education';
$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 activity filters
$type_filter = $_GET['type'] ?? '';
$user_filter = $_GET['user'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$sql = "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";

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

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

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

if ($date_from) {
    $conditions[] = "a.created_at >= ?";
    $params[] = $date_from;
}

if ($date_to) {
    $conditions[] = "a.created_at <= ?";
    $params[] = $date_to;
}

if ($search) {
    $conditions[] = "(a.description LIKE ? OR u.email LIKE ?)";
    $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);
$activities = $stmt->fetchAll();

// Get stats
$stats = [
    'total' => $pdo->query("SELECT COUNT(*) FROM activities")->fetchColumn(),
    'by_type' => $pdo->query("SELECT activity_type, COUNT(*) as count FROM activities GROUP BY activity_type ORDER BY count DESC")->fetchAll(),
];

// Get users for filter
$users = $pdo->query("SELECT u.id, u.email, u.user_type, 
                     CONCAT(s.first_name, ' ', s.last_name) as student_name,
                     CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
                     CONCAT(ad.first_name, ' ', ad.last_name) as admin_name
                     FROM users u
                     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
                     WHERE u.user_type IN ('student', 'counselor', 'admin')
                     ORDER BY u.user_type, u.email")->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>Activity Log - 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;
        }
        .activity-item {
            border-left: 3px solid #3fb7fe;
            padding-left: 15px;
            margin-bottom: 15px;
        }
        .activity-item .user-info {
            font-weight: 600;
        }
        .activity-item .activity-type {
            font-size: 0.9em;
            padding: 3px 8px;
            border-radius: 15px;
            font-weight: 600;
        }
        .activity-login {
            background: #d1ecf1;
            color: #0c5460;
        }
        .activity-application {
            background: #d4edda;
            color: #155724;
        }
        .activity-payment {
            background: #fff3cd;
            color: #856404;
        }
        .activity-document {
            background: #f8d7da;
            color: #721c24;
        }
        .activity-system {
            background: #d6d8d9;
            color: #383d41;
        }
        .activity-other {
            background: #e9ecef;
            color: #495057;
        }
    </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">System</h6>
        <h1 class="display-5">Activity Log</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 description or user" 
                           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="type" class="form-control" onchange="window.location='admin-activities.php?type='+this.value<?= $user_filter ? '&user='.urlencode($user_filter) : '' ?><?= $date_from ? '&date_from='.urlencode($date_from) : '' ?><?= $date_to ? '&date_to='.urlencode($date_to) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Types</option>
                        <option value="login" <?= $type_filter === 'login' ? 'selected' : '' ?>>Logins</option>
                        <option value="application_created" <?= $type_filter === 'application_created' ? 'selected' : '' ?>>Applications</option>
                        <option value="payment_received" <?= $type_filter === 'payment_received' ? 'selected' : '' ?>>Payments</option>
                        <option value="document_uploaded" <?= $type_filter === 'document_uploaded' ? 'selected' : '' ?>>Documents</option>
                        <option value="system" <?= $type_filter === 'system' ? 'selected' : '' ?>>System</option>
                    </select>
                </div>
                <div class="col-md-6 mb-2">
                    <select name="user" class="form-control" onchange="window.location='admin-activities.php<?= $type_filter ? '&type='.urlencode($type_filter) : '' ?>&user='+this.value<?= $date_from ? '&date_from='.urlencode($date_from) : '' ?><?= $date_to ? '&date_to='.urlencode($date_to) : '' ?><?= $search ? '&search='.urlencode($search) : '' ?>">
                        <option value="">All Users</option>
                        <?php foreach ($users as $u): ?>
                        <option value="<?= $u['id'] ?>" <?= $user_filter == $u['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($u['user_type'] . ': ' . 
                                ($u['student_name'] ?? $u['counselor_name'] ?? $u['admin_name'] ?? $u['email'])) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>
    </div>

    <!-- Date Filter -->
    <div class="row mb-4">
        <div class="col-lg-6">
            <form method="GET" class="d-flex">
                <div class="flex-grow-1 mr-2">
                    <label>Date From</label>
                    <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($date_from) ?>">
                </div>
                <div class="flex-grow-1 mr-2">
                    <label>Date To</label>
                    <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($date_to) ?>">
                </div>
                <div class="align-self-end">
                    <button type="submit" class="btn btn-primary">Filter</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Stats -->
    <div class="row mb-4">
        <div class="col-md-3 mb-3">
            <div class="stat-card">
                <div class="card-body">
                    <h6>Total Activities</h6>
                    <h3><?= $stats['total'] ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-9">
            <div class="bg-light p-4 rounded">
                <h6><i class="fas fa-chart-bar"></i> Activities by Type</h6>
                <div class="row mt-3">
                    <?php foreach ($stats['by_type'] as $type): ?>
                    <div class="col-md-3 mb-2">
                        <div class="text-center">
                            <strong><?= ucfirst(str_replace('_', ' ', $type['activity_type'])) ?></strong>
                            <div><?= $type['count'] ?> activities</div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Activities List -->
    <div class="bg-white p-4 rounded">
        <?php if (empty($activities)): ?>
        <div class="text-center py-5">
            <i class="fas fa-clipboard-list fa-3x text-muted mb-3"></i>
            <p>No activities found for the selected criteria.</p>
        </div>
        <?php else: ?>
        <?php foreach ($activities as $activity): ?>
        <div class="activity-item">
            <div class="d-flex justify-content-between">
                <div>
                    <strong><?= htmlspecialchars($activity['user_name'] ?? $activity['email']) ?></strong>
                    <span class="activity-type activity-<?= 
                        $activity['activity_type'] === 'login' ? 'login' :
                        $activity['activity_type'] === 'application_created' ? 'application' :
                        $activity['activity_type'] === 'payment_received' ? 'payment' :
                        $activity['activity_type'] === 'document_uploaded' ? 'document' :
                        $activity['activity_type'] === 'system' ? 'system' : 'other'
                    ?>">
                        <?= ucfirst(str_replace('_', ' ', $activity['activity_type'])) ?>
                    </span>
                </div>
                <small class="text-muted">
                    <?= date('M j, Y H:i', strtotime($activity['created_at'])) ?>
                </small>
            </div>
            <p class="mb-0"><?= htmlspecialchars($activity['description']) ?></p>
        </div>
        <?php endforeach; ?>
        <?php endif; ?>
    </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>
    document.getElementById('year').textContent = new Date().getFullYear();
</script>
</body>
</html>