<?php
use App\Core\Auth;
use App\Core\PosService;
$user = current_user();
$vendorId = $vendorId ?? PosService::currentVendorId();
$register = $register ?? PosService::defaultRegister($vendorId);
$shift = $shift ?? ($register ? PosService::currentShift((int)$register['id'], (int)($user['id'] ?? 0)) : null);
$pageTitle = $pageTitle ?? 'Pro POS | ' . APP_NAME;
$adminPosVendors = PosService::approvedVendors();
$posLink = static function(string $path) use ($vendorId): string {
    $separator = str_contains($path, '?') ? '&' : '?';
    return url($path . ((int)$vendorId > 0 ? $separator . 'vendor_id=' . (int)$vendorId : ''));
};
$dashboardLink = match ((string)Auth::role()) {
    'admin','staff' => url('admin/index.php'),
    'vendor' => url('vendor/index.php'),
    default => url('pos/register.php'),
};
$currentPosFile = basename((string)(parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?: ''));
$posGroups = [
    'Overview' => [
        ['index.php', 'POS Dashboard', 'bi-speedometer2'],
    ],
    'Sales' => [
        ['register.php', 'Sell / Register', 'bi-cart-check'],
        ['held.php', 'Held Sales', 'bi-pause-circle'],
    ],
    'Operations' => [
        ['shifts.php', 'Open / Close Shift', 'bi-clock-history'],
        ['refunds.php', 'Returns / Refunds', 'bi-arrow-counterclockwise'],
        ['print-labels.php', 'Barcode Labels', 'bi-upc-scan'],
    ],
    'Reports & Settings' => [
        ['reports.php', 'X/Z Reports', 'bi-bar-chart-line'],
        ['settings.php', 'POS Settings', 'bi-sliders'],
    ],
];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#0B5FFF">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="Purchase Haat POS">
<title><?= e($pageTitle) ?></title>
<link rel="manifest" href="<?= url('public/manifest.php') ?>">
<link rel="icon" href="<?= asset('brand/favicon.svg') ?>">
<link rel="stylesheet" href="<?= admin_asset('css/bootstrap.min.css') ?>">
<link rel="stylesheet" href="<?= asset('css/bootstrap-icons.min.css') ?>">
<link rel="stylesheet" href="<?= asset('css/purchase-haat.css') ?>">
<link rel="stylesheet" href="<?= asset('css/pos.css') ?>">
</head>
<body class="pos-body">
<header class="pos-topbar">
  <div class="d-flex align-items-center gap-2 min-w-0">
    <button class="btn btn-sm btn-light pos-nav-toggle d-lg-none" type="button" data-pos-toggle-nav aria-label="Open POS navigation"><i class="bi bi-list"></i></button>
    <a class="pos-brand" href="<?= $posLink('pos/index.php') ?>"><img src="<?= asset('brand/logo.png') ?>" alt="<?= e(BRAND_NAME) ?>" height="38"></a>
    <span class="pos-mode-badge d-none d-sm-inline-flex"><i class="bi bi-receipt-cutoff"></i> Pro POS</span>
  </div>
  <div class="pos-topbar-actions">
    <?php if ($adminPosVendors): ?>
    <label class="pos-vendor-switch d-none d-md-flex"><i class="bi bi-shop"></i><select class="form-select form-select-sm" aria-label="POS vendor" onchange="const u=new URL(location.href);u.searchParams.set('vendor_id',this.value);location.href=u.toString()">
      <?php foreach($adminPosVendors as $posVendor): ?><option value="<?= (int)$posVendor['id'] ?>" <?= (int)$vendorId===(int)$posVendor['id']?'selected':'' ?>><?= e($posVendor['shop_name']) ?></option><?php endforeach; ?>
    </select></label>
    <?php endif; ?>
    <span class="pos-status-pill d-none d-xl-inline-flex"><i class="bi bi-display"></i><?= e($register['name'] ?? 'No register') ?></span>
    <span class="pos-status-pill <?= $shift ? 'is-open' : 'is-closed' ?> d-none d-lg-inline-flex"><i class="bi bi-circle-fill"></i><?= $shift ? 'Shift Open' : 'Shift Closed' ?></span>
    <a class="btn btn-sm btn-outline-light d-none d-md-inline-flex align-items-center gap-1" href="<?= $dashboardLink ?>"><i class="bi bi-speedometer2"></i> Dashboard</a>
    <div class="dropdown">
      <button class="btn btn-sm btn-light pos-user-button" type="button" data-bs-toggle="dropdown" aria-expanded="false"><span><?= e(strtoupper(substr((string)($user['name'] ?? 'U'),0,1))) ?></span><i class="bi bi-chevron-down"></i></button>
      <div class="dropdown-menu dropdown-menu-end pos-user-dropdown">
        <div class="px-3 py-2"><strong class="d-block small"><?= e($user['name'] ?? 'POS User') ?></strong><small class="text-muted"><?= e($user['email'] ?? '') ?></small></div>
        <div class="dropdown-divider"></div>
        <a class="dropdown-item" href="<?= $dashboardLink ?>"><i class="bi bi-speedometer2 me-2"></i>Dashboard</a>
        <form method="post" action="<?= url('public/logout.php') ?>"><?= csrf_field() ?><button class="dropdown-item text-danger" type="submit"><i class="bi bi-box-arrow-right me-2"></i>Logout</button></form>
      </div>
    </div>
  </div>
