<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/Language.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');
}

$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);
$unread_count = count($unread_notifs);

$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');
$profile_image_url = !empty($user['profile_pic']) ? 'uploads/profiles/' . $user['profile_pic'] : null;

// Determine dashboard link based on role
$dashboard_link = 'dashboard.php';
if ($user['user_type'] == 'seller') { $dashboard_link = 'seller/index.php'; } 
elseif ($user['user_type'] == 'admin') { $dashboard_link = 'admin/index.php'; }

// Fetch Dynamic User Sliders from Database
/* The after-login banner has its OWN slides. Whatever the admin sets for the
   public home page never appears here, and vice versa — the two are managed
   on separate tabs in Admin -> Website Settings -> Hero Slider. */
$dashboard_slides = getHeroSlides('dashboard');

/* Bengali / Hindi text if the slide carries it, else the English one */
$dash_sfx = ($current_lang === 'bn') ? '_bn' : (($current_lang === 'hi') ? '_hi' : '');
$DH = function ($slide, $base) use ($dash_sfx) {
    $alt = ['title' => 'title', 'subtitle' => 'subtitle', 'badge_text' => 'badge', 'button_text' => 'button'];
    if ($dash_sfx !== '' && isset($alt[$base]) && !empty($slide[$alt[$base] . $dash_sfx])) {
        return (string)$slide[$alt[$base] . $dash_sfx];
    }
    return (string)($slide[$base] ?? '');
};

// Fetch ALL active categories for the Sidebar Dropdown & Main Grid
$all_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");

/* How much is actually inside each category, so a tile can say "6 services"
   instead of a flat "Open" — and an empty one honestly says "Coming soon". */
$dash_sub_counts = [];
$dash_srv_counts = [];
try {
    foreach ($db->select("SELECT category_id, COUNT(*) c FROM agency_sub_categories WHERE status = 1 GROUP BY category_id") as $__r) {
        $dash_sub_counts[(int)$__r['category_id']] = (int)$__r['c'];
    }
} catch (\Throwable $e) {}
try {
    foreach ($db->select("SELECT category_id, COUNT(*) c FROM seller_services WHERE status = 1 GROUP BY category_id") as $__r) {
        $dash_srv_counts[(int)$__r['category_id']] = (int)$__r['c'];
    }
} catch (\Throwable $e) {}
$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><?php echo $lang->translate('dashboard', 'Dashboard'); ?> - <?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://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.css" />
    <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@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; scroll-behavior: smooth;} .hide-scrollbar::-webkit-scrollbar { display: none; } .hide-scrollbar { -ms-overflow-style: none; scrollbar-width: none; } </style>
</head>
<?php
/* ===== Premium shared layout (Navy + Gold) ===== */
require_once __DIR__ . '/includes/theme.php';
$__cats = isset($all_categories) ? $all_categories : $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$__subs = isset($sidebar_subcats) ? $sidebar_subcats : null;
if ($__subs === null) { $__subs = [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) { $__subs[$__r['category_id']][] = $__r; } }
$__menu = theme_user_menu($__subs, $__cats);

/* ============================================================================
   REPORT TILES — every number the member needs, in one uniform square grid
   ============================================================================ */
require_once __DIR__ . '/includes/kyc.php';
kyc_ensure_schema($db);

$__o  = $db->select("SELECT COUNT(id) AS c FROM orders WHERE user_id = ?", [$user_id]);
$__op = $db->select("SELECT COUNT(id) AS c FROM orders WHERE user_id = ? AND status IN ('Pending','Processing')", [$user_id]);
$__oc = $db->select("SELECT COUNT(id) AS c FROM orders WHERE user_id = ? AND status = 'Completed'", [$user_id]);
$__rf = $db->select("SELECT COUNT(id) AS c FROM users WHERE referred_by = ?", [$user_id]);
$stat_orders    = !empty($__o[0]['c'])  ? (int)$__o[0]['c']  : 0;
$stat_pending   = !empty($__op[0]['c']) ? (int)$__op[0]['c'] : 0;
$stat_completed = !empty($__oc[0]['c']) ? (int)$__oc[0]['c'] : 0;
$stat_refs      = !empty($__rf[0]['c']) ? (int)$__rf[0]['c'] : 0;

/* Team size across 3 levels */
$stat_team = 0;
$__ids = array_column($db->select("SELECT id FROM users WHERE referred_by = ?", [$user_id]), 'id');
$stat_team += count($__ids);
for ($__lv = 0; $__lv < 2 && !empty($__ids); $__lv++) {
    $__ph = implode(',', array_fill(0, count($__ids), '?'));
    $__ids = array_column($db->select("SELECT id FROM users WHERE referred_by IN ($__ph)", $__ids), 'id');
    $stat_team += count($__ids);
}

