<?php
/* ============================================================================
   WBMCZ — CART
   ----------------------------------------------------------------------------
   The basket, with every line priced for this particular buyer, and a summary
   that separates what is payable now from what is collected at the visit.
   Checkout itself lives in checkout.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';
require_once __DIR__ . '/includes/wallet.php';
require_once __DIR__ . '/includes/purchase.php';

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

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

wallet_ensure_schema($db);
shares_ensure_schema($db);
buy_ensure_schema($db);

$company_name = getSetting('company_name', 'WBMCZ');
$company_logo = getSetting('company_logo', 'assets/images/logo.png');

$u    = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($u) ? $u[0] : ['name' => 'User', 'mobile' => ''];
$wal  = wallet_balances($db, $user_id);
$wallet_balance = $wal['main'];

/* ---------- actions ---------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['qty'], $_POST['cart_id'])) {
        cart_set_qty($db, $user_id, (int)$_POST['cart_id'], (int)$_POST['qty']);
    } elseif (isset($_POST['remove'])) {
        cart_remove($db, $user_id, (int)$_POST['remove']);
        $_SESSION['flash_ok'] = 'Removed from your cart.';
    } elseif (isset($_POST['clear'])) {
        cart_clear($db, $user_id);
        $_SESSION['flash_ok'] = 'Your cart is empty again.';
    }
    redirect('cart.php');
}
$flash = '';
if (!empty($_SESSION['flash_ok'])) { $flash = $_SESSION['flash_ok']; unset($_SESSION['flash_ok']); }

$lines = cart_items($db, $user_id);

/* anything the buyer is not allowed to purchase yet is flagged, not hidden */
$blocked = 0;
$collect = 0;
foreach ($lines as $i => $l) {
    $g  = product_purchase_gate($db, $l['svc'], $user_id);
    /* Missing KYC does not block the basket any more — the checkout page asks
       for it. Only a product that is out of the buyer's area is a real block. */
    $ok = $g['ok'] || !empty($g['collect']);
    $lines[$i]['gate_ok']  = $ok;
    $lines[$i]['gate_kyc'] = !empty($g['collect']);
    $lines[$i]['gate_msg'] = $ok ? '' : product_gate_message(product_gate_payload($db, $l['svc'], $user_id, $g));
    if (!$ok) { $blocked++; }
    elseif (!empty($g['collect'])) { $collect++; }
}

$t       = cart_totals($lines);
$payNow  = $t['has_visit'] ? $t['advance'] : $t['payable'];
$plan    = buy_wallet_plan($db, $user_id, $payNow, true);

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

