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

$user_id = $_SESSION['user_id'];
$site_settings = get_site_settings($pdo);
$system_comm = $site_settings['system_commission'] ?? 0;

// Pagination settings
$limit = 7;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// View filter (daily, weekly, monthly, yearly)
$view = isset($_GET['view']) ? $_GET['view'] : 'daily';
$allowed_views = ['daily', 'weekly', 'monthly', 'yearly'];
if (!in_array($view, $allowed_views)) $view = 'daily';

try {
    // 1. Calculate Summary Totals
    // Today's Total
    $stmt = $pdo->prepare("
        SELECT SUM(t.amount) as gross 
        FROM transactions t 
        JOIN videos v ON t.video_id = v.id 
        WHERE v.user_id = ? AND t.status = 'completed' 
        AND DATE(t.created_at) = CURDATE()
    ");
    $stmt->execute([$user_id]);
    $today_gross = $stmt->fetchColumn() ?: 0;
    $today_net = $today_gross * (1 - ($system_comm / 100));

    // Weekly Total
    $stmt = $pdo->prepare("
        SELECT SUM(t.amount) as gross 
        FROM transactions t 
        JOIN videos v ON t.video_id = v.id 
        WHERE v.user_id = ? AND t.status = 'completed' 
        AND YEARWEEK(t.created_at, 1) = YEARWEEK(CURDATE(), 1)
    ");
    $stmt->execute([$user_id]);
    $weekly_gross = $stmt->fetchColumn() ?: 0;
    $weekly_net = $weekly_gross * (1 - ($system_comm / 100));

    // Monthly Total
    $stmt = $pdo->prepare("
        SELECT SUM(t.amount) as gross 
        FROM transactions t 
        JOIN videos v ON t.video_id = v.id 
        WHERE v.user_id = ? AND t.status = 'completed' 
        AND MONTH(t.created_at) = MONTH(CURDATE()) AND YEAR(t.created_at) = YEAR(CURDATE())
    ");
    $stmt->execute([$user_id]);
    $monthly_gross = $stmt->fetchColumn() ?: 0;
    $monthly_net = $monthly_gross * (1 - ($system_comm / 100));

    // Yearly Total
    $stmt = $pdo->prepare("
        SELECT SUM(t.amount) as gross 
        FROM transactions t 
        JOIN videos v ON t.video_id = v.id 
        WHERE v.user_id = ? AND t.status = 'completed' 
        AND YEAR(t.created_at) = YEAR(CURDATE())
    ");
    $stmt->execute([$user_id]);
    $yearly_gross = $stmt->fetchColumn() ?: 0;
    $yearly_net = $yearly_gross * (1 - ($system_comm / 100));

    // 2. Fetch Earnings Data for Table
    $select_clause = "";
    $group_clause = "";
    $order_clause = "";

    switch ($view) {
        case 'weekly':
            $select_clause = "CONCAT('Week ', WEEK(t.created_at, 1), ', ', YEAR(t.created_at)) as period, COUNT(*) as conversions, SUM(t.amount) as gross";
            $group_clause = "YEARWEEK(t.created_at, 1)";
            $order_clause = "YEARWEEK(t.created_at, 1) DESC";
            break;
        case 'monthly':
            $select_clause = "DATE_FORMAT(t.created_at, '%M %Y') as period, COUNT(*) as conversions, SUM(t.amount) as gross";
            $group_clause = "YEAR(t.created_at), MONTH(t.created_at)";
            $order_clause = "YEAR(t.created_at) DESC, MONTH(t.created_at) DESC";
            break;
        case 'yearly':
            $select_clause = "YEAR(t.created_at) as period, COUNT(*) as conversions, SUM(t.amount) as gross";
            $group_clause = "YEAR(t.created_at)";
            $order_clause = "YEAR(t.created_at) DESC";
            break;
        case 'daily':
        default:
            $select_clause = "DATE(t.created_at) as period, COUNT(*) as conversions, SUM(t.amount) as gross";
            $group_clause = "DATE(t.created_at)";
            $order_clause = "DATE(t.created_at) DESC";
            break;
    }

    // Count total rows for pagination
    $stmt = $pdo->prepare("
        SELECT COUNT(DISTINCT $group_clause) 
        FROM transactions t 
        JOIN videos v ON t.video_id = v.id 
        WHERE v.user_id = ? AND t.status = 'completed'
    ");
    $stmt->execute([$user_id]);
    $total_records = $stmt->fetchColumn();
    $total_pages = ceil($total_records / $limit);

    // Fetch actual data
    $stmt = $pdo->prepare("
        SELECT $select_clause 
        FROM transactions t 
        JOIN videos v ON t.video_id = v.id 
        WHERE v.user_id = ? AND t.status = 'completed' 
        GROUP BY $group_clause 
        ORDER BY $order_clause 
        LIMIT ? OFFSET ?
    ");
    $stmt->bindValue(1, $user_id, PDO::PARAM_INT);
    $stmt->bindValue(2, $limit, PDO::PARAM_INT);
    $stmt->bindValue(3, $offset, PDO::PARAM_INT);
    $stmt->execute();
    $earnings_data = $stmt->fetchAll();

} catch (PDOException $e) { $error = "Failed to load earnings data."; }

$pageTitle = "My Earnings - SonicPesa";
?>
<!DOCTYPE html>
<html lang="en" data-theme="dark">
<?php include 'includes/head.php'; ?>
<style>
    .earnings-card {
        border: none; border-radius: 20px;
        transition: transform 0.3s ease;
        background: white; border: 1px solid rgba(0,0,0,0.05);
    }
    .earnings-card:hover { transform: translateY(-5px); }
    .period-badge { font-weight: 700; font-size: 0.75rem; text-transform: uppercase; }
    .pagination .page-link { border-radius: 8px; margin: 0 4px; border: none; background: #f8fafc; color: #64748b; font-weight: 600; }
    .pagination .page-item.active .page-link { background: var(--primary-600); color: white; }
</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-32">
                <div>
                    <h4 class="fw-bold mb-4">Earnings History</h4>
                    <p class="text-secondary-light text-sm mb-0">Track your financial growth across different time periods.</p>
                </div>
                <div class="dropdown">
                    <button class="btn btn-outline-primary dropdown-toggle radius-12 px-24 py-12 fw-bold d-flex align-items-center gap-2" type="button" data-bs-toggle="dropdown">
                        <iconify-icon icon="solar:calendar-bold-duotone" class="text-xl"></iconify-icon>
                        View: <?= ucfirst($view) ?>
                    </button>
                    <ul class="dropdown-menu radius-12 border-0 shadow-sm">
                        <li><a class="dropdown-item py-10" href="?view=daily">Daily Breakdown</a></li>
                        <li><a class="dropdown-item py-10" href="?view=weekly">Weekly Summary</a></li>
                        <li><a class="dropdown-item py-10" href="?view=monthly">Monthly Summary</a></li>
                        <li><a class="dropdown-item py-10" href="?view=yearly">Yearly Summary</a></li>
                    </ul>
                </div>
            </div>

            <!-- Summary Totals -->
            <div class="row g-4 mb-32">
                <div class="col-xl-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:calendar-bold-duotone" class="text-2xl text-success-main"></iconify-icon>
                            </div>
                            <div>
                                <span class="text-secondary fw-semibold text-xs text-uppercase">This Day (Net)</span>
                                <h5 class="text-dark fw-bold mb-0">TSH <?= number_format($today_net, 2) ?></h5>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xl-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:chart-2-bold-duotone" class="text-2xl text-primary-main"></iconify-icon>
                            </div>
                            <div>
                                <span class="text-secondary fw-semibold text-xs text-uppercase">This Week (Net)</span>
                                <h5 class="text-dark fw-bold mb-0">TSH <?= number_format($weekly_net, 2) ?></h5>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xl-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:calendar-date-bold-duotone" class="text-2xl text-warning-main"></iconify-icon>
                            </div>
                            <div>
                                <span class="text-secondary fw-semibold text-xs text-uppercase">This Month (Net)</span>
                                <h5 class="text-dark fw-bold mb-0">TSH <?= number_format($monthly_net, 2) ?></h5>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-xl-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:bill-list-bold-duotone" class="text-2xl text-danger-main"></iconify-icon>
                            </div>
                            <div>
                                <span class="text-secondary fw-semibold text-xs text-uppercase">Yearly Total (Net)</span>
                                <h5 class="text-dark fw-bold mb-0">TSH <?= number_format($yearly_net, 2) ?></h5>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Detailed Table -->
            <div class="card radius-24 border-0 shadow-sm overflow-hidden">
                <div class="card-header bg-white border-bottom py-20 px-32 d-flex align-items-center justify-content-between">
                    <h6 class="fw-bold mb-0"><?= ucfirst($view) ?> Revenue Report</h6>
                    <span class="badge bg-primary-100 text-primary-600 radius-8 px-12 py-6 fw-bold">Net after <?= $system_comm ?>% Fee</span>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="bg-light">
                                <tr>
                                    <th class="ps-32 py-16 text-xs text-uppercase fw-bold text-secondary-light">Period</th>
                                    <th class="py-16 text-xs text-uppercase fw-bold text-secondary-light">Conversions</th>
                                    <th class="py-16 text-xs text-uppercase fw-bold text-secondary-light">Gross Total</th>
                                    <th class="py-16 text-xs text-uppercase fw-bold text-secondary-light">Net Earnings (TZS)</th>
                                    <th class="pe-32 py-16 text-end text-xs text-uppercase fw-bold text-secondary-light">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(!empty($earnings_data)): ?>
                                    <?php foreach($earnings_data as $row): 
                                        $net = $row['gross'] * (1 - ($system_comm / 100));
                                        $display_period = $row['period'];
                                        if ($view == 'daily') {
                                            $display_period = date('M d, Y', strtotime($row['period']));
                                        }
                                    ?>
                                    <tr>
                                        <td class="ps-32 py-16 fw-bold text-dark"><?= $display_period ?></td>
                                        <td class="py-16"><span class="badge bg-light text-dark radius-4 px-10"><?= $row['conversions'] ?> Conversions</span></td>
                                        <td class="py-16 text-secondary-light">TZS <?= number_format($row['gross'], 2) ?></td>
                                        <td class="py-16 fw-extrabold text-primary-600">TZS <?= number_format($net, 2) ?></td>
                                        <td class="pe-32 py-16 text-end">
                                            <span class="badge bg-success-focus text-success-main radius-circle p-4 d-inline-flex align-items-center gap-1 px-12">
                                                <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Verified
                                            </span>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="5" class="py-64 text-center">
                                            <div class="d-flex flex-column align-items-center gap-2">
                                                <iconify-icon icon="solar:folder-error-bold-duotone" class="text-5xl text-secondary-light opacity-25"></iconify-icon>
                                                <span class="text-secondary-light fw-medium">No records found for this view.</span>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <?php if($total_pages > 1): ?>
                <div class="card-footer bg-white border-top py-20 px-32">
                    <nav>
                        <ul class="pagination justify-content-center mb-0">
                            <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                                <a class="page-link py-8 px-16" href="?view=<?= $view ?>&page=<?= $page - 1 ?>">Previous</a>
                            </li>
                            <?php for($i = 1; $i <= $total_pages; $i++): ?>
                                <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                                    <a class="page-link py-8 px-16" href="?view=<?= $view ?>&page=<?= $i ?>"><?= $i ?></a>
                                </li>
                            <?php endfor; ?>
                            <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                                <a class="page-link py-8 px-16" href="?view=<?= $view ?>&page=<?= $page + 1 ?>">Next</a>
                            </li>
                        </ul>
                    </nav>
                </div>
                <?php endif; ?>
            </div>
        </div>
        
        <?php include 'includes/footer.php'; ?>
    </main>
</body>
</html>