/* Earnings — referral commission from the share ledger, transactions as fallback */
$stat_earning = 0.00;
try {
    $__e = $db->select("SELECT SUM(amount) AS t FROM product_share_ledger WHERE share_type = 'referral' AND beneficiary_id = ?", [$user_id]);
    $stat_earning = !empty($__e[0]['t']) ? (float)$__e[0]['t'] : 0.00;
} catch (\Throwable $e) {}
if ($stat_earning <= 0) {
    $__e = $db->select("SELECT SUM(amount) AS t FROM transactions WHERE user_id = ? AND description LIKE '%Referral Commission%' AND status = 'Success'", [$user_id]);
    $stat_earning = !empty($__e[0]['t']) ? (float)$__e[0]['t'] : 0.00;
}

/* Subscription */
$is_sub = !empty($user['is_subscribed']);
$sub_till = '';
if ($is_sub) {
    foreach (['subscription_expiry', 'subscription_end', 'subscribed_till', 'subscription_date'] as $__c) {
        if (!empty($user[$__c])) { $sub_till = date('d M Y', strtotime($user[$__c])); break; }
    }
}

/* KYC */
$kyc_p = kyc_progress($db, $user_id, $user['user_type'] ?? 'customer');
$kyc_map = [
    'approved'      => ['Approved',  'from-emerald-500 to-teal-500', 'bg-emerald-50 text-emerald-700'],
    'pending'       => ['Pending',   'from-amber-400 to-orange-500', 'bg-amber-50 text-amber-700'],
    'rejected'      => ['Rejected',  'from-rose-500 to-pink-500',    'bg-rose-50 text-rose-700'],
    'not_submitted' => ['Not filled','from-slate-400 to-slate-500',  'bg-slate-100 text-slate-500'],
];
$kyc_ui = $kyc_map[$kyc_p['status']] ?? $kyc_map['not_submitted'];

/* Services the member can actually open right now */
$stat_services = 0;
foreach ($all_categories as $__c) { if (in_array($__c['id'], [1, 5])) $stat_services++; }

/* ---- The report grid (label, value, pill, icon, gradient, link) ---- */
$report_tiles = [
    ['Total Orders',   number_format($stat_orders),               $stat_pending > 0 ? $stat_pending . ' in progress' : 'all clear', 'fa-cart-shopping',  'from-indigo-500 to-blue-600',   'bg-indigo-50 text-indigo-600',  'orders.php'],
    ['Completed',      number_format($stat_completed),            'orders done',                                                   'fa-circle-check',   'from-emerald-500 to-teal-500',  'bg-emerald-50 text-emerald-600','orders.php'],
    ['In Progress',    number_format($stat_pending),              'pending',                                                       'fa-clock',          'from-amber-400 to-orange-500',  'bg-amber-50 text-amber-600',    'orders.php'],
    ['My Referrals',   number_format($stat_refs),                 $stat_team . ' in team',                                         'fa-user-group',     'from-purple-500 to-fuchsia-500','bg-purple-50 text-purple-600',  'refer.php'],
    ['Earning',        '₹' . number_format($stat_earning, 0),     'commission',                                                    'fa-chart-line',     'from-teal-500 to-cyan-500',     'bg-teal-50 text-teal-600',      'earning_report.php'],
    ['Wallet',         '₹' . number_format((float)$wallet_balance, 0), 'balance',                                                  'fa-wallet',         'from-slate-700 to-slate-900',   'bg-slate-100 text-slate-600',   'wallet.php'],
    ['Subscription',   $is_sub ? 'Active' : 'Inactive',           $is_sub ? ($sub_till ?: 'premium') : 'subscribe now',            'fa-crown',          $is_sub ? 'from-amber-400 to-yellow-600' : 'from-slate-400 to-slate-500', $is_sub ? 'bg-amber-50 text-amber-700' : 'bg-slate-100 text-slate-500', 'subscription.php'],
    ['KYC Status',     $kyc_ui[0],                                $kyc_p['percent'] . '% complete',                                'fa-id-card',        $kyc_ui[1],                      $kyc_ui[2],                      'profile.php#kyc'],
    ['My Services',    number_format($stat_services),             'categories open',                                               'fa-bag-shopping',   'from-blue-500 to-indigo-500',   'bg-blue-50 text-blue-600',      '#servicesHub'],
    ['Helpdesk',       'Support',                                 'raise a ticket',                                                'fa-headset',        'from-rose-500 to-pink-500',     'bg-rose-50 text-rose-600',      'helpdesk.php'],
];

