<?php
/* ============================================================================
   Seller panel → Earning Report
   ============================================================================ */
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Language.php';
require_once __DIR__ . '/../includes/earning_view.php';

if (!isLoggedIn() || $_SESSION['user_type'] !== 'seller') { redirect('../login.php'); }

$user_id = $_SESSION['user_id'];

// CSV export must run before any output
earning_handle_export($db, $user_id);

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();

$user_data = $db->select("SELECT u.*, s.business_name FROM users u LEFT JOIN sellers s ON u.id = s.user_id WHERE u.id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
if (!$user) { redirect('../logout.php'); }

$data = earning_page_data($db, $user_id);

/* Seller-specific order figures, shown alongside the wallet earnings */
$sell_completed = (float)($db->select("SELECT COALESCE(SUM(amount),0) t FROM orders WHERE seller_id = ? AND status = 'Completed'", [$user_id])[0]['t'] ?? 0);
$sell_pending   = (float)($db->select("SELECT COALESCE(SUM(amount),0) t FROM orders WHERE seller_id = ? AND status = 'Pending'", [$user_id])[0]['t'] ?? 0);
$sell_orders    = (int)($db->select("SELECT COUNT(*) c FROM orders WHERE seller_id = ?", [$user_id])[0]['c'] ?? 0);

$wallet_balance  = $data['balances']['main'];
$unread_notifs   = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$raw_logo        = getSetting('company_logo', 'assets/images/logo.png');
$company_logo    = (strpos($raw_logo, 'http') === 0) ? $raw_logo : '../' . ltrim($raw_logo, '/');
$company_name    = getSetting('company_name', 'WBMCZ');

/* Categories this seller is assigned to (for the sidebar) */
$__scats = [];
try {
    $cat_ids = array_filter(array_map('intval', explode(',', (string)($user['seller_categories'] ?? ''))));
    $all = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
    foreach ($all as $c) { if (empty($cat_ids) || in_array((int)$c['id'], $cat_ids, true)) $__scats[] = $c; }
} catch (\Throwable $e) {}
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Earning Report - Seller</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap" rel="stylesheet">
    <style> body { font-family:'Inter',sans-serif; } .hide-scrollbar::-webkit-scrollbar { display:none; } .hide-scrollbar { -ms-overflow-style:none; scrollbar-width:none; } </style>
</head>
<?php
require_once __DIR__ . '/../includes/theme.php';
$__menu = theme_seller_menu($__scats);
theme_open([
    'panel'  => 'seller',
    'base'   => '../',
    'title'  => 'Earning Report',
    'active' => 'earning',
    'user'   => $user,
    'wallet' => $wallet_balance,
    'notifs' => $unread_notifs,
    'logo'   => $company_logo,
    'brand'  => $company_name,
    'menu'   => $__menu,
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">
                <div class="max-w-6xl mx-auto pb-20">

                    <div class="mb-6">
                        <h2 class="text-2xl font-bold text-slate-800 mb-1"><i class="fas fa-chart-line text-teal-600 mr-2"></i>Earning Report</h2>
                        <p class="text-gray-500 text-sm">Your seller shares, referral earnings and order revenue, all in one report.</p>
                    </div>

                    <!-- seller-only order figures -->
                    <div class="grid grid-cols-2 lg:grid-cols-3 gap-3 mb-5">
                        <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4">
                            <p class="text-[10px] font-extrabold uppercase tracking-wider text-slate-400 mb-1">Completed Order Value</p>
                            <p class="text-2xl font-black text-teal-600">₹<?php echo number_format($sell_completed, 2); ?></p>
                            <p class="text-[10px] text-slate-400 mt-0.5">Gross, before share split</p>
                        </div>
                        <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4">
                            <p class="text-[10px] font-extrabold uppercase tracking-wider text-slate-400 mb-1">Pending Order Value</p>
                            <p class="text-2xl font-black text-amber-600">₹<?php echo number_format($sell_pending, 2); ?></p>
                            <p class="text-[10px] text-slate-400 mt-0.5">Awaiting completion</p>
                        </div>
                        <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4">
                            <p class="text-[10px] font-extrabold uppercase tracking-wider text-slate-400 mb-1">Total Orders</p>
                            <p class="text-2xl font-black text-slate-800"><?php echo number_format($sell_orders); ?></p>
                            <p class="text-[10px] text-slate-400 mt-0.5">All time</p>
                        </div>
                    </div>

                    <?php echo earning_render($data, ['self' => 'earning_report.php', 'accent' => 'teal']); ?>

                </div>
            </main>
<?php theme_close(); ?>
</html>
