<?php
session_start();
include('config.php');
require_once('api.php');

date_default_timezone_set('Asia/Jakarta');

$data = [];
$page = "statistics";

// Date handling
if (isset($_GET['date']) && $_GET['date'] != "") {
    if ($_GET['date'] == "yesterday") {
        $data['from'] = strtotime("yesterday");
        $data['to'] = strtotime("yesterday");
    } elseif ($_GET['date'] == "today") { 
        $data['from'] = strtotime("today");
        $data['to'] = strtotime(date('Y-m-d H:i:s'));
    }
} else {
    $data['from'] = isset($_GET['from']) && $_GET['from'] != "" ? strtotime($_GET['from']) : strtotime("today");
    $data['to'] = isset($_GET['to']) && $_GET['to'] != "" ? strtotime($_GET['to']) : strtotime(date('Y-m-d H:i:s'));
}

// Login check
if (isset($_POST['loginpass']) && $_POST['password'] != "") {
    if ($_POST['password'] == $passWd) {
        $_SESSION['loggedIn'] = true;
    } else {
        $loginError = "Password Salah!";
    }
}

if (!isset($_SESSION['loggedIn'])) {
    header('Location: dashboard_index.php');
    exit;
}

include('dashboard_header.php');

// Get statistics data
$startDate = date('Y-m-d', $data['from']);
$endDate = date('Y-m-d', $data['to']);
$stats = getStatistics($startDate, $endDate);

// Calculate totals
$totalVisits = 0;
$totalUnique = 0;
$totalClicks = 0;
$totalLeads = 0;
$totalPayouts = 0;

if (!empty($stats['data'])) {
    foreach ($stats['data'] as $row) {
        $totalVisits += intval($row['visits'] ?? 0);
        $totalUnique += intval($row['unique'] ?? 0);
        $totalClicks += intval($row['clicks'] ?? 0);
        $totalLeads += intval($row['leads'] ?? 0);
        $totalPayouts += floatval($row['payouts'] ?? 0);
    }
}

// Calculate conversion rates
$clickRate = $totalVisits > 0 ? ($totalClicks / $totalVisits) * 100 : 0;
$conversionRate = $totalClicks > 0 ? ($totalLeads / $totalClicks) * 100 : 0;
$avgPayout = $totalLeads > 0 ? $totalPayouts / $totalLeads : 0;
?>

<!-- Statistics Overview -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-header">
            <div class="stat-title">Total Visits</div>
            <div class="stat-icon primary">
                <i class="fas fa-eye"></i>
            </div>
        </div>
        <div class="stat-value"><?= number_format($totalVisits); ?></div>
        <div class="stat-change positive">
            <i class="fas fa-chart-line"></i>
            Traffic volume
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-header">
            <div class="stat-title">Unique Visitors</div>
            <div class="stat-icon info">
                <i class="fas fa-users"></i>
            </div>
        </div>
        <div class="stat-value"><?= number_format($totalUnique); ?></div>
        <div class="stat-change positive">
            <i class="fas fa-user-check"></i>
            Unique traffic
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-header">
            <div class="stat-title">Click Rate</div>
            <div class="stat-icon warning">
                <i class="fas fa-mouse-pointer"></i>
            </div>
        </div>
        <div class="stat-value"><?= number_format($clickRate, 1); ?>%</div>
        <div class="stat-change <?= $clickRate >= 5 ? 'positive' : 'negative'; ?>">
            <i class="fas fa-percentage"></i>
            Engagement rate
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-header">
            <div class="stat-title">Conversion Rate</div>
            <div class="stat-icon success">
                <i class="fas fa-bullseye"></i>
            </div>
        </div>
        <div class="stat-value"><?= number_format($conversionRate, 1); ?>%</div>
        <div class="stat-change <?= $conversionRate >= 10 ? 'positive' : 'negative'; ?>">
            <i class="fas fa-target"></i>
            Lead conversion
        </div>
    </div>
</div>

<!-- Date Range Selector -->
<div class="content-card mb-4">
    <div class="card-header">
        <h5 class="card-title mb-0">
            <i class="fas fa-calendar-alt me-2"></i>
            Performance Analytics - <?= date("d M Y", $data['from']) ?> to <?= date("d M Y", $data['to']) ?>
        </h5>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-8">
                <form method="get" class="d-flex gap-3 align-items-end">
                    <div class="flex-fill">
                        <label class="form-label small text-muted">From Date</label>
                        <input name="from" type="text" class="form-control datepicker" placeholder="From" 
                               value="<?= isset($_GET['from']) ? htmlspecialchars($_GET['from']) : '' ?>">
                    </div>
                    <div class="flex-fill">
                        <label class="form-label small text-muted">To Date</label>
                        <input name="to" type="text" class="form-control datepicker" placeholder="To" 
                               value="<?= isset($_GET['to']) ? htmlspecialchars($_GET['to']) : '' ?>">
                    </div>
                    <button class="btn btn-primary" type="submit">
                        <i class="fas fa-search me-1"></i>
                        Analyze
                    </button>
                </form>
            </div>
            <div class="col-md-4">
                <label class="form-label small text-muted">Quick Select</label>
                <select class="form-control" id="quickDateSelect">
                    <option value="">Choose period</option>
                    <option value="today">Today</option>
                    <option value="yesterday">Yesterday</option>
                    <option value="week">This Week</option>
                    <option value="month">This Month</option>
                </select>
            </div>
        </div>
    </div>
