<?php
/* ============================================================================
   WBMCZ — Earning Report renderer

   One implementation, used by both panels:
     - earning_report.php         (customer / member panel)
     - seller/earning_report.php  (seller panel)

   Data comes from includes/wallet.php (the `wallet_ledger` table).
   ============================================================================ */

require_once __DIR__ . '/wallet.php';

if (!function_exists('earning_handle_export')) {

/**
 * Streams the CSV and exits. Call BEFORE any HTML is output.
 */
function earning_handle_export($db, $user_id) {
    if (!isset($_GET['export'])) return;

    $from = preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['from'] ?? '') ? $_GET['from'] : '';
    $to   = preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['to'] ?? '')   ? $_GET['to']   : '';
    $cat  = trim($_GET['c'] ?? '');
    $utype = earning_user_type($db, $user_id);
    $rows = earning_rows($db, $user_id, $from, $to, $cat, 5000, $utype);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="earning_report_' . date('Ymd_His') . '.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Date', 'Time', 'Source', 'Wallet', 'Amount', 'Description', 'Reference']);
    foreach ($rows as $r) {
        $wl = $r['wallet'] === 'virtual' ? 'Virtual' : ($r['wallet'] === 'report' ? 'Report only' : 'Main');
        fputcsv($out, [
            date('Y-m-d', strtotime($r['created_at'])),
            date('H:i:s', strtotime($r['created_at'])),
            wallet_cat_label(wallet_category_alias($r['category'])),
            $wl,
            number_format((float)$r['amount'], 2, '.', ''),
            $r['description'],
            trim(($r['reference_type'] ?? '') . ' ' . ($r['reference_id'] ?? '')),
        ]);
    }
    fclose($out);
    exit;
}

/**
 * Returns everything the page needs, already filtered.
 */
/* The logged-in user's role — decides which sources are offered */
function earning_user_type($db, $user_id) {
    static $cache = [];
    $k = (int)$user_id;
    if (isset($cache[$k])) return $cache[$k];
    $t = 'customer';
    try {
        $r = $db->select("SELECT user_type FROM users WHERE id = ?", [$k]);
        if (!empty($r)) $t = (string)$r[0]['user_type'];
    } catch (\Throwable $e) {}
    return $cache[$k] = $t;
}

function earning_page_data($db, $user_id) {
    wallet_ensure_schema($db);
    $utype = earning_user_type($db, $user_id);

    $preset = $_GET['p'] ?? '';
    $from   = preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['from'] ?? '') ? $_GET['from'] : '';
    $to     = preg_match('/^\d{4}-\d{2}-\d{2}$/', $_GET['to'] ?? '')   ? $_GET['to']   : '';
    $cat    = trim($_GET['c'] ?? '');

    // Quick presets override the manual dates
    if ($preset === 'today')    { $from = date('Y-m-d'); $to = date('Y-m-d'); }
    elseif ($preset === '7')    { $from = date('Y-m-d', strtotime('-6 days')); $to = date('Y-m-d'); }
    elseif ($preset === '30')   { $from = date('Y-m-d', strtotime('-29 days')); $to = date('Y-m-d'); }
    elseif ($preset === 'month'){ $from = date('Y-m-01'); $to = date('Y-m-d'); }

    $rows = earning_rows($db, $user_id, $from, $to, $cat, 1000, $utype);

    // Discount rows are report-only, so they never enter the money total
    $range_total = 0.0; $range_discount = 0.0;
    foreach ($rows as $r) {
        if (wallet_is_report_only(wallet_category_alias($r['category']))) { $range_discount += (float)$r['amount']; }
        else { $range_total += (float)$r['amount']; }
    }

    return [
        'preset'         => $preset,
        'from'           => $from,
        'to'             => $to,
        'cat'            => $cat,
        'user_type'      => $utype,
        'totals'         => earning_totals($db, $user_id, $utype),
        'sources'        => earning_by_source($db, $user_id, $from, $to, $utype),
        'monthly'        => earning_monthly($db, $user_id, 12, $utype),
        'rows'           => $rows,
        'range_total'    => round($range_total, 2),
        'range_discount' => round($range_discount, 2),
        'balances'       => wallet_balances($db, $user_id),
    ];
}