theme_open([
    'panel'  => 'user',
    'base'   => '',
    'title'  => 'Dashboard',
    'active' => 'dashboard',
    'user'   => isset($user) ? $user : ['name' => 'User', 'mobile' => ''],
    'wallet' => isset($wallet_balance) ? $wallet_balance : 0,
    'notifs' => isset($unread_notifs) ? $unread_notifs : [],
    'logo'   => isset($company_logo) ? $company_logo : 'assets/images/logo.png',
    'brand'  => isset($company_name) ? $company_name : 'WBMCZ',
    'menu'   => $__menu,
    'state'  => '',
]);
?>

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

                <!-- ===================== 1. HERO BANNER (top of the page) ===================== -->
                <div class="mb-6 rounded-2xl overflow-hidden shadow-lg border border-gray-200 bg-white">
                    <div class="swiper dashboardSwiper h-[200px] md:h-[280px] lg:h-[350px]">
                        <div class="swiper-wrapper">
                            <?php if(!empty($dashboard_slides)): foreach($dashboard_slides as $slide):
                                $d_badge = $DH($slide, 'badge_text');
                                if ($d_badge === '') { $d_badge = $DH($slide, 'button_text'); }
                                $d_title = $DH($slide, 'title');
                                $d_sub   = $DH($slide, 'subtitle');
                                $d_link  = trim((string)($slide['button_link'] ?? ''));
                                $d_img   = (string)($slide['image_path'] ?? '');
                            ?>
                            <div class="swiper-slide relative">
                                <div class="absolute inset-0 bg-gradient-to-r from-gray-900/70 to-transparent z-10"></div>
                                <?php if ($d_img !== ''): ?>
                                    <img src="<?php echo esc($d_img); ?>" alt="" class="w-full h-full object-cover">
                                <?php else: ?>
                                    <div class="w-full h-full bg-gradient-to-br from-indigo-800 to-blue-900"></div>
                                <?php endif; ?>
                                <div class="absolute inset-y-0 left-0 z-20 flex flex-col justify-center px-8 md:px-12 w-full md:w-2/3 text-white">
                                    <?php if ($d_badge !== ''): ?>
                                        <span class="bg-blue-600 text-xs font-bold py-1.5 px-3.5 rounded-full w-max mb-3 shadow-md"><?php echo esc($d_badge); ?></span>
                                    <?php endif; ?>
                                    <?php if ($d_title !== ''): ?>
                                        <h2 class="text-2xl md:text-4xl font-extrabold mb-2 leading-snug"><?php echo esc($d_title); ?></h2>
                                    <?php endif; ?>
                                    <?php if ($d_sub !== ''): ?>
                                        <p class="text-sm md:text-base text-gray-200 leading-relaxed"><?php echo esc($d_sub); ?></p>
                                    <?php endif; ?>
                                    <?php if ($d_link !== '' && $d_link !== '#'): ?>
                                        <a href="<?php echo esc($d_link); ?>" class="mt-4 w-max px-5 py-2.5 rounded-xl bg-white text-slate-900 text-sm font-bold shadow hover:bg-gray-100">
                                            <?php echo esc($DH($slide, 'button_text') ?: 'Open'); ?> <i class="fas fa-arrow-right ml-1"></i>
                                        </a>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endforeach; else: ?>
                            <div class="swiper-slide relative bg-indigo-900 flex items-center justify-center">
                                <p class="text-white text-lg font-bold">Welcome to <?php echo htmlspecialchars($company_name); ?></p>
                            </div>
                            <?php endif; ?>
                        </div>
                        <div class="swiper-pagination"></div>
                    </div>
                </div>

                <!-- ===================== 2. WELCOME STRIP ===================== -->
                <div class="tp-stat mb-6 flex flex-wrap items-center justify-between gap-4">
                    <div class="relative z-10 min-w-0">
                        <p class="text-[11px] uppercase tracking-[.2em] text-[#F5C451] font-bold">Welcome back</p>
                        <h2 class="tp-title text-xl sm:text-2xl mt-1 truncate"><?php echo htmlspecialchars($user['name']); ?></h2>
                        <p class="text-white/60 text-xs mt-1">
                            WBMCZ<?php echo str_pad($user_id, 4, '0', STR_PAD_LEFT); ?>
                            <?php if ($is_sub): ?><span class="ml-2 text-[#F5C451] font-bold"><i class="fas fa-crown"></i> Premium</span><?php endif; ?>
                        </p>
                    </div>
                    <div class="relative z-10 flex items-center gap-4">
                        <div class="text-right">
                            <p class="text-[10px] uppercase tracking-wider text-white/50 font-bold">Wallet Balance</p>
                            <p class="text-2xl font-extrabold">₹<?php echo number_format((float)$wallet_balance, 2); ?></p>
                        </div>
                        <a href="wallet.php#add_money" class="tp-btn-gold text-xs !py-2 !px-4 whitespace-nowrap"><i class="fas fa-plus mr-1"></i>Add</a>
                    </div>
                </div>

                <!-- ===================== 3. SERVICES HUB — same square tile ===================== -->
                <div id="servicesHub" class="mb-4 flex items-end justify-between gap-3">
                    <div>
                        <h2 class="tp-title text-lg sm:text-xl">Services Hub</h2>
                        <p class="text-slate-500 text-xs mt-0.5">Select a category to browse services and start working.</p>
                    </div>
                    <span class="hidden sm:inline-flex tp-chip bg-slate-100 text-slate-500"><i class="fas fa-grip"></i> <?php echo count($all_categories); ?> categories</span>
                </div>

                <div class="tile-grid pb-20">
                    <?php if (!empty($all_categories)): ?>
                        <?php foreach ($all_categories as $cat):
                            $__cid  = (int)$cat['id'];
                            $__subs = (int)($dash_sub_counts[$__cid] ?? 0);
                            $__srv  = (int)($dash_srv_counts[$__cid] ?? 0);
                        ?>
                        <a href="category.php?id=<?php echo $__cid; ?>" class="sq-tile">
                            <span class="sq-ico bg-gradient-to-br <?php echo htmlspecialchars($cat['gradient_class']); ?>">
                                <i class="fas <?php echo htmlspecialchars($cat['icon_class']); ?>"></i>
                            </span>
                            <span class="sq-title"><?php echo $lang->translate($cat['category_key'], $cat['title']); ?></span>
                            <?php if ($__srv > 0): ?>
                                <span class="sq-pill bg-emerald-50 text-emerald-600">
                                    <?php echo $__srv; ?> service<?php echo $__srv > 1 ? 's' : ''; ?>
                                </span>
                            <?php elseif ($__subs > 0): ?>
                                <span class="sq-pill bg-indigo-50 text-indigo-600">
                                    <?php echo $__subs; ?> section<?php echo $__subs > 1 ? 's' : ''; ?>
                                </span>
                            <?php else: ?>
                                <span class="sq-pill bg-slate-100 text-slate-400">Coming soon</span>
                            <?php endif; ?>
                        </a>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="col-span-full p-8 text-center text-gray-500 bg-white rounded-xl border border-gray-200">
                            <?php echo $lang->translate('no_categories_found', 'No categories found.'); ?>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- ===================== 4. MY REPORTS — uniform square tiles ===================== -->
                <div class="mb-4 flex items-end justify-between gap-3">
                    <div>
                        <h2 class="tp-title text-lg sm:text-xl">My Reports</h2>
                        <p class="text-slate-500 text-xs mt-0.5">Orders, referrals, earning, subscription, KYC — everything at a glance.</p>
                    </div>
                    <a href="earning_report.php" class="hidden sm:inline-flex tp-chip bg-slate-100 text-slate-500 hover:bg-slate-200"><i class="fas fa-arrow-right"></i> Full report</a>
                </div>

                <div class="tile-grid mb-8">
                    <?php foreach ($report_tiles as $rt): ?>
                        <a href="<?php echo htmlspecialchars($rt[6]); ?>" class="sq-tile">
                            <span class="sq-ico bg-gradient-to-br <?php echo $rt[4]; ?>"><i class="fas <?php echo $rt[3]; ?>"></i></span>
                            <span class="sq-val"><?php echo htmlspecialchars($rt[1]); ?></span>
                            <span class="sq-lbl"><?php echo htmlspecialchars($rt[0]); ?></span>
                            <span class="sq-pill <?php echo $rt[5]; ?>"><?php echo htmlspecialchars($rt[2]); ?></span>
                        </a>
                    <?php endforeach; ?>
                </div>

            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/swiper@10/swiper-bundle.min.js"></script>
    <script>
        const dashboardSwiper = new Swiper('.dashboardSwiper', {
            loop: true,
            autoplay: { delay: 4000, disableOnInteraction: false },
            effect: 'fade', fadeEffect: { crossFade: true },
            pagination: { el: '.swiper-pagination', clickable: true },
        });
    </script>
</body>
</html>