</div>

<!-- Detailed Statistics Table -->
<div class="content-card">
    <div class="card-header">
        <h5 class="card-title mb-0">
            <i class="fas fa-table me-2"></i>
            Detailed Performance Metrics
        </h5>
        <div class="d-flex align-items-center gap-2">
            <span class="badge badge-info">Total: $<?= number_format($totalPayouts, 2); ?></span>
            <span class="badge badge-success"><?= number_format($totalLeads); ?> Leads</span>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="dataTable" class="modern-table">
                <thead>
                    <tr>
                        <th>Smartlink</th>
                        <th>Visits</th>
                        <th>Unique</th>
                        <th>Clicks</th>
                        <th>Leads</th>
                        <th>CR</th>
                        <th>LR</th>
                        <th>Payouts</th>
                        <th>eCPM</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    if (!empty($stats['data'])) {
                        foreach ($stats['data'] as $row) {
                            $visits = intval($row['visits'] ?? 0);
                            $unique = intval($row['unique'] ?? 0);
                            $clicks = intval($row['clicks'] ?? 0);
                            $leads = intval($row['leads'] ?? 0);
                            $payouts = floatval($row['payouts'] ?? 0);
                            
                            $clickRate = $visits > 0 ? ($clicks / $visits) * 100 : 0;
                            $convRate = $clicks > 0 ? ($leads / $clicks) * 100 : 0;
                            $ecpm = $visits > 0 ? ($payouts / $visits) * 1000 : 0;
                            
                            echo "<tr>
                                <td><strong>" . htmlspecialchars($row['smartlink'] ?? '-') . "</strong></td>
                                <td>" . number_format($visits) . "</td>
                                <td>" . number_format($unique) . "</td>
                                <td>" . number_format($clicks) . "</td>
                                <td><span class='badge badge-success'>" . number_format($leads) . "</span></td>
                                <td>" . number_format($clickRate, 2) . "%</td>
                                <td>" . number_format($convRate, 2) . "%</td>
                                <td class='text-success fw-bold'>$" . number_format($payouts, 2) . "</td>
                                <td>$" . number_format($ecpm, 2) . "</td>
                            </tr>";
                        }
                    } else {
                        echo "<tr><td colspan='9' class='text-center text-muted py-4'>
                                <i class='fas fa-chart-line fa-2x mb-2 d-block'></i>
                                No statistics available for this period
                              </td></tr>";
                    }
                    ?>
                </tbody>
                <tfoot>
                    <tr class="table-dark">
                        <th>TOTAL</th>
                        <th><?= number_format($totalVisits); ?></th>
                        <th><?= number_format($totalUnique); ?></th>
                        <th><?= number_format($totalClicks); ?></th>
                        <th><?= number_format($totalLeads); ?></th>
                        <th><?= number_format($clickRate, 2); ?>%</th>
                        <th><?= number_format($conversionRate, 2); ?>%</th>
                        <th class="text-success">$<?= number_format($totalPayouts, 2); ?></th>
                        <th>$<?= number_format($totalVisits > 0 ? ($totalPayouts / $totalVisits) * 1000 : 0, 2); ?></th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>

<script>
// Quick date selection
document.getElementById('quickDateSelect').addEventListener('change', function() {
    const value = this.value;
    if (value) {
        window.location.href = '?date=' + value;
    }
});

// Initialize charts
document.addEventListener('DOMContentLoaded', function() {
    // Performance Chart
    const performanceCtx = document.getElementById('performanceChart').getContext('2d');
    new Chart(performanceCtx, {
        type: 'line',
        data: {
            labels: ['Visits', 'Clicks', 'Leads', 'Payouts'],
            datasets: [{
                label: 'Performance Metrics',
                data: [<?= $totalVisits; ?>, <?= $totalClicks; ?>, <?= $totalLeads; ?>, <?= $totalPayouts; ?>],
                borderColor: '#6366f1',
                backgroundColor: 'rgba(99, 102, 241, 0.1)',
                borderWidth: 3,
                fill: true,
                tension: 0.4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    display: false
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(148, 163, 184, 0.1)'
                    },
                    ticks: {
                        color: '#94a3b8'
                    }
                },
                x: {
                    grid: {
                        color: 'rgba(148, 163, 184, 0.1)'
                    },
                    ticks: {
                        color: '#94a3b8'
                    }
                }
            }
        }
    });

    // Network Distribution Chart
    const networkCtx = document.getElementById('networkChart').getContext('2d');
    new Chart(networkCtx, {
        type: 'doughnut',
        data: {
            labels: ['ImonetiZeit', 'Adverten', 'ClickDealer', 'Others'],
            datasets: [{
                data: [40, 25, 20, 15], // Sample data - replace with actual network stats
                backgroundColor: [
                    '#10b981',
                    '#ef4444', 
                    '#6366f1',
                    '#8b5cf6'
                ],
                borderWidth: 0
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        color: '#94a3b8',
                        usePointStyle: true,
                        padding: 20
                    }
                }
            }
        }
    });
});

// Initialize date pickers
$('.datepicker').datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
    todayHighlight: true
});
</script>

<?php include('dashboard_footer.php'); ?>