<?php
// ─────────────────────────────────────────────────────────────
// TIMEZONE — always IST
// ─────────────────────────────────────────────────────────────
date_default_timezone_set('Asia/Kolkata');

include 'db_connect.php'; // provides $conn (mysqli) + enc() + dec()

// ─────────────────────────────────────────────────────────────
// DECRYPT ACCESS PARAMS
// ─────────────────────────────────────────────────────────────
$raw_source1 = trim($_GET['source1'] ?? ''); // encrypted employee mobile
$raw_source3 = trim($_GET['source3'] ?? ''); // encrypted store source_table_id

$access_mobile   = $raw_source1 ? dec($raw_source1) : '';
$access_store_id = $raw_source3 ? dec($raw_source3) : '';

if (empty($access_mobile) && empty($access_store_id)) {
    die("Invalid access link.");
}

// ─────────────────────────────────────────────────────────────
// DEFAULT DATE RANGE
// Before 5 PM IST → Yesterday, After 5 PM → Today
// ─────────────────────────────────────────────────────────────
$currentHour = (int)date('H');
$defaultRange = ($currentHour < 17) ? 'yesterday' : 'today';

$range     = $_GET['range']     ?? $defaultRange;
$dateFrom  = $_GET['date_from'] ?? '';
$dateTo    = $_GET['date_to']   ?? '';
$storeFilter = $_GET['store']   ?? '';

// Resolve actual FROM/TO dates
switch ($range) {
    case 'today':
        $dateFrom = $dateTo = date('Y-m-d');
        break;
    case 'yesterday':
        $dateFrom = $dateTo = date('Y-m-d', strtotime('-1 day'));
        break;
    case 'this_week':
        $dateFrom = date('Y-m-d', strtotime('monday this week'));
        $dateTo   = date('Y-m-d');
        break;
    case 'this_month':
        $dateFrom = date('Y-m-01');
        $dateTo   = date('Y-m-d');
        break;
    case 'custom':
        // keep dateFrom / dateTo from GET
        if (empty($dateFrom)) $dateFrom = date('Y-m-d');
        if (empty($dateTo))   $dateTo   = date('Y-m-d');
        break;
    default:
        $dateFrom = $dateTo = date('Y-m-d', strtotime('-1 day'));
}

$dtFrom = $dateFrom . ' 00:00:00';
$dtTo   = $dateTo   . ' 23:59:59';

// ─────────────────────────────────────────────────────────────
// FIND ACCESSIBLE STORES
// ─────────────────────────────────────────────────────────────
$accessibleStores = []; // [ ['source_table_id'=>x, 'title'=>y, 'sap_code'=>z, 'uid'=>w, 'address'=>a, 'city'=>c], ... ]

if (!empty($access_store_id)) {
    // Direct store access via source3
    $sql = "
        SELECT ss.source_table_id, ss.title, ss.address, ss.city, ss.state,
               dm.sap_code, dm.website_id AS uid
        FROM showroom_store ss
        LEFT JOIN dc_dealer_master dm ON dm.website_id = ss.website_id
        WHERE ss.source_table_id = ?
          AND ss.deleted_at IS NULL
        LIMIT 1
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $access_store_id);
    $stmt->execute();
    $r = $stmt->get_result()->fetch_assoc();
    if ($r) $accessibleStores[] = $r;

} else {
    // Employee mobile access via source1
    // Check showroom_users.phone first, then emp_users.mobile1
    $sql = "
        SELECT DISTINCT ss.source_table_id, ss.title, ss.address, ss.city, ss.state,
               dm.sap_code, dm.website_id AS uid
        FROM showroom_users su
        JOIN showroom_store_user ssu ON ssu.user_id = su.source_table_id
        JOIN showroom_store ss ON ss.source_table_id = ssu.store_id
        LEFT JOIN dc_dealer_master dm ON dm.website_id = ss.website_id
        WHERE su.phone = ?
          AND su.deleted_at IS NULL
          AND ss.deleted_at IS NULL
          AND ss.dealertype IS NULL
          AND ss.website_id > 0
        ORDER BY ss.title ASC
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $access_mobile);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($r = $res->fetch_assoc()) $accessibleStores[] = $r;

    // Also check emp_users mapping via dealer_employee_website_mapping
    if (empty($accessibleStores)) {
        $sql2 = "
            SELECT DISTINCT ss.source_table_id, ss.title, ss.address, ss.city, ss.state,
                   dm.sap_code, dm.website_id AS uid
            FROM emp_users eu
            JOIN dealer_employee_website_mapping dwm ON dwm.emp_code = eu.emp_code
            JOIN showroom_store ss ON ss.website_id = dwm.website_id
            LEFT JOIN dc_dealer_master dm ON dm.website_id = ss.website_id
            WHERE eu.mobile1 = ?
              AND eu.status = 1
              AND ss.deleted_at IS NULL
              AND ss.dealertype IS NULL
              AND ss.website_id > 0
            ORDER BY ss.title ASC
        ";
        $stmt2 = $conn->prepare($sql2);
        $stmt2->bind_param("s", $access_mobile);
        $stmt2->execute();
        $res2 = $stmt2->get_result();
        while ($r = $res2->fetch_assoc()) $accessibleStores[] = $r;
    }
}

