<?php
/* ============================================================================
   WBMCZ — My Commission
   Every rupee credited to this member through the product share engine:
     referral · seller share · subscription discount · staff share
   Source of truth: product_share_ledger (includes/shares.php)
   ============================================================================ */
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/shares.php';

if (!isLoggedIn()) { redirect('login.php'); }

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];

$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;
if (!$user) { session_destroy(); redirect('login.php'); }

shares_ensure_schema($db);

/* ---- Filters ---- */
$f_type = isset($_GET['type']) ? preg_replace('/[^a-z_]/', '', $_GET['type']) : 'all';
$f_from = isset($_GET['from']) && $_GET['from'] !== '' ? $_GET['from'] : '';
$f_to   = isset($_GET['to'])   && $_GET['to']   !== '' ? $_GET['to']   : '';

$where  = "beneficiary_id = ?";
$params = [$user_id];
if ($f_type !== 'all' && $f_type !== '') { $where .= " AND share_type = ?"; $params[] = $f_type; }
if ($f_from !== '') { $where .= " AND DATE(created_at) >= ?"; $params[] = $f_from; }
if ($f_to   !== '') { $where .= " AND DATE(created_at) <= ?"; $params[] = $f_to; }

$rows = [];
try {
    $rows = $db->select("SELECT * FROM product_share_ledger WHERE $where ORDER BY id DESC LIMIT 500", $params);
} catch (\Throwable $e) {}

/* ---- Totals by type (unfiltered, all time) ---- */
$totals = ['referral' => 0.0, 'seller' => 0.0, 'staff' => 0.0, 'subscription_discount' => 0.0];
$counts = ['referral' => 0,   'seller' => 0,   'staff' => 0,   'subscription_discount' => 0];
try {
    foreach ($db->select("SELECT share_type, SUM(amount) AS t, COUNT(id) AS c FROM product_share_ledger WHERE beneficiary_id = ? GROUP BY share_type", [$user_id]) as $r) {
        $totals[$r['share_type']] = (float)$r['t'];
        $counts[$r['share_type']] = (int)$r['c'];
    }
} catch (\Throwable $e) {}
$grand_total = array_sum($totals);

/* This month */
$this_month = 0.0;
try {
    $m = $db->select("SELECT SUM(amount) AS t FROM product_share_ledger WHERE beneficiary_id = ? AND YEAR(created_at) = YEAR(CURDATE()) AND MONTH(created_at) = MONTH(CURDATE())", [$user_id]);
    $this_month = !empty($m[0]['t']) ? (float)$m[0]['t'] : 0.0;
} catch (\Throwable $e) {}

/* Filtered total */
$filtered_total = 0.0;
foreach ($rows as $r) { $filtered_total += (float)$r['amount']; }

$type_meta = [
    'referral'              => ['Referral Commission', 'fa-user-group',    'from-purple-500 to-fuchsia-500', 'bg-purple-50 text-purple-700'],
    'seller'                => ['Seller Share',        'fa-store',         'from-emerald-500 to-teal-600',   'bg-emerald-50 text-emerald-700'],
    'staff'                 => ['Staff Share',         'fa-user-tie',      'from-blue-500 to-indigo-600',    'bg-blue-50 text-blue-700'],
    'subscription_discount' => ['Subscriber Saving',   'fa-crown',         'from-amber-400 to-yellow-600',   'bg-amber-50 text-amber-700'],
];

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

