<?php
require_once '../config/config.php';
requireLogin();
if (!isSuperAdmin() && !isInstitutionAdmin()) redirect(SITE_URL . '/index.php');

$pageTitle = 'Analytics Dashboard';

$db = getDB();

// User growth
$stmt = $db->prepare("
    SELECT DATE(created_at) as date, COUNT(*) as count
    FROM users
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY DATE(created_at)
    ORDER BY date
");
$stmt->execute();
$userGrowth = $stmt->fetchAll();

// Study statistics by type
$stmt = $db->prepare("
    SELECT type, COUNT(*) as count
    FROM studies
    GROUP BY type
    ORDER BY count DESC
");
$stmt->execute();
$studyTypes = $stmt->fetchAll();

// Top institutions
$stmt = $db->prepare("
    SELECT i.name, COUNT(im.id) as members_count
    FROM institutions i
    LEFT JOIN institution_members im ON i.id = im.institution_id
    GROUP BY i.id
    ORDER BY members_count DESC
    LIMIT 10
");
$stmt->execute();
$topInstitutions = $stmt->fetchAll();

// Activity summary

$stmt = $db->prepare("SELECT COUNT(*) FROM users WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
if ($stmt->execute()) {
    $newUsersWeek = $stmt->fetchColumn();
} else {
    $newUsersWeek = 0;
}

$stmt = $db->prepare("SELECT COUNT(*) FROM studies WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)");
if ($stmt->execute()) {
    $newStudiesWeek = $stmt->fetchColumn();
} else {
    $newStudiesWeek = 0;
}

include '../templates/admin-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar-new.php'; ?>
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <?php include 'header-bar.php'; ?>

            <div class="row mb-4">
                <div class="col-md-6">
                    <div class="card shadow">
                        <div class="card-header">
                            <h6 class="mb-0">User Growth (Last 30 Days)</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="userGrowthChart" height="200"></canvas>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="card shadow">
                        <div class="card-header">
                            <h6 class="mb-0">Studies by Type</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="studyTypesChart" height="200"></canvas>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="card shadow">
                        <div class="card-header">
                            <h6 class="mb-0">Top Institutions by Members</h6>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>Institution</th>
                                            <th>Members</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($topInstitutions as $inst): ?>
                                        <tr>
                                            <td><?php echo e($inst['name']); ?></td>
                                            <td><?php echo $inst['members_count']; ?></td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-6">
                    <div class="card shadow">
                        <div class="card-header">
                            <h6 class="mb-0">Weekly Summary</h6>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <h4><?php echo $newUsersWeek; ?></h4>
                                <p class="text-muted mb-0">New Users This Week</p>
                            </div>
                            <div class="mb-3">
                                <h4><?php echo $newStudiesWeek; ?></h4>
                                <p class="text-muted mb-0">New Studies This Week</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
// User Growth Chart
const userGrowthCtx = document.getElementById('userGrowthChart').getContext('2d');
new Chart(userGrowthCtx, {
    type: 'line',
    data: {
        labels: <?php echo json_encode(array_column($userGrowth, 'date')); ?>,
        datasets: [{
            label: 'New Users',
            data: <?php echo json_encode(array_column($userGrowth, 'count')); ?>,
            borderColor: 'rgb(75, 192, 192)',
            tension: 0.1
        }]
    }
});

// Study Types Chart
const studyTypesCtx = document.getElementById('studyTypesChart').getContext('2d');
new Chart(studyTypesCtx, {
    type: 'doughnut',
    data: {
        labels: <?php echo json_encode(array_column($studyTypes, 'type')); ?>,
        datasets: [{
            data: <?php echo json_encode(array_column($studyTypes, 'count')); ?>,
            backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40']
        }]
    }
});
</script>

<?php include '../templates/admin-footer.php'; ?>