if (empty($accessibleStores)) {
    die("No store access found for this link.");
}

// ─────────────────────────────────────────────────────────────
// STORE FILTER (when user has multiple stores)
// ─────────────────────────────────────────────────────────────
$multiStore = count($accessibleStores) > 1;

if ($multiStore && !empty($storeFilter)) {
    $filteredStores = array_filter($accessibleStores, fn($s) => $s['source_table_id'] == $storeFilter);
    $activeStores   = !empty($filteredStores) ? array_values($filteredStores) : $accessibleStores;
} else {
    $activeStores = $accessibleStores;
}

// Store IDs for SQL IN clause
$storeIds    = array_column($activeStores, 'source_table_id');
$storeInList = implode(',', array_map('intval', $storeIds));

// Current store info for header (first/only store)
$currentStore = $activeStores[0];

// ─────────────────────────────────────────────────────────────
// HELPER: run a query and return result
// ─────────────────────────────────────────────────────────────
function q($conn, $sql, $types = '', $params = []) {
    if ($types && $params) {
        $stmt = $conn->prepare($sql);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        return $stmt->get_result();
    }
    return $conn->query($sql);
}

function pct($val, $total) {
    if (!$total) return '0.0%';
    return number_format($val / $total * 100, 1) . '%';
}

// ─────────────────────────────────────────────────────────────
// METRIC 1: Total Walk-ins
// COUNT DISTINCT customers with order.status=1 in date range
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT COUNT(DISTINCT sc.source_table_id) AS cnt
    FROM showroom_customer sc
    JOIN showroom_order so
        ON so.customer_id = sc.source_table_id
        AND so.store_id = sc.store_id
        AND so.status = 1
        AND so.created_at BETWEEN ? AND ?
    WHERE sc.store_id IN ($storeInList)
      AND sc.deleted_at IS NULL
";
$totalWalkins = (int)q($conn, $sql, 'ss', [$dtFrom, $dtTo])->fetch_assoc()['cnt'];

// ─────────────────────────────────────────────────────────────
// METRIC 2: Projects & Retails
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT sc.type, COUNT(DISTINCT sc.source_table_id) AS cnt
    FROM showroom_customer sc
    JOIN showroom_order so
        ON so.customer_id = sc.source_table_id
        AND so.store_id = sc.store_id
        AND so.status = 1
        AND so.created_at BETWEEN ? AND ?
    WHERE sc.store_id IN ($storeInList)
      AND sc.deleted_at IS NULL
    GROUP BY sc.type
";
$res = q($conn, $sql, 'ss', [$dtFrom, $dtTo]);
$projects = 0; $retails = 0;
while ($r = $res->fetch_assoc()) {
    if (strtolower($r['type']) === 'project')  $projects = (int)$r['cnt'];
    if (strtolower($r['type']) === 'retailer') $retails  = (int)$r['cnt'];
}

// ─────────────────────────────────────────────────────────────
// METRIC 3: Look & Feel — tblenquiry_app.lead_visit = 1
// Match store via showroom_store.source_table_id → store_code or user_id
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT COUNT(DISTINCT ta.source_table_id) AS cnt
    FROM showroom_tblenquiry_app ta
    JOIN showroom_store ss ON ss.source_table_id IN ($storeInList)
    WHERE ta.lead_visit = 1
      AND ta.deleted_at IS NULL
      AND ta.created_at BETWEEN ? AND ?
      AND ta.store_code = ss.web_id