function pr($n) { return '₹' . number_format((float)$n, 2); }
?>
<!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 Cart - <?php echo esc($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@400;600;700&family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Inter', sans-serif; }
        .font-poppins { font-family: 'Poppins', sans-serif; }
        [x-cloak] { display:none !important; }
        .c-card { background:#fff; border:1px solid #e8edf5; border-radius:18px; box-shadow:0 10px 30px -22px rgba(15,23,42,.55); }
        .c-line { display:flex; gap:14px; padding:16px; border-bottom:1px solid #f1f5f9; }
        .c-line:last-child { border-bottom:0; }
        .c-ico { width:64px; height:64px; border-radius:16px; background:#f8fafc; display:flex; align-items:center;
                 justify-content:center; font-size:1.5rem; flex-shrink:0; overflow:hidden; }
        .c-ico img { width:100%; height:100%; object-fit:contain; padding:8px; }
        .qty { display:inline-flex; align-items:center; border:1px solid #e2e8f0; border-radius:10px; overflow:hidden; }
        .qty button { width:30px; height:30px; font-weight:800; color:#475569; background:#f8fafc; }
        .qty button:hover { background:#eef2f7; }
        .qty span { width:34px; text-align:center; font-weight:800; font-size:.82rem; }
        .row { display:flex; align-items:center; justify-content:space-between; padding:9px 0;
               border-bottom:1px dashed #eef2f7; font-size:.86rem; }
        .row:last-child { border-bottom:0; }
        .btn { display:inline-flex; align-items:center; justify-content:center; gap:8px; width:100%;
               font-weight:800; border-radius:13px; padding:14px 18px; font-size:.9rem; transition:transform .18s ease; }
        .btn:hover { transform:translateY(-2px); }
        .btn-go  { background:linear-gradient(135deg,#C8901B,#e0a92c); color:#14202f; box-shadow:0 12px 26px -14px rgba(200,144,27,.95); }
        .btn-off { background:#e2e8f0; color:#64748b; cursor:not-allowed; }
        .btn-off:hover { transform:none; }
        .chip { display:inline-flex; align-items:center; gap:5px; padding:3px 9px; border-radius:999px;
                font-size:.66rem; font-weight:800; }
        .chip-gold { background:#fff7e6; color:#b45309; border:1px solid #fde3af; }
        .chip-green{ background:#ecfdf5; color:#047857; border:1px solid #d1fae5; }
    </style>
</head>
<?php
require_once __DIR__ . '/includes/theme.php';
$__cats = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$__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;
}
theme_open([
    'panel' => 'user', 'base' => '', 'title' => 'My Cart', 'active' => 'cart',
    'user' => $user, 'wallet' => $wallet_balance, 'notifs' => $unread_notifs,
    'logo' => $company_logo, 'brand' => $company_name,
    'menu' => theme_user_menu($__subs, $__cats),
]);
?>
<main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">
  <div class="max-w-5xl mx-auto">

    <?php if ($flash): ?>
        <div class="mb-4 px-4 py-3 rounded-xl bg-emerald-50 border border-emerald-200 text-emerald-800 text-sm font-semibold">
            <i class="fas fa-circle-check mr-1"></i> <?php echo esc($flash); ?>
        </div>
    <?php endif; ?>

    <?php if (empty($lines)): ?>
        <div class="c-card p-10 text-center">
            <div class="w-20 h-20 mx-auto rounded-full bg-slate-50 flex items-center justify-center text-3xl text-slate-300">
                <i class="fas fa-basket-shopping"></i>
            </div>
            <h2 class="font-poppins text-lg font-bold text-slate-800 mt-4">Your cart is empty</h2>
            <p class="text-[13px] text-slate-500 mt-1">Pick a service and it will show up here.</p>
            <a href="dashboard.php" class="btn btn-go mt-5 max-w-xs mx-auto"><i class="fas fa-bag-shopping"></i> Browse services</a>
        </div>
    <?php else: ?>
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-5">

      <div class="lg:col-span-2 c-card overflow-hidden">
        <div class="flex items-center justify-between px-5 py-4 border-b border-slate-100">
            <h2 class="font-poppins font-bold text-slate-800"><?php echo (int)$t['items']; ?> item<?php echo $t['items'] > 1 ? 's' : ''; ?> in your cart</h2>
            <form method="POST" onsubmit="return confirm('Empty the whole cart?');">
                <button name="clear" value="1" class="text-[12px] font-bold text-slate-400 hover:text-rose-600">
                    <i class="fas fa-trash-can"></i> Empty cart
                </button>
            </form>
        </div>

        <?php foreach ($lines as $l):
            $s  = $l['svc'];
            $th = buy_thumb($s);
        ?>
        <div class="c-line <?php echo $l['gate_ok'] ? '' : 'bg-rose-50/40'; ?>">
            <div class="c-ico">
                <?php if ($th['img']): ?><img src="<?php echo esc($th['img']); ?>" alt="">
                <?php else: ?><i class="fas <?php echo esc($th['icon']); ?> text-slate-400"></i><?php endif; ?>
            </div>
            <div class="flex-1 min-w-0">
                <a href="product.php?id=<?php echo (int)$l['service_id']; ?>" class="font-bold text-[14px] text-slate-800 hover:text-[#C8901B] leading-snug block truncate">
                    <?php echo esc($l['title']); ?>
                </a>
                <div class="flex flex-wrap items-center gap-1.5 mt-1.5">
                    <?php if ($l['fulfilment'] === 'visit'): ?>
                        <span class="chip chip-gold"><i class="fas fa-person-walking"></i> Visit</span>
                    <?php else: ?>
                        <span class="chip chip-green"><i class="fas fa-bolt"></i> Online</span>
                    <?php endif; ?>
                    <?php if ($l['discount'] > 0): ?>
                        <span class="chip chip-gold"><i class="fas fa-crown"></i> Saved <?php echo pr($l['discount']); ?></span>
                    <?php endif; ?>
                </div>
                <?php if (!$l['gate_ok']): ?>
                    <p class="text-[11.5px] text-rose-700 font-semibold mt-2 leading-snug"><i class="fas fa-lock mr-1"></i><?php echo esc($l['gate_msg']); ?></p>
                <?php elseif (!empty($l['gate_kyc'])): ?>
                    <p class="text-[11.5px] text-amber-700 font-semibold mt-2 leading-snug"><i class="fas fa-id-card mr-1"></i>A few verification details will be asked for at checkout.</p>
                <?php elseif ($l['fulfilment'] === 'visit'): ?>
                    <p class="text-[11.5px] text-slate-500 mt-2"><?php echo pr($l['advance']); ?> now · <?php echo pr($l['due']); ?> at the visit</p>
                <?php endif; ?>

                <div class="flex items-center gap-3 mt-2.5">
                    <form method="POST" class="qty">
                        <input type="hidden" name="cart_id" value="<?php echo (int)$l['cart_id']; ?>">
                        <button name="qty" value="<?php echo (int)$l['qty'] - 1; ?>" type="submit">−</button>
                        <span><?php echo (int)$l['qty']; ?></span>
                        <button name="qty" value="<?php echo (int)$l['qty'] + 1; ?>" type="submit">+</button>
                    </form>
                    <form method="POST">
                        <button name="remove" value="<?php echo (int)$l['cart_id']; ?>" class="text-[12px] font-bold text-slate-400 hover:text-rose-600">Remove</button>
                    </form>
                </div>
            </div>
            <div class="text-right flex-shrink-0">
                <p class="font-extrabold text-slate-800"><?php echo pr($l['payable'] * $l['qty']); ?></p>
                <?php if ($l['mrp'] > $l['payable']): ?>
                    <p class="text-[11px] line-through text-slate-400"><?php echo pr($l['mrp'] * $l['qty']); ?></p>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
      </div>

      <!-- summary -->
      <div class="lg:col-span-1">
        <div class="c-card p-5 lg:sticky lg:top-4">
            <h3 class="font-poppins font-bold text-slate-800 mb-3">Order summary</h3>

            <div class="row"><span class="text-slate-500">Total MRP</span><span class="font-bold text-slate-700"><?php echo pr($t['mrp']); ?></span></div>
            <?php if ($t['mrp'] > $t['regular']): ?>
                <div class="row"><span class="text-slate-500">Discount</span><span class="font-bold text-emerald-600">− <?php echo pr($t['mrp'] - $t['regular']); ?></span></div>
            <?php endif; ?>
            <?php if ($t['discount'] > 0): ?>
                <div class="row"><span class="text-amber-700 font-semibold"><i class="fas fa-crown"></i> Subscriber saving</span><span class="font-bold text-amber-700">− <?php echo pr($t['discount']); ?></span></div>
            <?php endif; ?>
            <div class="row"><span class="text-slate-800 font-bold">Order total</span><span class="font-extrabold text-slate-900 text-base"><?php echo pr($t['payable']); ?></span></div>

            <?php if ($t['has_visit']): ?>
            <div class="mt-3 rounded-xl border border-amber-200 bg-amber-50 p-4">
                <p class="text-[11px] font-extrabold uppercase tracking-wider text-amber-700 mb-1">Split into two</p>
                <div class="row" style="border-color:#fde3af"><span class="text-amber-900 font-semibold">Pay now</span><span class="font-extrabold text-amber-900"><?php echo pr($t['advance']); ?></span></div>
                <div class="row" style="border-color:#fde3af"><span class="text-amber-900 font-semibold">At the visit</span><span class="font-extrabold text-amber-900"><?php echo pr($t['due']); ?></span></div>
            </div>
            <?php endif; ?>

            <div class="mt-3 rounded-xl border border-slate-200 p-4">
                <div class="row"><span class="text-slate-500"><i class="fas fa-wallet text-slate-400 mr-1"></i> Wallet</span><span class="font-bold text-slate-800"><?php echo pr($wal['total']); ?></span></div>
                <?php if ($plan['wallet'] > 0): ?>
                    <div class="row"><span class="text-slate-500">Wallet covers</span><span class="font-bold text-emerald-600">− <?php echo pr($plan['wallet']); ?></span></div>
                <?php endif; ?>
                <div class="row"><span class="text-slate-800 font-bold">Payable now</span><span class="font-extrabold text-[#C8901B] text-base"><?php echo pr($plan['gateway']); ?></span></div>
            </div>

            <?php if ($blocked > 0): ?>
                <div class="mt-3 rounded-xl bg-rose-50 border border-rose-200 p-3.5">
                    <p class="text-[12px] text-rose-800 font-semibold leading-snug">
                        <?php echo $blocked; ?> item<?php echo $blocked > 1 ? 's are' : ' is'; ?> not ready to buy yet. Remove
                        <?php echo $blocked > 1 ? 'them' : 'it'; ?>, or finish what is missing, to continue.
                    </p>
                </div>
                <button class="btn btn-off mt-4" disabled><i class="fas fa-lock"></i> Checkout blocked</button>
            <?php else: ?>
                <?php if ($collect > 0): ?>
                <div class="mt-3 rounded-xl bg-amber-50 border border-amber-200 p-3.5">
                    <p class="text-[12px] text-amber-900 font-semibold leading-snug">
                        <i class="fas fa-id-card mr-1"></i>
                        Some verification details are still needed. You will fill them in on the next page.
                    </p>
                </div>
                <?php endif; ?>
                <a href="checkout.php" class="btn btn-go mt-4"><i class="fas fa-lock"></i> Proceed to checkout</a>
            <?php endif; ?>

            <a href="dashboard.php" class="block text-center mt-3 text-[12.5px] font-bold text-slate-400 hover:text-slate-700">
                <i class="fas fa-arrow-left"></i> Keep shopping
            </a>
        </div>
      </div>

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