/**
 * Renders the whole report body.
 * $opts = ['self' => 'earning_report.php', 'accent' => 'indigo'|'teal']
 */
function earning_render($d, $opts = []) {
    $self   = $opts['self'] ?? 'earning_report.php';
    $accent = $opts['accent'] ?? 'indigo';

    $qs = function ($extra = []) use ($d, $self) {
        $p = array_filter([
            'p' => $d['preset'], 'from' => $d['from'], 'to' => $d['to'], 'c' => $d['cat'],
        ], function ($v) { return $v !== '' && $v !== null; });
        return $self . '?' . http_build_query(array_merge($p, $extra));
    };

    $max = 0.0;
    foreach ($d['monthly'] as $m) { if ($m['total'] > $max) $max = $m['total']; }

    ob_start(); ?>

<style>
    .er-k { font-size:10px; font-weight:800; text-transform:uppercase; letter-spacing:.07em; color:#94a3b8; margin-bottom:.25rem; }
    .er-l { display:block; font-size:10px; font-weight:700; color:#64748b; margin-bottom:.2rem; text-transform:uppercase; letter-spacing:.04em; }
    .er-f { width:100%; padding:.6rem .7rem; background:#fff; border:1px solid #cbd5e1; border-radius:.75rem; font-size:.75rem; outline:none; }
    .er-f:focus { box-shadow:0 0 0 2px rgba(99,102,241,.35); border-color:#6366f1; }
    .er-chip { padding:.45rem .9rem; border-radius:999px; font-size:.7rem; font-weight:800; border:1px solid #e2e8f0; background:#fff; color:#64748b; transition:all .15s; }
    .er-chip:hover { background:#f8fafc; }
    .er-chip.on { background:#0f172a; color:#fff; border-color:#0f172a; }
    .er-bar { transition:height .5s cubic-bezier(.4,0,.2,1); }
</style>

<!-- ===== HEADLINE CARDS ===== -->
<div class="grid grid-cols-2 lg:grid-cols-5 gap-3 mb-5">
    <div class="rounded-2xl p-4 text-white shadow-lg" style="background:linear-gradient(135deg,#0f172a,#1e293b);">
        <p class="er-k text-white/50">Total Earned</p>
        <p class="text-2xl font-black">₹<?php echo number_format($d['totals']['all_time'], 2); ?></p>
        <p class="text-[10px] text-white/40 mt-0.5">All time</p>
    </div>
    <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4">
        <p class="er-k">This Month</p>
        <p class="text-2xl font-black text-emerald-600">₹<?php echo number_format($d['totals']['month'], 2); ?></p>
        <p class="text-[10px] text-slate-400 mt-0.5"><?php echo date('F Y'); ?></p>
    </div>
    <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4">
        <p class="er-k">Last 7 Days</p>
        <p class="text-2xl font-black text-blue-600">₹<?php echo number_format($d['totals']['week'], 2); ?></p>
        <p class="text-[10px] text-slate-400 mt-0.5">Rolling week</p>
    </div>
    <div class="bg-white rounded-2xl border border-amber-200 shadow-sm p-4">
        <p class="er-k text-amber-500">Today</p>
        <p class="text-2xl font-black text-amber-600">₹<?php echo number_format($d['totals']['today'], 2); ?></p>
        <p class="text-[10px] text-amber-400 mt-0.5"><?php echo date('d M Y'); ?></p>
    </div>
    <div class="bg-emerald-50 rounded-2xl border border-emerald-200 shadow-sm p-4 col-span-2 lg:col-span-1">
        <p class="er-k text-emerald-500"><i class="fas fa-tags mr-1"></i>My Discount Saved</p>
        <p class="text-2xl font-black text-emerald-600">₹<?php echo number_format($d['totals']['discount'] ?? 0, 2); ?></p>
        <p class="text-[10px] text-emerald-500 mt-0.5">Report only — not added to earnings</p>
    </div>
</div>

<!-- ===== WALLET SPLIT ===== -->
<div class="grid sm:grid-cols-2 gap-3 mb-5">
    <div class="bg-white rounded-2xl border-2 border-slate-200 p-4 flex items-center gap-4">
        <div class="w-12 h-12 rounded-2xl bg-slate-100 flex items-center justify-center text-slate-500 text-lg flex-shrink-0"><i class="fas fa-wallet"></i></div>
        <div class="min-w-0">
            <p class="er-k">Main Wallet</p>
            <p class="text-xl font-black text-slate-800">₹<?php echo number_format($d['balances']['main'], 2); ?></p>
            <p class="text-[10px] text-slate-400">Withdrawable · deposits &amp; seller income</p>
        </div>
    </div>
    <div class="bg-amber-50 rounded-2xl border-2 border-amber-200 p-4 flex items-center gap-4">
        <div class="w-12 h-12 rounded-2xl bg-amber-100 flex items-center justify-center text-amber-600 text-lg flex-shrink-0"><i class="fas fa-gift"></i></div>
        <div class="min-w-0">
            <p class="er-k text-amber-500">Virtual Wallet</p>
            <p class="text-xl font-black text-amber-600">₹<?php echo number_format($d['balances']['virtual'], 2); ?></p>
            <p class="text-[10px] text-amber-500">Referral earnings · spend on purchases, not withdrawable</p>
        </div>
    </div>
</div>

<!-- ===== CHART ===== -->
<div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-5 mb-5">
    <div class="flex items-center justify-between mb-5">
        <div>
            <p class="text-sm font-bold text-slate-800"><i class="fas fa-chart-column mr-2 text-indigo-500"></i>Last 12 months</p>
            <p class="text-[11px] text-slate-400">Earnings credited each month</p>
        </div>
        <p class="text-xs font-black text-slate-700">Peak ₹<?php echo number_format($max, 2); ?></p>
    </div>
    <div class="flex items-end gap-1.5 sm:gap-2.5 h-44">
        <?php foreach ($d['monthly'] as $m):
            $h = $max > 0 ? max(3, round(($m['total'] / $max) * 100)) : 3;
        ?>
        <div class="flex-1 flex flex-col items-center justify-end h-full group relative">
            <div class="absolute -top-1 opacity-0 group-hover:opacity-100 transition-opacity bg-slate-900 text-white text-[10px] font-bold px-2 py-1 rounded-md whitespace-nowrap z-10 pointer-events-none">
                ₹<?php echo number_format($m['total'], 2); ?>
            </div>
            <div class="w-full rounded-t-lg er-bar <?php echo $m['total'] > 0 ? 'bg-gradient-to-t from-indigo-600 to-indigo-400' : 'bg-slate-100'; ?>"
                 style="height:<?php echo $h; ?>%"></div>
            <span class="text-[8px] sm:text-[9px] font-bold text-slate-400 mt-1.5 whitespace-nowrap"><?php echo htmlspecialchars($m['label']); ?></span>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- ===== SOURCE BREAKDOWN ===== -->
<div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-5 mb-5">
    <p class="text-sm font-bold text-slate-800 mb-4"><i class="fas fa-layer-group mr-2 text-indigo-500"></i>Where your money came from</p>
    <?php
        // Real money sources drive the bar; the discount is shown separately
        $money_src = []; $report_src = []; $src_total = 0.0; $report_total = 0.0;
        foreach ($d['sources'] as $k => $v) {
            if (!empty($v['report_only'])) { $report_src[$k] = $v; $report_total += $v['total']; }
            else { $money_src[$k] = $v; $src_total += $v['total']; }
        }
        $nothing_yet = ($src_total <= 0 && $report_total <= 0);
    ?>
    <?php if ($nothing_yet): ?>
        <p class="text-xs text-slate-400 py-6 text-center">No earnings recorded in this period yet.</p>
    <?php else: ?>
        <?php if ($src_total > 0): ?>
        <div class="flex h-3 rounded-full overflow-hidden mb-4 bg-slate-100">
            <?php foreach ($money_src as $k => $v):
                    if ($v['total'] <= 0) continue;
                    $w = round(($v['total'] / $src_total) * 100, 2);
            ?>
                <div style="width:<?php echo $w; ?>%; background:<?php echo wallet_cat_hex($k); ?>;" title="<?php echo wallet_cat_label($k); ?>"></div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <div class="grid grid-cols-2 lg:grid-cols-3 gap-2">
            <?php foreach ($money_src as $k => $v):
                $pct = $src_total > 0 ? round(($v['total'] / $src_total) * 100) : 0;
            ?>
            <div class="rounded-xl border border-slate-200 p-3">
                <p class="text-[10px] font-bold text-slate-400 uppercase leading-tight mb-1">
                    <span class="inline-block w-2 h-2 rounded-full mr-1 align-middle" style="background:<?php echo wallet_cat_hex($k); ?>"></span>
                    <?php echo wallet_cat_label($k); ?>
                </p>
                <p class="text-lg font-black text-slate-800">₹<?php echo number_format($v['total'], 2); ?></p>
                <p class="text-[10px] text-slate-400"><?php echo (int)$v['count']; ?> entries · <?php echo $pct; ?>%</p>
            </div>
            <?php endforeach; ?>
        </div>

        <?php foreach ($report_src as $k => $v): ?>
            <div class="mt-3 rounded-xl border-2 border-dashed border-emerald-200 bg-emerald-50/60 p-3 flex items-center gap-3">
                <div class="w-10 h-10 rounded-xl bg-emerald-100 text-emerald-600 flex items-center justify-center flex-shrink-0"><i class="fas <?php echo wallet_cat_icon($k); ?>"></i></div>
                <div class="min-w-0 flex-1">
                    <p class="text-[10px] font-bold text-emerald-500 uppercase leading-tight"><?php echo wallet_cat_label($k); ?></p>
                    <p class="text-lg font-black text-emerald-700">₹<?php echo number_format($v['total'], 2); ?></p>
                </div>
                <span class="text-[9px] font-black uppercase tracking-wider text-emerald-500 bg-emerald-100 px-2 py-1 rounded-lg flex-shrink-0">Report only</span>
            </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- ===== FILTERS ===== -->
<div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4 mb-4">
    <div class="flex flex-wrap gap-2 mb-3">
        <a href="<?php echo $self; ?>" class="er-chip <?php echo $d['preset']==='' && $d['from']==='' ? 'on' : ''; ?>">All time</a>
        <a href="<?php echo $qs(['p'=>'today','from'=>'','to'=>'']); ?>" class="er-chip <?php echo $d['preset']==='today'?'on':''; ?>">Today</a>
        <a href="<?php echo $qs(['p'=>'7','from'=>'','to'=>'']); ?>" class="er-chip <?php echo $d['preset']==='7'?'on':''; ?>">Last 7 days</a>
        <a href="<?php echo $qs(['p'=>'30','from'=>'','to'=>'']); ?>" class="er-chip <?php echo $d['preset']==='30'?'on':''; ?>">Last 30 days</a>
        <a href="<?php echo $qs(['p'=>'month','from'=>'','to'=>'']); ?>" class="er-chip <?php echo $d['preset']==='month'?'on':''; ?>">This month</a>
    </div>
    <form method="GET" class="grid sm:grid-cols-2 lg:grid-cols-5 gap-2 items-end">
        <div><label class="er-l">Source</label>
            <select name="c" class="er-f">
                <option value="">All sources</option>
                <?php foreach (wallet_earning_categories($d['user_type'] ?? '') as $ck): ?>
                    <option value="<?php echo $ck; ?>" <?php echo $d['cat']===$ck?'selected':''; ?>><?php echo wallet_cat_label($ck); ?><?php echo wallet_is_report_only($ck) ? ' (report only)' : ''; ?></option>
                <?php endforeach; ?>
            </select></div>
        <div><label class="er-l">From</label><input type="date" name="from" value="<?php echo htmlspecialchars($d['from']); ?>" class="er-f"></div>
        <div><label class="er-l">To</label><input type="date" name="to" value="<?php echo htmlspecialchars($d['to']); ?>" class="er-f"></div>
        <div><button class="w-full py-2.5 bg-slate-900 hover:bg-slate-800 text-white rounded-xl text-xs font-bold">Apply filter</button></div>
        <div><a href="<?php echo $qs(['export'=>1]); ?>" class="block text-center w-full py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl text-xs font-bold"><i class="fas fa-file-csv mr-1.5"></i>Export CSV</a></div>
    </form>
</div>

<!-- ===== TRANSACTION LIST ===== -->
<div class="bg-white rounded-2xl border border-gray-200 shadow-sm overflow-hidden">
    <div class="px-5 py-3 border-b border-gray-100 bg-slate-50/60 flex flex-wrap items-center justify-between gap-2">
        <p class="text-sm font-bold text-slate-700"><i class="fas fa-receipt mr-2 text-indigo-500"></i>Earning entries</p>
        <p class="text-[11px] font-bold text-slate-500">
            <?php echo count($d['rows']); ?> row(s) ·
            <span class="text-emerald-600">₹<?php echo number_format($d['range_total'], 2); ?></span> earned
            <?php if (($d['range_discount'] ?? 0) > 0): ?>
                · <span class="text-emerald-500">₹<?php echo number_format($d['range_discount'], 2); ?> saved</span>
            <?php endif; ?>
        </p>
    </div>
    <div class="overflow-x-auto">
        <table class="w-full text-left text-xs">
            <thead>
                <tr class="bg-slate-50 text-[10px] uppercase text-slate-500 tracking-wider">
                    <th class="p-3 pl-5 font-semibold">Date</th>
                    <th class="p-3 font-semibold">Source</th>
                    <th class="p-3 font-semibold">Details</th>
                    <th class="p-3 font-semibold">Wallet</th>
                    <th class="p-3 pr-5 font-semibold text-right">Amount</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
            <?php if (!empty($d['rows'])): foreach ($d['rows'] as $r):
                $cat  = wallet_category_alias($r['category']);
                $ronly= wallet_is_report_only($cat);
                $isv  = ($r['wallet'] === 'virtual');
            ?>
                <tr class="hover:bg-slate-50/60">
                    <td class="p-3 pl-5 whitespace-nowrap">
                        <p class="font-bold text-slate-700"><?php echo date('d M Y', strtotime($r['created_at'])); ?></p>
                        <p class="text-[10px] text-slate-400"><?php echo date('h:i A', strtotime($r['created_at'])); ?></p>
                    </td>
                    <td class="p-3">
                        <span class="text-[10px] font-bold whitespace-nowrap <?php echo $ronly ? 'text-emerald-600' : 'text-slate-600'; ?>">
                            <i class="fas <?php echo wallet_cat_icon($cat); ?> mr-1 <?php echo $ronly ? 'text-emerald-400' : 'text-slate-400'; ?>"></i><?php echo wallet_cat_label($cat); ?>
                        </span>
                    </td>
                    <td class="p-3 text-slate-600 max-w-[340px]">
                        <p class="break-words"><?php echo htmlspecialchars($r['description'] ?: '—'); ?></p>
                        <?php if (!empty($r['reference_type'])): ?>
                            <p class="text-[10px] text-slate-400 mt-0.5"><?php echo htmlspecialchars($r['reference_type']); ?> #<?php echo (int)$r['reference_id']; ?></p>
                        <?php endif; ?>
                    </td>
                    <td class="p-3">
                        <?php if ($ronly): ?>
                            <span class="px-2 py-1 rounded-lg text-[10px] font-bold bg-emerald-100 text-emerald-700">Report only</span>
                        <?php else: ?>
                            <span class="px-2 py-1 rounded-lg text-[10px] font-bold <?php echo $isv ? 'bg-amber-100 text-amber-700' : 'bg-slate-100 text-slate-600'; ?>">
                                <?php echo $isv ? 'Virtual' : 'Main'; ?>
                            </span>
                        <?php endif; ?>
                    </td>
                    <td class="p-3 pr-5 text-right whitespace-nowrap">
                        <span class="font-black text-sm <?php echo $ronly ? 'text-emerald-500' : 'text-emerald-600'; ?>">
                            <?php echo $ronly ? '' : '+'; ?>₹<?php echo number_format((float)$r['amount'], 2); ?>
                        </span>
                        <?php if ($ronly): ?><p class="text-[9px] text-emerald-400 font-bold">saved</p><?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; else: ?>
                <tr><td colspan="5" class="p-14 text-center text-slate-400">
                    <i class="fas fa-chart-line text-3xl mb-3 block text-slate-300"></i>
                    <p class="text-sm font-semibold text-slate-500 mb-1">No earnings yet</p>
                    <p class="text-xs">Refer friends or sell services and your earnings will appear here.</p>
                </td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php
    return ob_get_clean();
}

} // end function_exists guard