";
$lookAndFeel = (int)q($conn, $sql, 'ss', [$dtFrom, $dtTo])->fetch_assoc()['cnt'];

// ─────────────────────────────────────────────────────────────
// METRIC 4: Repeat Clients
// Customers in date range whose mobile ALSO appears in same store
// OUTSIDE the selected date range
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT COUNT(DISTINCT sc.mobile) AS cnt
    FROM showroom_customer sc
    JOIN showroom_order so
        ON so.customer_id = sc.source_table_id
        AND so.store_id = sc.store_id
        AND so.status = 1
        AND so.created_at BETWEEN ? AND ?
    WHERE sc.store_id IN ($storeInList)
      AND sc.deleted_at IS NULL
      AND EXISTS (
          SELECT 1
          FROM showroom_customer sc2
          JOIN showroom_order so2
              ON so2.customer_id = sc2.source_table_id
              AND so2.store_id = sc2.store_id
              AND so2.status = 1
          WHERE sc2.mobile = sc.mobile
            AND sc2.store_id IN ($storeInList)
            AND sc2.deleted_at IS NULL
            AND (so2.created_at < ? OR so2.created_at > ?)
      )
";
$repeatClients = (int)q($conn, $sql, 'ssss', [$dtFrom, $dtTo, $dtFrom, $dtTo])->fetch_assoc()['cnt'];

// ─────────────────────────────────────────────────────────────
// METRIC 5: Outstation Clients (customer_status = 1)
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT COUNT(DISTINCT sc.source_table_id) AS cnt
    FROM showroom_customer sc
    JOIN showroom_order so
        ON so.customer_id = sc.source_table_id
        AND so.store_id = sc.store_id
        AND so.status = 1
        AND so.created_at BETWEEN ? AND ?
    WHERE sc.store_id IN ($storeInList)
      AND sc.deleted_at IS NULL
      AND sc.customer_status = 1
";
$outstation = (int)q($conn, $sql, 'ss', [$dtFrom, $dtTo])->fetch_assoc()['cnt'];

// ─────────────────────────────────────────────────────────────
// METRIC 6: Interested in Kerovit (order.referrd_to_kerovit = 1)
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT COUNT(DISTINCT so.customer_id) AS cnt
    FROM showroom_order so
    WHERE so.store_id IN ($storeInList)
      AND so.status = 1
      AND so.referrd_to_kerovit = 1
      AND so.created_at BETWEEN ? AND ?
";
$kerovit = (int)q($conn, $sql, 'ss', [$dtFrom, $dtTo])->fetch_assoc()['cnt'];

// ─────────────────────────────────────────────────────────────
// METRIC 7: Total Quantity (sq.mtrs)
// AVG qty per order (since order_final has multiple rows per order)
// then sum across all orders * 0.092903
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT COALESCE(SUM(avg_qty), 0) AS total_qty
    FROM (
        SELECT AVG(of2.qty) AS avg_qty
        FROM showroom_order so
        JOIN showroom_order_final of2 ON of2.order_id = so.source_table_id
        WHERE so.store_id IN ($storeInList)
          AND so.status = 1
          AND so.created_at BETWEEN ? AND ?
        GROUP BY so.source_table_id
    ) t
";
$rawQty   = (float)q($conn, $sql, 'ss', [$dtFrom, $dtTo])->fetch_assoc()['total_qty'];
$totalQty = number_format($rawQty * 0.092903, 0);

// ─────────────────────────────────────────────────────────────
// SECTION: Referred to Sales Team
// showroom_customer.referred_by → showroom_users.source_table_id
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT su.name, COUNT(DISTINCT sc.source_table_id) AS cnt
    FROM showroom_customer sc
    JOIN showroom_order so
        ON so.customer_id = sc.source_table_id
        AND so.store_id = sc.store_id
        AND so.status = 1
        AND so.created_at BETWEEN ? AND ?
    JOIN showroom_users su ON su.source_table_id = sc.referred_by
    WHERE sc.store_id IN ($storeInList)
      AND sc.deleted_at IS NULL
      AND sc.referred_by IS NOT NULL
    GROUP BY sc.referred_by, su.name
    ORDER BY cnt DESC