</header>
<div class="pos-shell">
<aside class="pos-nav" id="posNav">
  <div class="pos-nav-head">
    <span><strong>POS Navigation</strong><small><?= e($register['name'] ?? 'Select a register') ?></small></span>
    <button class="btn btn-sm btn-light d-lg-none" type="button" data-pos-toggle-nav aria-label="Close POS navigation"><i class="bi bi-x-lg"></i></button>
  </div>
  <?php if ($adminPosVendors): ?>
  <label class="pos-mobile-vendor d-md-none"><span>Vendor</span><select class="form-select form-select-sm" onchange="const u=new URL(location.href);u.searchParams.set('vendor_id',this.value);location.href=u.toString()">
    <?php foreach($adminPosVendors as $posVendor): ?><option value="<?= (int)$posVendor['id'] ?>" <?= (int)$vendorId===(int)$posVendor['id']?'selected':'' ?>><?= e($posVendor['shop_name']) ?></option><?php endforeach; ?>
  </select></label>
  <?php endif; ?>
  <nav class="pos-nav-groups">
    <?php foreach ($posGroups as $group => $links):
      $isGroupActive = false;
      foreach ($links as $link) if ($link[0] === $currentPosFile) { $isGroupActive = true; break; }
    ?>
      <details class="pos-nav-group" <?= $isGroupActive ? 'open' : '' ?>>
        <summary><span><?= e($group) ?></span><i class="bi bi-chevron-down"></i></summary>
        <div class="pos-nav-group-links">
          <?php foreach ($links as $link): $isActive = $link[0] === $currentPosFile; ?>
            <a class="<?= $isActive ? 'active' : '' ?>" href="<?= $posLink('pos/'.$link[0]) ?>" <?= $isActive ? 'aria-current="page"' : '' ?>><i class="bi <?= e($link[2]) ?>"></i><span><?= e($link[1]) ?></span></a>
          <?php endforeach; ?>
        </div>
      </details>
    <?php endforeach; ?>
    <details class="pos-nav-group" open>
      <summary><span>Management</span><i class="bi bi-chevron-down"></i></summary>
      <div class="pos-nav-group-links">
        <?php if (Auth::role()==='vendor'): ?><a href="<?= url('vendor/products.php') ?>"><i class="bi bi-box-seam"></i><span>Products</span></a><a href="<?= url('vendor/orders.php') ?>"><i class="bi bi-bag-check"></i><span>Orders</span></a><?php endif; ?>
        <?php if (in_array(Auth::role(),['admin','staff'],true)): ?><a href="<?= url('admin/products.php') ?>"><i class="bi bi-box-seam"></i><span>Products</span></a><a href="<?= url('admin/orders.php') ?>"><i class="bi bi-bag-check"></i><span>Orders</span></a><?php endif; ?>
      </div>
    </details>
  </nav>
</aside>
<button class="pos-nav-overlay" type="button" data-pos-toggle-nav aria-label="Close POS navigation"></button>
<main class="pos-content">
<div class="pos-page-titlebar"><div><span class="pos-page-kicker">Smart Tech OMP</span><h1><?= e(preg_replace('/\s*\|.*$/', '', $pageTitle)) ?></h1></div><div class="pos-title-status d-lg-none"><?= $shift ? '<span class="text-success"><i class="bi bi-circle-fill"></i> Shift open</span>' : '<span class="text-warning"><i class="bi bi-circle-fill"></i> Shift closed</span>' ?></div></div>
<?php if($msg=flash('success')): ?><div class="alert alert-success pos-alert"><i class="bi bi-check-circle-fill"></i><span><?= e($msg) ?></span></div><?php endif; ?>
<?php if($msg=flash('error')): ?><div class="alert alert-danger pos-alert"><i class="bi bi-exclamation-triangle-fill"></i><span><?= e($msg) ?></span></div><?php endif; ?>
