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

$user_id = $_SESSION['user_id'];
$user_data = ['name' => 'User', 'email' => 'N/A'];
$daily_stats = [];
$total_period_revenue = 0;
$total_period_transactions = 0;
$total_pending_amount = 0;
$total_pending_count = 0;
$total_all_transactions = 0;
$site_settings = get_site_settings($pdo);
$system_comm = $site_settings['system_commission'] ?? 0;

try {
    // Get user basic info - Adjusted to match db.sql (name, email)
    $stmt = $pdo->prepare("SELECT name, email FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $fetched_user = $stmt->fetch();
    if ($fetched_user) {
        $user_data = $fetched_user;
    }
    
    // Daily Revenue Data for Chart & Table
    $stmt = $pdo->prepare("
        SELECT 
            DATE(t.created_at) as date, 
            COUNT(*) as transactions, 
            SUM(t.amount) as gross_revenue 
        FROM transactions t 
        JOIN videos v ON t.video_id = v.id 
        WHERE v.user_id = ? AND t.status = 'completed' 
        GROUP BY DATE(t.created_at) 
        ORDER BY DATE(t.created_at) DESC
    ");
    $stmt->execute([$user_id]);
    $daily_stats = $stmt->fetchAll();
    
    // Aggregates for Metric Cards
    foreach($daily_stats as &$day) {
        $day['revenue'] = $day['gross_revenue'] * (1 - ($system_comm / 100));
        $total_period_revenue += $day['revenue'];
        $total_period_transactions += $day['transactions'];
    }
    unset($day);

    // Pending Transactions
    $stmt = $pdo->prepare("SELECT COUNT(*) as cnt, SUM(t.amount) as gross_amt FROM transactions t JOIN videos v ON t.video_id = v.id WHERE v.user_id = ? AND t.status = 'pending'");
    $stmt->execute([$user_id]);
    $pendingData = $stmt->fetch();
    $gross_pending = $pendingData['gross_amt'] ?? 0;
    $total_pending_amount = $gross_pending * (1 - ($system_comm / 100));
    $total_pending_count = $pendingData['cnt'] ?? 0;

    // Total Transactions (All Statuses)
    $stmt = $pdo->prepare("SELECT COUNT(*) as cnt FROM transactions t JOIN videos v ON t.video_id = v.id WHERE v.user_id = ?");
    $stmt->execute([$user_id]);
    $total_all_transactions = $stmt->fetch()['cnt'] ?? 0;

} catch (PDOException $e) {
    // Fallback variables are already set
}

$pageTitle = "Revenue Statistics - SonicPesa";
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        
        <div class="dashboard-main-body">
            <style>
                .sophisticated-card {
                    background: white;
                    border: 1px solid rgba(0,0,0,0.05);
                    box-shadow: 0 4px 15px rgba(0,0,0,0.03);
                    transition: all 0.3s ease;
                }
                .sophisticated-card:hover { transform: translateY(-4px); box-shadow: 0 12px 25px rgba(0,0,0,0.06); }
                .chart-container { height: 350px; position: relative; }
                .glass-header { 
                    background: rgba(255,255,255,0.7); 
                    backdrop-filter: blur(8px); 
                    border-bottom: 1px solid rgba(0,0,0,0.05);
                }
                .day-badge {
                    display: inline-flex;
                    align-items: center;
                    justify-content: center;
                    padding: 4px 12px;
                    border-radius: 20px;
                    font-size: 0.75rem;
                    font-weight: 600;
                    text-transform: uppercase;
                }
                .day-badge.weekend { background: #fee2e2; color: #ef4444; }
                .day-badge.weekday { background: #e0e7ff; color: #6366f1; }
            </style>

            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <div>
                    <h4 class="fw-bold mb-0"><iconify-icon icon="solar:chart-square-bold-duotone" class="me-8 text-primary-600"></iconify-icon> Revenue Analytics</h4>
                    <nav aria-label="breadcrumb">
                        <ol class="breadcrumb mb-0 text-sm mt-4">
                            <li class="breadcrumb-item"><a href="<?= SITE_URL ?>/dashboard" class="text-secondary-light">Dashboard</a></li>
                            <li class="breadcrumb-item active text-primary-600">Revenue Analytics</li>
                        </ol>
                    </nav>
                </div>
                <div class="d-flex align-items-center gap-12">
                    <button class="btn btn-outline-base bg-white radius-8 d-flex align-items-center gap-8 text-sm" onclick="window.print()">
                        <iconify-icon icon="solar:printer-broken"></iconify-icon> Print Report
                    </button>
                    <button class="btn btn-primary radius-8 d-flex align-items-center gap-8 text-sm">
                        <iconify-icon icon="solar:download-broken"></iconify-icon> Export CSV
                    </button>
                </div>
            </div>

            <!-- Metric Summaries -->
            <div class="row gy-4 mb-24">
                <div class="col-xxl-3 col-sm-6">
                    <div class="card p-12 radius-8 border-0" style="background: #D9F7EF; color: #111;">
                        <div class="d-flex align-items-center gap-16">
                            <div class="w-50-px h-50-px radius-8 d-flex justify-content-center align-items-center bg-white shadow-sm">
                                <iconify-icon icon="solar:wad-of-money-bold-duotone" class="text-2xl text-success-main"></iconify-icon>
                            </div>
                            <div>
                                <span class="text-secondary fw-semibold text-xs text-uppercase">Net Revenue</span>
                                <h5 class="text-dark fw-bold mb-0">TSH <?= number_format($total_period_revenue, 2) ?></h5>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-sm-6">
                    <div class="card p-12 radius-8 border-0" style="background: #e0e7ff; color: #111;">
                        <div class="d-flex align-items-center gap-16">
                            <div class="w-50-px h-50-px radius-8 d-flex justify-content-center align-items-center bg-white shadow-sm">
                                <iconify-icon icon="solar:check-circle-bold-duotone" class="text-2xl text-primary-main"></iconify-icon>
                            </div>
                            <div>
                                <span class="text-secondary fw-semibold text-xs text-uppercase">Completed</span>
                                <h5 class="text-dark fw-bold mb-0"><?= number_format($total_period_transactions) ?> Trans</h5>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-sm-6">
                    <div class="card p-12 radius-8 border-0" style="background: #fef3c7; color: #111;">
                        <div class="d-flex align-items-center gap-16">
                            <div class="w-50-px h-50-px radius-8 d-flex justify-content-center align-items-center bg-white shadow-sm">
                                <iconify-icon icon="solar:clock-circle-bold-duotone" class="text-2xl text-warning-main"></iconify-icon>
                            </div>
                            <div>
                                <span class="text-secondary fw-semibold text-xs text-uppercase">Pending Volume</span>
                                <h5 class="text-dark fw-bold mb-0">TSH <?= number_format($total_pending_amount, 2) ?></h5>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xxl-3 col-sm-6">
                    <div class="card p-12 radius-8 border-0" style="background: #fee2e2; color: #111;">
                        <div class="d-flex align-items-center gap-16">
                            <div class="w-50-px h-50-px radius-8 d-flex justify-content-center align-items-center bg-white shadow-sm">
                                <iconify-icon icon="solar:reorder-bold-duotone" class="text-2xl text-danger-main"></iconify-icon>
                            </div>
                            <div>
                                <span class="text-secondary fw-semibold text-xs text-uppercase">Total Volume</span>
                                <h5 class="text-dark fw-bold mb-0"><?= number_format($total_all_transactions) ?> Trans</h5>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="row gy-4">
                <!-- Revenue Trend -->
                <div class="col-xxl-8">
                    <div class="card radius-16 border-0 sophisticated-card h-100">
                        <div class="card-header border-bottom py-16 px-24 d-flex align-items-center justify-content-between">
                            <h6 class="mb-0 fw-bold">Revenue Trend</h6>
                            <div class="dropdown">
                                <button class="btn btn-sm text-secondary-light" type="button" data-bs-toggle="dropdown">
                                    <iconify-icon icon="solar:menu-dots-bold"></iconify-icon>
                                </button>
                                <ul class="dropdown-menu">
                                    <li><a class="dropdown-item" href="#">View Large</a></li>
                                    <li><a class="dropdown-item" href="#">Refresh Data</a></li>
                                </ul>
                            </div>
                        </div>
                        <div class="card-body p-24">
                            <div class="chart-container">
                                <canvas id="revenueChart"></canvas>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Account Info -->
                <div class="col-xxl-4">
                    <div class="card radius-16 border-0 sophisticated-card h-100">
                        <div class="card-header border-bottom py-16 px-24">
                            <h6 class="mb-0 fw-bold">Account Profile</h6>
                        </div>
                        <div class="card-body p-24">
                            <div class="d-flex flex-column gap-20">
                                <div class="d-flex align-items-center gap-16">
                                    <div class="w-48-px h-48-px radius-12 bg-primary-100 text-primary-600 d-flex justify-content-center align-items-center text-xl">
                                        <iconify-icon icon="solar:user-circle-bold-duotone"></iconify-icon>
                                    </div>
                                    <div>
                                        <span class="text-xs text-secondary-light d-block text-uppercase fw-bold">Display Name</span>
                                        <span class="fw-bold text-dark"><?= htmlspecialchars($user_data['name']) ?></span>
                                    </div>
                                </div>
                                <div class="d-flex align-items-center gap-16">
                                    <div class="w-48-px h-48-px radius-12 bg-success-100 text-success-600 d-flex justify-content-center align-items-center text-xl">
                                        <iconify-icon icon="solar:letter-bold-duotone"></iconify-icon>
                                    </div>
                                    <div>
                                        <span class="text-xs text-secondary-light d-block text-uppercase fw-bold">Account Email</span>
                                        <span class="fw-bold text-dark"><?= htmlspecialchars($user_data['email'] ?: 'N/A') ?></span>
                                    </div>
                                </div>
                                <div class="d-flex align-items-center gap-16">
                                    <div class="w-48-px h-48-px radius-12 bg-warning-100 text-warning-600 d-flex justify-content-center align-items-center text-xl">
                                        <iconify-icon icon="solar:calendar-date-bold-duotone"></iconify-icon>
                                    </div>
                                    <div>
                                        <span class="text-xs text-secondary-light d-block text-uppercase fw-bold">Report Generated</span>
                                        <span class="fw-bold text-dark"><?= date('M d, Y H:i') ?></span>
                                    </div>
                                </div>
                                <hr class="my-8 opacity-50">
                                <div class="bg-base p-16 radius-12">
                                    <p class="text-xs text-secondary-light mb-0">Note: Revenue shown is based on successful transactions only. Pending or failed attempts are not included in these analytics.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Detailed Breakdown -->
                <div class="col-12">
                    <div class="card radius-16 border-0 sophisticated-card">
                        <div class="card-header border-bottom py-16 px-24 d-flex align-items-center justify-content-between flex-wrap gap-12">
                            <h6 class="mb-0 fw-bold">Daily Revenue Breakdown</h6>
                            <div class="input-group w-auto">
                                <span class="input-group-text bg-base border-0"><iconify-icon icon="solar:magnifer-broken"></iconify-icon></span>
                                <input type="text" id="tableSearch" class="form-control bg-base border-0 text-sm" placeholder="Search dates..." style="min-width: 250px;">
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div class="table-responsive">
                                <table class="table table-hover mb-0" id="statsTable">
                                    <thead class="bg-base">
                                        <tr>
                                            <th class="ps-24 py-16 text-xs text-uppercase fw-bold text-secondary-light">Date</th>
                                            <th class="py-16 text-xs text-uppercase fw-bold text-secondary-light">Day</th>
                                            <th class="py-16 text-xs text-uppercase fw-bold text-secondary-light">Transactions</th>
                                            <th class="py-16 text-xs text-uppercase fw-bold text-secondary-light">Revenue (TZS)</th>
                                            <th class="pe-24 py-16 text-end text-xs text-uppercase fw-bold text-secondary-light">Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php if(!empty($daily_stats)): ?>
                                            <?php foreach($daily_stats as $day): 
                                                $d = new DateTime($day['date']);
                                                $isWeekend = in_array($d->format('N'), [6, 7]);
                                            ?>
                                            <tr>
                                                <td class="ps-24 py-16 fw-bold text-dark"><?= $d->format('M d, Y') ?></td>
                                                <td class="py-16">
                                                    <span class="day-badge <?= $isWeekend ? 'weekend' : 'weekday' ?>">
                                                        <?= $d->format('D') ?>
                                                    </span>
                                                </td>
                                                <td class="py-16 text-secondary-light"><?= $day['transactions'] ?> orders</td>
                                                <td class="py-16 fw-bold text-dark"><?= number_format($day['revenue'], 2) ?></td>
                                                <td class="pe-24 py-16 text-end">
                                                    <span class="badge bg-success-focus text-success-main radius-4">Verified</span>
                                                </td>
                                            </tr>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <tr>
                                                <td colspan="5" class="py-48 text-center text-secondary-light">No revenue data discovered for your account yet.</td>
                                            </tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <?php include 'includes/footer.php'; ?>
    </main>

    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Chart Data Prep
            const rawData = <?= json_encode($daily_stats) ?>;
            const labels = rawData.map(d => {
                const dt = new DateTime(d.date);
                return dt.format('d M');
            }).reverse();
            const revData = rawData.map(d => d.revenue).reverse();

            const ctx = document.getElementById('revenueChart').getContext('2d');
            const gradient = ctx.createLinearGradient(0, 0, 0, 300);
            gradient.addColorStop(0, 'rgba(99, 102, 241, 0.2)');
            gradient.addColorStop(1, 'rgba(99, 102, 241, 0)');

            new Chart(ctx, {
                type: 'line',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'Revenue (TZS)',
                        data: revData,
                        borderColor: '#6366f1',
                        backgroundColor: gradient,
                        borderWidth: 3,
                        tension: 0.4,
                        fill: true,
                        pointBackgroundColor: '#ffffff',
                        pointBorderColor: '#6366f1',
                        pointBorderWidth: 2,
                        pointRadius: 4,
                        pointHoverRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            backgroundColor: '#1e293b',
                            padding: 12,
                            titleFont: { size: 14, weight: 'bold' },
                            callbacks: {
                                label: (ctx) => ' TSH ' + new Intl.NumberFormat().format(ctx.parsed.y)
                            }
                        }
                    },
                    scales: {
                        x: { grid: { display: false }, ticks: { color: '#94a3b8' } },
                        y: { 
                            beginAtZero: true, 
                            grid: { color: 'rgba(0,0,0,0.03)' },
                            ticks: { 
                                color: '#94a3b8',
                                callback: (v) => 'TSH ' + v.toLocaleString()
                            }
                        }
                    }
                }
            });

            // Search Filter
            document.getElementById('tableSearch').addEventListener('keyup', function() {
                const val = this.value.toLowerCase();
                const rows = document.querySelectorAll('#statsTable tbody tr');
                rows.forEach(row => {
                    const text = row.textContent.toLowerCase();
                    row.style.display = text.includes(val) ? '' : 'none';
                });
            });
        });

        // Simple mock DateTime for the chart labels
        class DateTime {
            constructor(str) { this.date = new Date(str); }
            format(fmt) {
                const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                if(fmt === 'd M') return this.date.getDate() + ' ' + months[this.date.getMonth()];
                return this.date.toDateString();
            }
        }
    </script>
</body>
</html>