";
$referredRows = q($conn, $sql, 'ss', [$dtFrom, $dtTo])->fetch_all(MYSQLI_ASSOC);

// ─────────────────────────────────────────────────────────────
// SECTION: Attended by Employee
// showroom_customer.user_id → showroom_users.source_table_id
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT su.name, COUNT(DISTINCT sc.source_table_id) AS cnt
    FROM showroom_customer sc
    JOIN showroom_order so
        ON so.customer_id = sc.source_table_id
        AND so.store_id = sc.store_id
        AND so.status = 1
        AND so.created_at BETWEEN ? AND ?
    JOIN showroom_users su ON su.source_table_id = sc.user_id
    WHERE sc.store_id IN ($storeInList)
      AND sc.deleted_at IS NULL
    GROUP BY sc.user_id, su.name
    ORDER BY cnt DESC
";
$attendedRows = q($conn, $sql, 'ss', [$dtFrom, $dtTo])->fetch_all(MYSQLI_ASSOC);

// ─────────────────────────────────────────────────────────────
// SECTION: Clients' Profession
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT COALESCE(sc.profession, 'Not Specified') AS profession,
           COUNT(DISTINCT sc.source_table_id) AS cnt
    FROM showroom_customer sc
    JOIN showroom_order so
        ON so.customer_id = sc.source_table_id
        AND so.store_id = sc.store_id
        AND so.status = 1
        AND so.created_at BETWEEN ? AND ?
    WHERE sc.store_id IN ($storeInList)
      AND sc.deleted_at IS NULL
    GROUP BY sc.profession
    ORDER BY cnt DESC
";
$professionRows = q($conn, $sql, 'ss', [$dtFrom, $dtTo])->fetch_all(MYSQLI_ASSOC);

// ─────────────────────────────────────────────────────────────
// SECTION: Clients' from Reference
// referral_type IS NOT NULL (old records may be NULL)
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT COALESCE(sc.referral_type, 'Other') AS ref_type,
           COUNT(DISTINCT sc.source_table_id) AS cnt
    FROM showroom_customer sc
    JOIN showroom_order so
        ON so.customer_id = sc.source_table_id
        AND so.store_id = sc.store_id
        AND so.status = 1
        AND so.created_at BETWEEN ? AND ?
    WHERE sc.store_id IN ($storeInList)
      AND sc.deleted_at IS NULL
      AND sc.referral_type IS NOT NULL
    GROUP BY sc.referral_type
    ORDER BY cnt DESC
";
$referenceRows = q($conn, $sql, 'ss', [$dtFrom, $dtTo])->fetch_all(MYSQLI_ASSOC);
$totalReference = array_sum(array_column($referenceRows, 'cnt'));

// ─────────────────────────────────────────────────────────────
// SECTION: Client Source
// NULL = Walk-in, otherwise use value from DB
// ─────────────────────────────────────────────────────────────
$sql = "
    SELECT COALESCE(sc.source, 'Walk-in') AS src,
           COUNT(DISTINCT sc.source_table_id) AS cnt
    FROM showroom_customer sc
    JOIN showroom_order so
        ON so.customer_id = sc.source_table_id
        AND so.store_id = sc.store_id
        AND so.status = 1
        AND so.created_at BETWEEN ? AND ?
    WHERE sc.store_id IN ($storeInList)
      AND sc.deleted_at IS NULL
    GROUP BY sc.source
    ORDER BY cnt DESC
";
$sourceRows = q($conn, $sql, 'ss', [$dtFrom, $dtTo])->fetch_all(MYSQLI_ASSOC);

