<?php
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../engine/Logger.php'; // COVERAGE
$ctx = Kernel::handle(['auth' => true]);
$u   = $ctx['user'];
if (!$u['provider_verified']) Kernel::fail('not_provider', '', 403);

$period = $_GET['period'] ?? 'month'; // week|month|all

$where = 'pe.provider_id = ?';
$params = [$u['id']];
if ($period === 'week')  { $where .= ' AND pe.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)'; }
if ($period === 'month') { $where .= ' AND pe.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)'; }

$st = db()->prepare("
    SELECT pe.*, b.booking_date, b.booking_time, u.name AS client_name
    FROM provider_earnings pe
    JOIN bookings b ON b.id = pe.booking_id
    JOIN users u ON u.id = b.user_id
    WHERE {$where}
    ORDER BY pe.created_at DESC LIMIT 50
");
$st->execute($params);
$earnings = $st->fetchAll();

$sum = db()->prepare("SELECT SUM(net_sdg) AS total, SUM(commission_sdg) AS commission, COUNT(*) AS count FROM provider_earnings WHERE provider_id=? AND status IN ('pending','cleared','paid')");
$sum->execute([$u['id']]);
$totals = $sum->fetch();

$pending = db()->prepare("SELECT SUM(net_sdg) FROM provider_earnings WHERE provider_id=? AND status='pending'");
$pending->execute([$u['id']]);
$pendingAmt = (float)$pending->fetchColumn();

json_response([
    'success'      => true,
    'earnings'     => $earnings,
    'summary'      => [
        'total_net'     => (float)($totals['total'] ?? 0),
        'total_count'   => (int)($totals['count'] ?? 0),
        'commission'    => (float)($totals['commission'] ?? 0),
        'pending'       => $pendingAmt,
    ],
    'period' => $period,
]);