$all_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$sidebar_subcats = [1 => [], 5 => []];
foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $sidebar_subcats[$__r['category_id']][] = $__r; }
?>
<!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>My Commission - <?php echo htmlspecialchars($company_name); ?></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=Poppins:wght@600;700;800&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family:'Inter',sans-serif; } .hide-scrollbar::-webkit-scrollbar { display:none; } </style>
</head>
<?php
require_once __DIR__ . '/includes/theme.php';
$__menu = theme_user_menu($sidebar_subcats, $all_categories);
theme_open([
    'panel'  => 'user',
    'base'   => '',
    'title'  => 'My Commission',
    'active' => 'profile',
    'user'   => $user,
    'wallet' => $wallet_balance,
    'notifs' => $unread_notifs,
    'logo'   => $company_logo,
    'brand'  => $company_name,
    'menu'   => $__menu,
    'state'  => '',
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">

                <!-- ===== Totals ===== -->
                <div class="tp-stat mb-6 flex flex-wrap items-center justify-between gap-4">
                    <div class="relative z-10">
                        <p class="text-[11px] uppercase tracking-[.2em] text-[#F5C451] font-bold">Total commission earned</p>
                        <h2 class="tp-title text-3xl sm:text-4xl mt-1">₹<?php echo number_format($grand_total, 2); ?></h2>
                        <p class="text-white/60 text-xs mt-1">This month: <b class="text-white">₹<?php echo number_format($this_month, 2); ?></b></p>
                    </div>
                    <a href="wallet.php" class="tp-btn-gold text-xs !py-2.5 !px-5 relative z-10 whitespace-nowrap">
                        <i class="fas fa-wallet mr-1"></i> Open My Wallet
                    </a>
                </div>

                <div class="tile-grid mb-6">
                    <?php foreach ($type_meta as $k => $m): ?>
                        <div class="sq-tile">
                            <span class="sq-ico bg-gradient-to-br <?php echo $m[2]; ?>"><i class="fas <?php echo $m[1]; ?>"></i></span>
                            <span class="sq-val">₹<?php echo number_format($totals[$k], 0); ?></span>
                            <span class="sq-lbl"><?php echo $m[0]; ?></span>
                            <span class="sq-pill <?php echo $m[3]; ?>"><?php echo (int)$counts[$k]; ?> entries</span>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- ===== Filters ===== -->
                <form method="GET" class="bg-white border border-slate-200 rounded-2xl p-4 sm:p-5 mb-6">
                    <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
                        <div>
                            <label class="block text-[11px] font-bold uppercase tracking-wide text-slate-500 mb-1">Type</label>
                            <select name="type" class="w-full px-4 py-2.5 bg-white border border-slate-300 rounded-lg text-sm">
                                <option value="all" <?php echo $f_type === 'all' ? 'selected' : ''; ?>>All commission</option>
                                <?php foreach ($type_meta as $k => $m): ?>
                                    <option value="<?php echo $k; ?>" <?php echo $f_type === $k ? 'selected' : ''; ?>><?php echo $m[0]; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold uppercase tracking-wide text-slate-500 mb-1">From</label>
                            <input type="date" name="from" value="<?php echo htmlspecialchars($f_from); ?>" class="w-full px-4 py-2.5 bg-white border border-slate-300 rounded-lg text-sm">
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold uppercase tracking-wide text-slate-500 mb-1">To</label>
                            <input type="date" name="to" value="<?php echo htmlspecialchars($f_to); ?>" class="w-full px-4 py-2.5 bg-white border border-slate-300 rounded-lg text-sm">
                        </div>
                        <div class="flex items-end gap-2">
                            <button type="submit" class="flex-1 px-5 py-2.5 rounded-lg bg-slate-800 hover:bg-slate-900 text-white font-bold text-sm"><i class="fas fa-filter mr-1"></i> Apply</button>
                            <a href="my_commission.php" class="px-4 py-2.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-600 font-bold text-sm">Reset</a>
                        </div>
                    </div>
                </form>

                <!-- ===== Ledger ===== -->
                <div class="bg-white rounded-2xl shadow-sm border border-slate-200 overflow-hidden mb-20">
                    <div class="px-5 py-4 border-b border-slate-100 bg-slate-50/60 flex flex-wrap items-center justify-between gap-2">
                        <h3 class="font-bold text-slate-800">Commission History</h3>
                        <span class="text-xs font-bold text-slate-500">
                            <?php echo count($rows); ?> entries · <span class="text-emerald-600">₹<?php echo number_format($filtered_total, 2); ?></span>
                        </span>
                    </div>
                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-slate-50 border-b border-slate-100 text-slate-500 text-xs uppercase tracking-wider">
                                    <th class="py-3.5 px-5 font-semibold">Date</th>
                                    <th class="py-3.5 px-5 font-semibold">Service</th>
                                    <th class="py-3.5 px-5 font-semibold">Type</th>
                                    <th class="py-3.5 px-5 font-semibold text-right">Rate</th>
                                    <th class="py-3.5 px-5 font-semibold text-right">Amount</th>
                                    <th class="py-3.5 px-5 font-semibold text-center">Credited</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100 text-sm">
                            <?php if (empty($rows)): ?>
                                <tr><td colspan="6" class="py-12 text-center text-slate-500">
                                    <i class="fas fa-hand-holding-dollar text-3xl mb-3 text-slate-300 block"></i>
                                    No commission recorded for this filter yet.
                                    <p class="text-xs text-slate-400 mt-2">Share your referral link and earn on every purchase your team makes.</p>
                                    <a href="refer.php" class="inline-flex items-center gap-2 mt-4 px-5 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-sm"><i class="fas fa-gift"></i> Refer &amp; Earn</a>
                                </td></tr>
                            <?php else: foreach ($rows as $r):
                                $m = $type_meta[$r['share_type']] ?? [ucfirst(str_replace('_', ' ', $r['share_type'])), 'fa-coins', 'from-slate-400 to-slate-500', 'bg-slate-100 text-slate-600'];
                            ?>
                                <tr class="hover:bg-slate-50">
                                    <td class="py-3.5 px-5 text-slate-500 whitespace-nowrap"><?php echo date('d M Y', strtotime($r['created_at'])); ?><span class="block text-[11px] text-slate-400"><?php echo date('h:i A', strtotime($r['created_at'])); ?></span></td>
                                    <td class="py-3.5 px-5">
                                        <span class="font-bold text-slate-800"><?php echo htmlspecialchars($r['service_title'] ?: 'Service #' . (int)$r['service_id']); ?></span>
                                        <?php if (!empty($r['order_id'])): ?><span class="block text-[11px] text-slate-400">Order #<?php echo (int)$r['order_id']; ?></span><?php endif; ?>
                                    </td>
                                    <td class="py-3.5 px-5">
                                        <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-bold <?php echo $m[3]; ?> whitespace-nowrap">
                                            <i class="fas <?php echo $m[1]; ?>"></i> <?php echo $m[0]; ?>
                                        </span>
                                    </td>
                                    <td class="py-3.5 px-5 text-right text-slate-500 whitespace-nowrap"><?php echo ((float)$r['percent'] > 0) ? rtrim(rtrim(number_format((float)$r['percent'], 2), '0'), '.') . '%' : '—'; ?></td>
                                    <td class="py-3.5 px-5 text-right font-extrabold text-emerald-600 whitespace-nowrap">+₹<?php echo number_format((float)$r['amount'], 2); ?></td>
                                    <td class="py-3.5 px-5 text-center">
                                        <?php if (!empty($r['paid'])): ?>
                                            <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-bold bg-emerald-100 text-emerald-700"><i class="fas fa-circle-check"></i> Credited</span>
                                        <?php else: ?>
                                            <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-bold bg-amber-50 text-amber-700"><i class="fas fa-clock"></i> Recorded</span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php if (count($rows) >= 500): ?>
                    <p class="px-5 py-3 text-xs text-slate-400 bg-slate-50 border-t border-slate-100">Showing the 500 most recent entries. Narrow the date range to see older ones.</p>
                    <?php endif; ?>
                </div>

            </main>
        </div>
    </div>
</body>
</html>