// ─────────────────────────────────────────────────────────────
// Helper: render a horizontal scroll section of person cards
// ─────────────────────────────────────────────────────────────
function renderCards(array $rows, int $total, string $nameKey = 'name'): string
{
    if (empty($rows)) {
        return '<div class="text-secondary small ps-1">No data for selected period.</div>';
    }
    $html = '<div class="walkin-row">';
    foreach ($rows as $r) {
        $name  = htmlspecialchars($r[$nameKey] ?? 'Unknown');
        $cnt   = (int)$r['cnt'];
        $pct   = $total ? number_format($cnt / $total * 100, 1) : 0;
        $init  = mb_strtoupper(mb_substr($name, 0, 1));
        $html .= "
        <div class='walkin-col'>
            <div class='glass p-3 text-center'>
                <div class='avatar'>{$init}</div>
                <div class='small'>{$name}</div>
                <div class='fs-2 fw-bold'>{$cnt}</div>
                <div class='sub'>({$pct}%)</div>
            </div>
        </div>";
    }
    $html .= '</div>';
    return $html;
}

function renderCategoryCards(array $rows, int $total, string $labelKey): string
{
    if (empty($rows)) {
        return '<div class="text-secondary small ps-1">No data for selected period.</div>';
    }
    $html = '<div class="walkin-row">';
    foreach ($rows as $r) {
        $label = htmlspecialchars($r[$labelKey] ?? 'Unknown');
        $cnt   = (int)$r['cnt'];
        $pct   = $total ? number_format($cnt / $total * 100, 1) : 0;
        $init  = mb_strtoupper(mb_substr($label, 0, 1));
        $html .= "
        <div class='walkin-col'>
            <div class='glass p-3 text-center'>
                <div class='avatar'>{$init}</div>
                <div class='small'>{$label}</div>
                <div class='fs-2 fw-bold'>{$cnt}</div>
                <div class='sub'>({$pct}%)</div>
            </div>
        </div>";
    }
    $html .= '</div>';
    return $html;
}

