<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_login();

$user_id = $_SESSION['user_id'];
$domain_id = (int)($_GET['id'] ?? 0);

// Security: Verify domain ownership
$stmt = $pdo->prepare("SELECT * FROM user_domains WHERE id = ? AND user_id = ?");
$stmt->execute([$domain_id, $user_id]);
$domain = $stmt->fetch();
if (!$domain) {
    die("Domain not found or unauthorized.");
}

// Date Range
$start_date = $_GET['start'] ?? date('Y-m-d', strtotime('-30 days'));
$end_date = $_GET['end'] ?? date('Y-m-d');

// 1. Total Views & Clicks
$stmt = $pdo->prepare("
    SELECT 
        SUM(CASE WHEN event_type = 'view' THEN 1 ELSE 0 END) as total_views,
        SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END) as total_clicks
    FROM link_analytics 
    WHERE domain_id = ? AND DATE(created_at) BETWEEN ? AND ?
");
$stmt->execute([$domain_id, $start_date, $end_date]);
$counts = $stmt->fetch();
$total_views = $counts['total_views'] ?? 0;
$total_clicks = $counts['total_clicks'] ?? 0;
$ctr = ($total_views > 0) ? round(($total_clicks / $total_views) * 100, 2) : 0;

// 2. Top ISPs
$stmt = $pdo->prepare("
    SELECT isp, COUNT(*) as count 
    FROM link_analytics 
    WHERE domain_id = ? AND DATE(created_at) BETWEEN ? AND ?
    GROUP BY isp 
    ORDER BY count DESC 
    LIMIT 10
");
$stmt->execute([$domain_id, $start_date, $end_date]);
$isps = $stmt->fetchAll();

// 3. Top Devices
$stmt = $pdo->prepare("
    SELECT device, COUNT(*) as count 
    FROM link_analytics 
    WHERE domain_id = ? AND DATE(created_at) BETWEEN ? AND ?
    GROUP BY device 
    ORDER BY count DESC
");
$stmt->execute([$domain_id, $start_date, $end_date]);
$devices = $stmt->fetchAll();

// 4. Top Regions
$stmt = $pdo->prepare("
    SELECT region, COUNT(*) as count 
    FROM link_analytics 
    WHERE domain_id = ? AND DATE(created_at) BETWEEN ? AND ?
    GROUP BY region 
    ORDER BY count DESC 
    LIMIT 10
");
$stmt->execute([$domain_id, $start_date, $end_date]);
$regions = $stmt->fetchAll();

// 5. Daily Trend (for chart)
$stmt = $pdo->prepare("
    SELECT DATE(created_at) as date, 
           SUM(CASE WHEN event_type = 'view' THEN 1 ELSE 0 END) as views,
           SUM(CASE WHEN event_type = 'click' THEN 1 ELSE 0 END) as clicks
    FROM link_analytics 
    WHERE domain_id = ? AND DATE(created_at) BETWEEN ? AND ?
    GROUP BY DATE(created_at) 
    ORDER BY date ASC
");
$stmt->execute([$domain_id, $start_date, $end_date]);
$daily_trend = $stmt->fetchAll();

$pageTitle = "Link Analytics - " . $domain['domain_name'];
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
    .analytics-card { transition: transform 0.2s; border: none; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
    .analytics-card:hover { transform: translateY(-2px); }
    .badge-premium { background: linear-gradient(135deg, #e50914, #ff5c5c); color: white; }
    .bg-primary-focus { background-color: rgba(99, 102, 241, 0.1) !important; }
    .text-primary-main { color: #6366f1 !important; }
    .bg-danger-focus { background-color: rgba(244, 63, 94, 0.1) !important; }
    .text-danger-main { color: #f43f5e !important; }
    .bg-success-focus { background-color: rgba(16, 185, 129, 0.1) !important; }
    .text-success-main { color: #10b981 !important; }
    .bg-info-focus { background-color: rgba(59, 130, 246, 0.1) !important; }
    .text-info-main { color: #3b82f6 !important; }
</style>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <div>
                    <h6 class="fw-semibold mb-0">Link Analytics</h6>
                    <ul class="d-flex align-items-center gap-2 text-sm mt-4">
                        <li class="fw-medium">
                            <a href="<?= SITE_URL ?>/dashboard" class="d-flex align-items-center gap-1 hover-text-primary text-secondary-light">
                                <iconify-icon icon="solar:home-smile-angle-outline" class="icon"></iconify-icon> Dashboard
                            </a>
                        </li>
                        <li class="text-secondary-light">-</li>
                        <li class="fw-medium">
                            <a href="<?= SITE_URL ?>/domains" class="hover-text-primary text-secondary-light">Landing Pages</a>
                        </li>
                        <li class="text-secondary-light">-</li>
                        <li class="fw-medium text-primary-600">Analytics</li>
                    </ul>
                    <p class="text-xs text-secondary-light mb-0 mt-8"><?= SITE_URL ?>/<?= htmlspecialchars($domain['domain_name']) ?></p>
                </div>
                <form class="d-flex align-items-center gap-2 bg-white p-8 radius-8 shadow-sm">
                    <input type="hidden" name="id" value="<?= $domain_id ?>">
                    <input type="date" name="start" value="<?= $start_date ?>" class="form-control form-control-sm border-0 bg-light">
                    <span class="text-xs fw-bold">-</span>
                    <input type="date" name="end" value="<?= $end_date ?>" class="form-control form-control-sm border-0 bg-light">
                    <button type="submit" class="btn btn-primary btn-sm px-16 radius-6">Filter</button>
                </form>
            </div>

            <!-- Scorecards -->
            <div class="row gy-4 mb-24">
                <div class="col-xxl-3 col-sm-6">
                    <div class="card p-24 radius-12 analytics-card">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <span class="text-secondary-light fw-bold text-xs text-uppercase ls-1">Total Views</span>
                                <h3 class="mb-0 mt-8 fw-extrabold"><?= number_format($total_views) ?></h3>
                            </div>
                            <div class="w-48-px h-48-px radius-12 bg-primary-focus text-primary-main d-flex justify-content-center align-items-center">
                                <iconify-icon icon="solar:eye-bold-duotone" class="text-2xl"></iconify-icon>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-sm-6">
                    <div class="card p-24 radius-12 analytics-card">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <span class="text-secondary-light fw-bold text-xs text-uppercase ls-1">Total Clicks</span>
                                <h3 class="mb-0 mt-8 fw-extrabold"><?= number_format($total_clicks) ?></h3>
                            </div>
                            <div class="w-48-px h-48-px radius-12 bg-success-focus text-success-main d-flex justify-content-center align-items-center">
                                <iconify-icon icon="solar:cursor-bold-duotone" class="text-2xl"></iconify-icon>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-sm-6">
                    <div class="card p-24 radius-12 analytics-card">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <span class="text-secondary-light fw-bold text-xs text-uppercase ls-1">Conversion (CTR)</span>
                                <h3 class="mb-0 mt-8 fw-extrabold"><?= $ctr ?>%</h3>
                            </div>
                            <div class="w-48-px h-48-px radius-12 bg-warning-focus text-warning-main d-flex justify-content-center align-items-center">
                                <iconify-icon icon="solar:chart-2-bold-duotone" class="text-2xl"></iconify-icon>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-sm-6">
                    <div class="card p-24 radius-12 analytics-card">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <span class="text-secondary-light fw-bold text-xs text-uppercase ls-1">Tracking Status</span>
                                <h3 class="mb-0 mt-8 fw-extrabold text-success-main">ACTIVE</h3>
                            </div>
                            <div class="w-48-px h-48-px radius-12 bg-info-focus text-info-main d-flex justify-content-center align-items-center">
                                <iconify-icon icon="solar:check-read-bold-duotone" class="text-2xl"></iconify-icon>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row gy-4">
                <!-- Performance Chart -->
                <div class="col-lg-8">
                    <div class="card h-100 radius-12 border-0 shadow-sm">
                        <div class="card-header bg-white border-0 py-20 px-24">
                            <h6 class="mb-0 fw-bold">Daily Performance</h6>
                        </div>
                        <div class="card-body">
                            <canvas id="dailyChart" height="280"></canvas>
                        </div>
                    </div>
                </div>

                <!-- Device Breakdown -->
                <div class="col-lg-4">
                    <div class="card h-100 radius-12 border-0 shadow-sm">
                        <div class="card-header bg-white border-0 py-20 px-24">
                            <h6 class="mb-0 fw-bold">Device Breakdown</h6>
                        </div>
                        <div class="card-body d-flex flex-column justify-content-center">
                            <div style="max-height: 250px;">
                                <canvas id="deviceChart"></canvas>
                            </div>
                            <div class="mt-24">
                                <?php foreach ($devices as $dev): 
                                    $pct = ($total_views > 0) ? round(($dev['count'] / ($total_views + $total_clicks)) * 100, 1) : 0;
                                    $icon = 'solar:monitor-bold-duotone';
                                    if ($dev['device'] === 'Mobile') $icon = 'solar:smartphone-bold-duotone';
                                    if ($dev['device'] === 'Tablet') $icon = 'solar:tablet-bold-duotone';
                                ?>
                                <div class="d-flex align-items-center justify-content-between mb-12">
                                    <div class="d-flex align-items-center gap-8">
                                        <iconify-icon icon="<?= $icon ?>" class="text-secondary-light"></iconify-icon>
                                        <span class="text-sm fw-bold text-secondary-light"><?= $dev['device'] ?></span>
                                    </div>
                                    <span class="text-sm fw-extrabold text-dark"><?= $dev['count'] ?></span>
                                </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- ISPs -->
                <div class="col-lg-6">
                    <div class="card h-100 radius-12 border-0 shadow-sm">
                        <div class="card-header bg-white border-0 py-20 px-24 d-flex align-items-center justify-content-between">
                            <h6 class="mb-0 fw-bold">Top ISPs in Tanzania</h6>
                            <a href="analytics_view_all.php?id=<?= $domain_id ?>&type=isp" class="text-primary-600 hover-text-primary fw-bold text-xs text-uppercase ls-1">View All</a>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table bordered-table mb-0">
                                    <thead>
                                        <tr class="bg-light">
                                            <th class="px-24 py-12 text-xs fw-extrabold text-uppercase text-secondary-light">ISP Provider</th>
                                            <th class="px-24 py-12 text-xs fw-extrabold text-uppercase text-secondary-light text-end">Visits</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if(empty($isps)): ?>
                                            <tr><td colspan="2" class="text-center py-20 text-muted">No ISP data available for this range.</td></tr>
                                        <?php endif; ?>
                                        <?php foreach ($isps as $isp): ?>
                                        <tr>
                                            <td class="px-24 py-12 fw-bold text-primary-600">
                                                <div class="d-flex align-items-center gap-8">
                                                    <iconify-icon icon="solar:globus-bold-duotone" class="text-lg"></iconify-icon>
                                                    <span><?= htmlspecialchars($isp['isp'] ?: 'Other/Unknown') ?></span>
                                                </div>
                                            </td>
                                            <td class="px-24 py-12 text-end">
                                                <span class="badge bg-primary-focus text-primary-main px-12 py-6 radius-8 fw-extrabold">
                                                    <?= number_format($isp['count']) ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Regions -->
                <div class="col-lg-6">
                    <div class="card h-100 radius-12 border-0 shadow-sm">
                        <div class="card-header bg-white border-0 py-20 px-24 d-flex align-items-center justify-content-between">
                            <h6 class="mb-0 fw-bold">Visitor Regions</h6>
                            <a href="analytics_view_all.php?id=<?= $domain_id ?>&type=region" class="text-primary-600 hover-text-primary fw-bold text-xs text-uppercase ls-1">View All</a>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table bordered-table mb-0">
                                    <thead>
                                        <tr class="bg-light">
                                            <th class="px-24 py-12 text-xs fw-extrabold text-uppercase text-secondary-light">Region / City</th>
                                            <th class="px-24 py-12 text-xs fw-extrabold text-uppercase text-secondary-light text-end">Visits</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if(empty($regions)): ?>
                                            <tr><td colspan="2" class="text-center py-20 text-muted">No regional data available yet.</td></tr>
                                        <?php endif; ?>
                                        <?php foreach ($regions as $reg): ?>
                                        <tr>
                                            <td class="px-24 py-12 fw-bold text-dark">
                                                <div class="d-flex align-items-center gap-8">
                                                    <iconify-icon icon="solar:map-point-bold-duotone" class="text-danger-main text-lg"></iconify-icon>
                                                    <span><?= htmlspecialchars($reg['region'] ?: 'Unknown') ?></span>
                                                </div>
                                            </td>
                                            <td class="px-24 py-12 text-end">
                                                <span class="badge bg-danger-focus text-danger-main px-12 py-6 radius-8 fw-extrabold">
                                                    <?= number_format($reg['count']) ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <?php include 'includes/footer.php'; ?>
    </main>

    <script>
        // Data for Daily Chart
        const dailyLabels = <?= json_encode(array_column($daily_trend, 'date')) ?>;
        const viewData = <?= json_encode(array_column($daily_trend, 'views')) ?>;
        const clickData = <?= json_encode(array_column($daily_trend, 'clicks')) ?>;

        const ctxDaily = document.getElementById('dailyChart');
        new Chart(ctxDaily, {
            type: 'line',
            data: {
                labels: dailyLabels,
                datasets: [
                    {
                        label: 'Page Views',
                        data: viewData,
                        borderColor: '#e50914',
                        backgroundColor: 'rgba(229, 9, 20, 0.1)',
                        fill: true,
                        tension: 0.4,
                        borderWidth: 3,
                        pointRadius: 4,
                        pointBackgroundColor: '#e50914'
                    },
                    {
                        label: 'Video Clicks',
                        data: clickData,
                        borderColor: '#28a745',
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        fill: true,
                        tension: 0.4,
                        borderWidth: 3,
                        pointRadius: 4,
                        pointBackgroundColor: '#28a745'
                    }
                ]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'top', labels: { usePointStyle: true, font: { weight: 'bold' } } }
                },
                scales: {
                    y: { beginAtZero: true, grid: { borderDash: [5, 5] } },
                    x: { grid: { display: false } }
                }
            }
        });

        // Data for Device Chart
        const deviceLabels = <?= json_encode(array_column($devices, 'device')) ?>;
        const deviceData = <?= json_encode(array_column($devices, 'count')) ?>;

        const ctxDevice = document.getElementById('deviceChart');
        new Chart(ctxDevice, {
            type: 'doughnut',
            data: {
                labels: deviceLabels,
                datasets: [{
                    data: deviceData,
                    backgroundColor: ['#e50914', '#f59e0b', '#3b82f6'],
                    borderWidth: 0,
                    hoverOffset: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: {
                    legend: { display: false }
                }
            }
        });
    </script>
</body>
</html>