// Build query string to preserve access params on filter changes
$accessParam = $raw_source1 ? "source1={$raw_source1}" : "source3={$raw_source3}";

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Showroom Walk-in Report</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body { background:radial-gradient(circle at top,#1d2740,#0b0d13 60%); color:#fff; font-family:Arial,sans-serif; padding-bottom:30px; }
        .wrap { max-width:760px; margin:auto; padding:18px; }
        .glass { background:linear-gradient(180deg,#1a1f2cbf,#131722f7); border:1px solid #3a3f4d; border-radius:18px; box-shadow:0 8px 30px rgba(0,0,0,.35); }
        .metric { font-size:2.8rem; font-weight:700; line-height:1; }
        .sub { color:#aeb5c4; font-size:.88rem; }
        .form-control,.form-select { background:#0f1320 !important; color:#fff !important; border-color:#414758 !important; }
        .icon { width:54px; height:54px; border-radius:50%; display:flex; align-items:center; justify-content:center; background:#3a2d0b; color:#ffc83d; font-size:24px; }
        .avatar { width:52px; height:52px; border-radius:50%; background:#6f42c1; display:flex; align-items:center; justify-content:center; margin:0 auto 8px; font-size:22px; }
        .walkin-row { display:flex; gap:12px; overflow-x:auto; -webkit-overflow-scrolling:touch; scroll-snap-type:x proximity; padding-bottom:8px; margin-top:.5rem; }
        .walkin-row::-webkit-scrollbar { height:6px; }
        .walkin-row::-webkit-scrollbar-thumb { background:#414758; border-radius:3px; }
        .walkin-col { flex:0 0 42%; scroll-snap-align:start; }
        input[type="date"] { cursor:pointer; }
        input[type="date"]::-webkit-calendar-picker-indicator { cursor:pointer; }
        @media(min-width:768px) { .walkin-row { overflow-x:visible; flex-wrap:wrap; } .walkin-col { flex:1 1 0; min-width:130px; } }
        .section-title { display:flex; justify-content:space-between; align-items:center; margin-bottom:4px; }
        .btn-filter { background:#ffc83d; border:none; color:#000; font-weight:600; padding:6px 16px; border-radius:8px; }
        .btn-filter:hover { background:#e6b200; }
    </style>
</head>
<body>
<div class="wrap">

    <!-- ── Header ───────────────────────────────────────────── -->
    <div class="d-flex justify-content-between align-items-start mb-3">
        <div>
            <h2 class="mb-0">Showroom Walk-in Report</h2>
            <div style="color:#eee;font-size:14px;">
                <?= htmlspecialchars($currentStore['title'] ?? '') ?>
                <?php if (!empty($currentStore['city'])): ?>
                    — <?= htmlspecialchars($currentStore['city']) ?>, <?= htmlspecialchars($currentStore['state'] ?? '') ?>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- ── Filters ──────────────────────────────────────────── -->
    <form method="GET" id="filterForm">
        <input type="hidden" name="<?= $raw_source1 ? 'source1' : 'source3' ?>"
               value="<?= htmlspecialchars($raw_source1 ?: $raw_source3) ?>">

        <div class="row g-3 mb-3">

            <!-- Store selector (only shown if multi-store access) -->
            <?php if ($multiStore): ?>
            <div class="col-12">
                <div class="glass p-3">
                    <div class="small text-secondary mb-2">Showroom</div>
                    <select name="store" class="form-select" onchange="document.getElementById('filterForm').submit()">
                        <option value="">All Stores (Combined)</option>
                        <?php foreach ($accessibleStores as $s): ?>
                            <option value="<?= $s['source_table_id'] ?>"
                                <?= ($storeFilter == $s['source_table_id']) ? 'selected' : '' ?>>
                                <?= htmlspecialchars($s['title']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <?php endif; ?>

            <!-- Store info card -->
            <div class="col-md-6">
                <div class="glass p-3 h-100">
                    <div class="small text-secondary mb-2">Store Details</div>
                    <div class="row text-center">
                        <div class="col border-end">
                            <div class="sub">SAP Code</div>
                            <div class="text-warning fs-5 fw-bold">
                                <?= htmlspecialchars($currentStore['sap_code'] ?? '—') ?>
                            </div>
                        </div>
                        <div class="col">
                            <div class="sub">UID</div>
                            <div class="text-warning fs-5 fw-bold">
                                <?= htmlspecialchars($currentStore['uid'] ?? '—') ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Date range selector -->
            <div class="col-md-6">
                <div class="glass p-3">
                    <div class="small text-secondary mb-1">Date Range</div>
                    <select name="range" class="form-select mb-2" id="dateRangeSelect"
                            onchange="toggleCustomRange(); document.getElementById('filterForm').submit()">
                        <option value="today"      <?= $range==='today'      ? 'selected':'' ?>>Today</option>
                        <option value="yesterday"  <?= $range==='yesterday'  ? 'selected':'' ?>>Yesterday</option>
                        <option value="this_week"  <?= $range==='this_week'  ? 'selected':'' ?>>This Week</option>
                        <option value="this_month" <?= $range==='this_month' ? 'selected':'' ?>>This Month</option>
                        <option value="custom"     <?= $range==='custom'     ? 'selected':'' ?>>Custom Range</option>
                    </select>
                    <div id="customRangeRow" class="row g-2"
                         style="display:<?= $range==='custom' ? 'flex' : 'none' ?>">
                        <div class="col">
                            <label class="sub d-block mb-1">From</label>
                            <input type="date" name="date_from" class="form-control"
                                   value="<?= htmlspecialchars($dateFrom) ?>">
                        </div>
                        <div class="col">
                            <label class="sub d-block mb-1">To</label>
                            <input type="date" name="date_to" class="form-control"
                                   value="<?= htmlspecialchars($dateTo) ?>">
                        </div>
                        <div class="col-12">
                            <button type="submit" class="btn btn-filter w-100">Apply</button>
                        </div>
                    </div>
                    <div class="sub mt-1">
                        <?= date('d M Y', strtotime($dateFrom)) ?>
                        <?= ($dateFrom !== $dateTo) ? ' – ' . date('d M Y', strtotime($dateTo)) : '' ?>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <div class="row g-3">

        <!-- Total Quantity -->
        <div class="col-6">
            <div class="glass p-3 h-100">
                <div class="d-flex gap-3">
                    <div class="icon"><i class="bi bi-layers"></i></div>
                    <div>
                        <div>Total Quantity</div>
                        <div class="metric"><?= $totalQty ?></div>
                        <div class="sub">(sq.mtrs.)</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Total Walk-ins -->
        <div class="col-6">
            <div class="glass p-3 h-100">
                <div class="d-flex gap-3">
                    <div class="icon"><i class="bi bi-people-fill"></i></div>
                    <div>
                        <div>Total Walk-ins</div>
                        <div class="metric"><?= $totalWalkins ?></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Projects -->
        <div class="col-6">
            <div class="glass p-3 h-100">
                <div class="d-flex gap-3">
                    <div class="icon"><i class="bi bi-building"></i></div>
                    <div>
                        <div>Projects</div>
                        <div class="metric"><?= $projects ?></div>
                        <div class="sub"><?= pct($projects, $totalWalkins) ?> of Walk-ins</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Retails -->
        <div class="col-6">
            <div class="glass p-3 h-100">
                <div class="d-flex gap-3">
                    <div class="icon"><i class="bi bi-shop"></i></div>
                    <div>
                        <div>Retails</div>
                        <div class="metric"><?= $retails ?></div>
                        <div class="sub"><?= pct($retails, $totalWalkins) ?> of Walk-ins</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Look & Feel -->
        <div class="col-6">
            <div class="glass p-3 h-100">
                <div class="d-flex gap-3">
                    <div class="icon"><i class="bi bi-palette2"></i></div>
                    <div>
                        <div>Look and Feel</div>
                        <div class="metric"><?= $lookAndFeel ?></div>
                        <div class="sub"><?= pct($lookAndFeel, $totalWalkins) ?> of Walk-ins</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Repeat Clients -->
        <div class="col-6">
            <div class="glass p-3 h-100">
                <div class="d-flex gap-3">
                    <div class="icon"><i class="bi bi-arrow-repeat"></i></div>
                    <div>
                        <div>Repeat Clients</div>
                        <div class="metric"><?= $repeatClients ?></div>
                        <div class="sub"><?= pct($repeatClients, $totalWalkins) ?> of Walk-ins</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Referred to Sales Team -->
        <div class="col-12">
            <div class="glass p-3">
                <div class="section-title">
                    <strong>Referred to Sales Team</strong>
                </div>
                <?= renderCards($referredRows, $totalWalkins) ?>
            </div>
        </div>

        <!-- Attended by Employee -->
        <div class="col-12">
            <div class="glass p-3">
                <div class="section-title">
                    <strong>Attended by Employee</strong>
                </div>
                <?= renderCards($attendedRows, $totalWalkins) ?>
            </div>
        </div>

        <!-- Clients' Profession -->
        <div class="col-12">
            <div class="glass p-3">
                <div class="section-title">
                    <strong>Clients' Profession</strong>
                </div>
                <?= renderCategoryCards($professionRows, $totalWalkins, 'profession') ?>
            </div>
        </div>

        <!-- Clients' from Reference -->
        <div class="col-12">
            <div class="glass p-3">
                <div class="section-title">
                    <strong>Clients' from Reference</strong>
                    <span class="sub"><?= $totalReference ?> total</span>
                </div>
                <?= renderCategoryCards($referenceRows, $totalWalkins, 'ref_type') ?>
            </div>
        </div>

        <!-- Client Source -->
        <div class="col-12">
            <div class="glass p-3">
                <div class="section-title">
                    <strong>Client Source</strong>
                </div>
                <?= renderCategoryCards($sourceRows, $totalWalkins, 'src') ?>
            </div>
        </div>

        <!-- Outstation Clients -->
        <div class="col-6 col-md-6">
            <div class="glass p-3 text-center h-100">
                <div>Outstation Clients</div>
                <div class="metric" style="font-size:2rem"><?= $outstation ?></div>
                <div class="sub"><?= pct($outstation, $totalWalkins) ?></div>
            </div>
        </div>

        <!-- Interested in Kerovit -->
        <div class="col-6 col-md-6">
            <div class="glass p-3 text-center h-100">
                <div>Interested in Kerovit</div>
                <div class="metric" style="font-size:2rem"><?= $kerovit ?></div>
                <div class="sub"><?= pct($kerovit, $totalWalkins) ?></div>
            </div>
        </div>

    </div>
</div>

<script>
    function toggleCustomRange() {
        const v = document.getElementById('dateRangeSelect').value;
        document.getElementById('customRangeRow').style.display = (v === 'custom') ? 'flex' : 'none';
    }
    document.querySelectorAll('input[type="date"]').forEach(function(input) {
        input.addEventListener('click', function() {
            if (typeof this.showPicker === 'function') {
                try { this.showPicker(); } catch(e) {}
            }
        });
    });
</script>
</body>
</html>
