<?php $title=__('orders.tablet_create_order', 'Odbiorca - Create Order'); ob_start(); ?>

<style>
  /* Bakery-themed color palette */
  :root {
    --bakery-primary: #d4a373;
    --bakery-secondary: #8b4513;
    --bakery-accent: #f4a460;
    --bakery-light: #faf6f1;
    --bakery-dark: #3e2723;
    --success-green: #28a745;
    --danger-red: #dc3545;
  }

  body { touch-action: manipulation; -webkit-tap-highlight-color: transparent; }

  .btn-circle { 
    width: 44px; 
    height: 44px; 
    padding: 0; 
    border-radius: 50%; 
    display: flex; 
    align-items: center; 
    justify-content: center; 
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); 
    background: white; 
    border: 2px solid #dee2e6;
    font-size: 18px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  }
  .btn-circle:hover { transform: scale(1.05); box-shadow: 0 4px 8px rgba(0,0,0,0.15); }
  .btn-circle:active { transform: scale(0.92); box-shadow: 0 1px 2px rgba(0,0,0,0.1); }
  .btn-circle.text-danger { border-color: var(--danger-red); }
  .btn-circle.text-danger:hover { background: #fff5f5; }
  .btn-circle.text-success { border-color: var(--success-green); }
  .btn-circle.text-success:hover { background: #f0fff4; }

  .product-card { 
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); 
    border: 3px solid transparent !important; 
    cursor: pointer;
    background: white;
    border-radius: 12px !important;
    overflow: hidden;
  }
  .product-card:hover { 
    transform: translateY(-4px); 
    box-shadow: 0 8px 20px rgba(0,0,0,0.12) !important;
  }
  .product-card.active { 
    border-color: var(--bakery-primary) !important; 
    background: linear-gradient(135deg, #fff9f0 0%, #ffffff 100%);
    box-shadow: 0 4px 12px rgba(212, 163, 115, 0.3) !important;
  }
  .product-card.active::before {
    content: '✓';
    position: absolute;
    top: 8px;
    right: 8px;
    width: 24px;
    height: 24px;
    background: var(--bakery-primary);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 14px;
    z-index: 10;
  }
  .product-card .card-body { position: relative; }

  .qty-input { 
    font-size: 20px !important; 
    font-weight: 700 !important;
    color: var(--bakery-secondary) !important;
  }
  .qty-input:focus { outline: none !important; box-shadow: none !important; }

  input[type=number]::-webkit-inner-spin-button, 
  input[type=number]::-webkit-outer-spin-button { 
    -webkit-appearance: none; 
    margin: 0; 
  }

  .form-floating > .form-control, 
  .form-floating > .form-select { 
    height: calc(3.5rem + 2px); 
    line-height: 1.25;
    border-radius: 8px;
    border: 2px solid #e0e0e0;
    transition: all 0.3s;
  }
  .form-floating > .form-control:focus,
  .form-floating > .form-select:focus {
    border-color: var(--bakery-primary);
    box-shadow: 0 0 0 0.2rem rgba(212, 163, 115, 0.15);
  }
  .form-floating > label { padding: 1rem 0.75rem; color: #6c757d; }

  .sticky-top { 
    background: linear-gradient(180deg, #ffffff 0%, #fafafa 100%);
    backdrop-filter: blur(10px);
  }

  .input-group-text { 
    background: transparent !important;
    border: 2px solid #e0e0e0;
    border-right: 0;
  }
  #productSearch {
    border: 2px solid #e0e0e0;
    border-left: 0;
    padding-left: 0;
    transition: all 0.3s;
  }
  #productSearch:focus {
    border-color: var(--bakery-primary);
    box-shadow: none;
  }
  #productSearch:focus + .input-group-text {
    border-color: var(--bakery-primary);
  }

  .fixed-bottom {
    background: linear-gradient(0deg, #ffffff 0%, #fafafa 100%);
    backdrop-filter: blur(20px);
    border-top: 3px solid var(--bakery-light) !important;
  }

  .btn-primary {
    background: linear-gradient(135deg, var(--bakery-primary) 0%, var(--bakery-accent) 100%);
    border: none;
    transition: all 0.3s;
    box-shadow: 0 4px 12px rgba(212, 163, 115, 0.3);
  }
  .btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(212, 163, 115, 0.4);
    background: linear-gradient(135deg, var(--bakery-accent) 0%, var(--bakery-primary) 100%);
  }
  .btn-primary:active {
    transform: translateY(0);
  }

  .text-primary { color: var(--bakery-primary) !important; }

  /* Animations */
  @keyframes fadeIn {
    from { opacity: 0; transform: translateY(10px); }
    to { opacity: 1; transform: translateY(0); }
  }
  .product-item { animation: fadeIn 0.3s ease-out; }

  /* Mobile optimizations */
  @media (max-width: 768px) {
    .btn-circle { width: 40px; height: 40px; font-size: 16px; }
    .product-card .card-title { font-size: 14px !important; }
    .qty-input { font-size: 18px !important; }
    .fixed-bottom .btn { font-size: 16px; padding: 12px 24px !important; }
    #totalItems { font-size: 1.5rem !important; }
  }

  /* Smooth scroll */
  .overflow-auto { scroll-behavior: smooth; -webkit-overflow-scrolling: touch; }

  /* Loading state */
  .product-card.loading { opacity: 0.6; pointer-events: none; }

  /* Category sections */
  .category-section { 
    background: white; 
    border-radius: 12px; 
    padding: 20px; 
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }
  .category-header { 
    color: var(--bakery-secondary); 
    border-bottom: 3px solid var(--bakery-light);
    padding-bottom: 10px;
  }
  .category-header-container {
    user-select: none;
    transition: background 0.2s;
    padding: 8px;
    margin: -8px;
    border-radius: 8px;
  }
  .category-header-container:hover {
    background: rgba(212, 163, 115, 0.1);
  }
  .category-header-container:active {
    background: rgba(212, 163, 115, 0.2);
  }
  .category-toggle-icon {
    transition: transform 0.3s ease;
  }
  .category-section.collapsed .category-toggle-icon {
    transform: rotate(180deg);
  }
  .category-section.collapsed .category-products { display: none; }
  .category-section.collapsed .list-view { display: none; }

  /* List view */
  .list-view { margin-top: 1rem; }
  .list-group-item { 
    border: 2px solid #f0f0f0;
    border-radius: 8px !important;
    margin-bottom: 8px;
    transition: all 0.3s;
    position: relative;
  }
  .list-group-item:hover {
    border-color: var(--bakery-primary);
    background: #fafafa;
  }
  .list-group-item.active {
    border-color: var(--bakery-primary) !important;
    background: linear-gradient(135deg, #fff9f0 0%, #ffffff 100%);
  }
  .list-group-item.active::before {
    content: '✓';
    position: absolute;
    top: 50%;
    left: 8px;
    transform: translateY(-50%);
    width: 24px;
    height: 24px;
    background: var(--bakery-primary);
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 14px;
    z-index: 10;
  }
  .list-group-item.active {
       color: rgba(var(--bs-dark-rgb), var(--bs-text-opacity)) !important;
}
  .list-group-item.active .flex-grow-1 {
    margin-left: 32px;
  }
  .qty-input-list {
    border: 2px solid #dee2e6 !important;
    border-radius: 6px !important;
    font-size: 16px !important;
    font-weight: 700 !important;
    color: var(--bakery-secondary) !important;
  }

  /* Summary panel */
  .offcanvas-footer {
    position: sticky;
    bottom: 0;
    background: white;
    z-index: 10;
  }
  .summary-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px;
    border-bottom: 1px solid #f0f0f0;
    transition: background 0.3s;
  }
  .summary-item:hover { background: #fafafa; }
  .summary-item-name { font-weight: 600; color: var(--bakery-dark); }
  .summary-item-qty { 
    background: var(--bakery-light); 
    padding: 4px 12px; 
    border-radius: 20px;
    font-weight: 700;
    color: var(--bakery-secondary);
  }
  .summary-item-remove {
    color: var(--danger-red);
    cursor: pointer;
    padding: 4px 8px;
    border-radius: 50%;
    transition: all 0.2s;
  }
  .summary-item-remove:hover {
    background: #fff5f5;
    transform: scale(1.1);
  }

  /* View mode toggle */
  .btn-group .btn.active {
    background: var(--bakery-primary);
    color: white;
    border-color: var(--bakery-primary);
  }
  
  /* Filter button active state */
  #btnShowSelected.active {
    background: var(--bakery-primary);
    color: white;
    border-color: var(--bakery-primary);
  }
  
  /* Quick adjust floating menu */
  .quick-adjust-menu {
    position: fixed;
    background: white;
    border-radius: 50px;
    box-shadow: 0 8px 24px rgba(0,0,0,0.2);
    padding: 8px;
    z-index: 9999;
    display: none;
    opacity: 0;
    transform: translateX(-50%) scale(0.8);
    transition: opacity 0.2s ease-out, transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1);
  }
  .quick-adjust-menu.show {
    display: flex;
    gap: 4px;
    opacity: 1;
    transform: translateX(-50%) scale(1);
  }
  .quick-adjust-btn {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    border: 2px solid #dee2e6;
    background: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s;
    user-select: none;
  }
  .quick-adjust-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }
  .quick-adjust-btn:active {
    transform: scale(0.95);
  }
  .quick-adjust-btn.negative {
    color: var(--danger-red);
    border-color: var(--danger-red);
  }
  .quick-adjust-btn.negative:hover {
    background: #fff5f5;
  }
  .quick-adjust-btn.positive {
    color: var(--success-green);
    border-color: var(--success-green);
  }
  .quick-adjust-btn.positive:hover {
    background: #f0fff4;
  }
  
  /* Fix for sticky inside main container */
  body > main {
    overflow: visible !important;
  }
</style>

<div class="container-fluid p-0 bg-light min-vh-100">
  <!-- Header -->
  <div class="bg-white shadow-sm p-3">
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h1 class="h5 mb-0 text-primary fw-bold"><i class="fas fa-tablet-alt me-2"></i><?= __('orders.tablet_panel', 'Tablet Order') ?></h1>
      <a href="/samanta_crm/orders" class="btn btn-outline-secondary btn-sm rounded-circle" style="width: 32px; height: 32px; padding: 0; display: flex; align-items: center; justify-content: center;"><i class="fas fa-times"></i></a>
    </div>
    
    <form method="post" action="/samanta_crm/orders" id="tablet-order-form">
      <div class="row g-2">
        <div class="col-md-4 col-12">
          <div class="form-floating">
            <select name="customer_id" class="form-select" id="customerSelect" required>
              <option value=""><?= __('common.select', 'Select') ?>...</option>
              <?php foreach($customers as $c): ?><option value="<?=$c['id'];?>"><?=$c['name'];?></option><?php endforeach; ?>
            </select>
            <label for="customerSelect"><?= __('common.customer', 'Customer') ?></label>
          </div>
        </div>
        <div class="col-6 col-md-2">
          <div class="form-floating">
            <input type="date" name="order_date" value="<?=date('Y-m-d');?>" class="form-control" id="orderDate" required>
            <label for="orderDate"><?= __('orders.date', 'Date') ?></label>
          </div>
        </div>
        <div class="col-6 col-md-2">
          <div class="form-floating">
            <input type="date" name="delivery_date" value="<?=date('Y-m-d');?>" class="form-control" id="deliveryDate">
            <label for="deliveryDate"><?= __('orders.delivery', 'Delivery') ?></label>
          </div>
        </div>
        <div class="col-md-4 col-12">
          <div class="form-floating">
            <select name="assigned_user_id" id="assignedUser" class="form-select">
              <option value=""><?= __('common.select', 'Select') ?></option>
              <?php foreach($users as $u): ?><option value="<?=$u['id'];?>"><?=$u['name'];?></option><?php endforeach; ?>
            </select>
            <label for="assignedUser"><?= __('orders.assigned_to', 'Assigned To') ?></label>
          </div>
        </div>
        <div class="col-12">
          <div class="form-floating">
            <input type="text" name="notes" class="form-control" id="orderNotes" placeholder="Notes">
            <label for="orderNotes"><?= __('common.notes', 'Notes') ?></label>
          </div>
        </div>
      </div>
      <div id="hidden-items"></div>
    </form>
  </div>

  <!-- Search & Controls -->
  <div class="p-3 bg-white border-bottom position-sticky" style="z-index: 1015; top: 0;">
    <div class="row g-2 align-items-center">
      <div class="col-md-6 col-12">
        <div class="input-group">
          <span class="input-group-text bg-light border-end-0"><i class="fas fa-search text-muted"></i></span>
          <input type="text" id="productSearch" class="form-control border-start-0 bg-light" placeholder="<?= __('common.search_products', 'Search products...') ?>">
        </div>
      </div>
      <div class="col-md-6 col-12">
        <div class="d-flex gap-2 justify-content-end">
          <div class="btn-group btn-group-sm" role="group">
            <button type="button" class="btn btn-outline-secondary active fs-6" id="viewCards" onclick="switchView('cards')">
              <i class="fas fa-th"></i> <?= __('common.cards', 'Cards') ?>
            </button>
            <button type="button" class="btn btn-outline-secondary fs-6" id="viewList" onclick="switchView('list')">
              <i class="fas fa-list"></i> <?= __('common.list', 'List') ?>
            </button>
          </div>
          <button type="button" class="btn btn-sm btn-outline-secondary fs-6" id="btnShowSelected" onclick="toggleShowSelected()">
            <i class="fas fa-filter"></i> <?= __('common.selected', 'Selected') ?>
          </button>
          <button type="button" class="btn btn-sm btn-outline-primary fs-6" onclick="toggleSummary()">
            <i class="fas fa-shopping-cart"></i> <span class="badge bg-primary ms-1" id="summaryBadge">0</span>
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- Categories & Products -->
  <div class="p-3" style="padding-bottom: 100px !important;">
    <?php 
    // Group products by category
    $categorizedProducts = [];
    $uncategorized = [];
    foreach($products as $p) {
      if(!empty($p['category_name'])) {
        $catName = $p['category_name'];
        if(!isset($categorizedProducts[$catName])) $categorizedProducts[$catName] = [];
        $categorizedProducts[$catName][] = $p;
      } else {
        $uncategorized[] = $p;
      }
    }
    ksort($categorizedProducts);
    ?>
    
    <div id="productContainer">
      <?php foreach($categorizedProducts as $categoryName => $categoryProducts): ?>
        <div class="category-section mb-4" data-category="<?= htmlspecialchars(strtolower($categoryName)) ?>">
          <div class="d-flex justify-content-between align-items-center mb-3 category-header-container" onclick="toggleCategoryByHeader(this)" style="cursor: pointer;">
            <h5 class="category-header mb-0 fw-bold text-secondary">
              <i class="fas fa-folder-open me-2"></i><?= htmlspecialchars($categoryName) ?>
              <span class="badge bg-secondary ms-2"><?= count($categoryProducts) ?></span>
              <span class="badge bg-primary ms-2 selected-count" style="display: none;">0</span>
            </h5>
            <div class="category-toggle-icon">
              <i class="fas fa-chevron-up"></i>
            </div>
          </div>
          
          <!-- Cards View -->
          <div class="row g-3 category-products cards-view">
            <?php foreach($categoryProducts as $p): ?>
              <div class="col-12 col-sm-6 col-md-4 col-lg-3 product-item" data-name="<?=strtolower($p['name'])?>" data-category="<?=strtolower($categoryName)?>">
                <div class="card h-100 border-0 shadow-sm product-card" id="card-<?=$p['id']?>">
                  <div class="card-body d-flex flex-column justify-content-between p-3">
                    <h6 class="card-title fw-bold mb-3 text-dark text-truncate" title="<?=htmlspecialchars($p['name'])?>"><?=$p['name'];?></h6>
                    <div class="d-flex align-items-center justify-content-between bg-light rounded-pill p-1">
                      <button type="button" class="btn btn-circle btn-white text-danger shadow-sm adjQty adjQty-minus" onclick="adjQty(<?=$p['id']?>, -1)"><i class="fas fa-minus"></i></button>
                      <input type="number" class="form-control border-0 bg-transparent text-center fw-bold p-0 qty-input" id="qty-<?=$p['id']?>" value="0" min="0" style="width: 50px;" data-id="<?=$p['id']?>" data-name="<?=htmlspecialchars($p['name'])?>" onchange="syncHidden(this)">
                      <button type="button" class="btn btn-circle btn-white text-success shadow-sm adjQty adjQty-plus" onclick="adjQty(<?=$p['id']?>, 1)"><i class="fas fa-plus"></i></button>
                    </div>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
          
          <!-- List View (hidden by default) -->
          <div class="list-view d-none">
            <div class="list-group">
              <?php foreach($categoryProducts as $p): ?>
                <div class="list-group-item product-item-list" id="list-item-<?=$p['id']?>" data-name="<?=strtolower($p['name'])?>" data-category="<?=strtolower($categoryName)?>">
                  <div class="d-flex justify-content-between align-items-center">
                    <div class="flex-grow-1">
                      <h6 class="mb-0 fw-bold"><?=$p['name'];?></h6>
                    </div>
                    <div class="d-flex align-items-center gap-2 d-flex align-items-center justify-content-between bg-light rounded-pill p-1">
                      <button type="button" class="btn btn-circle btn-white text-danger shadow-sm adjQty adjQty-minus" onclick="adjQty(<?=$p['id']?>, -1)">
                        <i class="fas fa-minus"></i>
                      </button>
                      <input type="number" class="form-control form-control-sm text-center fw-bold qty-input-list" id="qty-list-<?=$p['id']?>" value="0" min="0" style="width: 60px;" data-id="<?=$p['id']?>" data-name="<?=htmlspecialchars($p['name'])?>" onchange="syncHiddenList(this, <?=$p['id']?>)">
                      <button type="button" class="btn btn-circle btn-white text-success shadow-sm adjQty adjQty-plus" onclick="adjQty(<?=$p['id']?>, 1)">
                        <i class="fas fa-plus"></i>
                      </button>
                    </div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          </div>
        </div>
      <?php endforeach; ?>
      
      <?php if(!empty($uncategorized)): ?>
        <div class="category-section mb-4">
          <div class="d-flex justify-content-between align-items-center mb-3 category-header-container" onclick="toggleCategoryByHeader(this)" style="cursor: pointer;">
            <h5 class="category-header mb-0 fw-bold text-secondary">
              <i class="fas fa-box me-2"></i><?= __('common.uncategorized', 'Uncategorized') ?>
              <span class="badge bg-secondary ms-2"><?= count($uncategorized) ?></span>
              <span class="badge bg-primary ms-2 selected-count" style="display: none;">0</span>
            </h5>
            <div class="category-toggle-icon">
              <i class="fas fa-chevron-up"></i>
            </div>
          </div>
          <div class="row g-3 category-products cards-view">
            <?php foreach($uncategorized as $p): ?>
              <div class="col-12 col-sm-6 col-md-4 col-lg-3 product-item" data-name="<?=strtolower($p['name'])?>">
                <div class="card h-100 border-0 shadow-sm product-card" id="card-<?=$p['id']?>">
                  <div class="card-body d-flex flex-column justify-content-between p-3">
                    <h6 class="card-title fw-bold mb-3 text-dark text-truncate" title="<?=htmlspecialchars($p['name'])?>"><?=$p['name'];?></h6>
                    <div class="d-flex align-items-center justify-content-between bg-light rounded-pill p-1">
                      <button type="button" class="btn  btn-white text-danger shadow-sm btn-circle adjQty adjQty-minus" onclick="adjQty(<?=$p['id']?>, -1)"><i class="fas fa-minus"></i></button>
                      <input type="number" class="form-control border-0 bg-transparent text-center fw-bold p-0 qty-input" id="qty-<?=$p['id']?>" value="0" min="0" style="width: 50px;" data-id="<?=$p['id']?>" data-name="<?=htmlspecialchars($p['name'])?>" onchange="syncHidden(this)">
                      <button type="button" class="btn  btn-white text-success shadow-sm btn-circle adjQty adjQty-plus" onclick="adjQty(<?=$p['id']?>, 1)"><i class="fas fa-plus"></i></button>
                    </div>
                  </div>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Summary Sidebar -->
  <div class="offcanvas offcanvas-end" tabindex="-1" id="summaryPanel" style="width: 400px;">
    <div class="offcanvas-header bg-light">
      <h5 class="offcanvas-title fw-bold">
        <i class="fas fa-shopping-cart me-2"></i><?= __('orders.order_summary', 'Order Summary') ?>
      </h5>
      <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
    </div>
    <div class="offcanvas-body p-0">
      <div id="summaryContent" class="p-3">
        <div class="text-center text-muted py-5">
          <i class="fas fa-shopping-cart fa-3x mb-3 opacity-50"></i>
          <p><?= __('orders.empty_cart', 'No items added yet') ?></p>
        </div>
      </div>
    </div>
    <div class="offcanvas-footer border-top p-3 bg-light">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <span class="fw-bold"><?= __('orders.total_items', 'Total Items') ?>:</span>
        <span class="h4 mb-0 text-primary fw-bold" id="summaryTotal">0</span>
      </div>
      <button type="button" onclick="submitForm()" class="btn btn-primary w-100 rounded-pill fw-bold">
        <?= __('orders.submit', 'Submit Order') ?> <i class="fas fa-paper-plane ms-2"></i>
      </button>
    </div>
  </div>

  <!-- Footer -->
  <div class="fixed-bottom bg-white border-top shadow-lg p-3" style="z-index: 1030;">
    <div class="d-flex justify-content-between align-items-center">
      <div>
        <span class="text-muted small text-uppercase fw-bold"><?= __('orders.total_items', 'Total Items') ?></span>
        <div class="h4 mb-0 fw-bold text-primary" id="totalItems">0</div>
      </div>
      <button type="button" onclick="submitForm()" class="btn btn-primary btn-lg px-5 rounded-pill shadow-sm fw-bold">
        <?= __('orders.submit', 'Submit Order') ?> <i class="fas fa-paper-plane ms-2"></i>
      </button>
    </div>
  </div>
</div>

<!-- Quick Adjust Menu -->
<div id="quickAdjustMenu" class="quick-adjust-menu">
  <div class="quick-adjust-btn negative" data-value="-10">-10</div>
  <div class="quick-adjust-btn negative" data-value="-5">-5</div>
  <div class="quick-adjust-btn positive" data-value="+5">+5</div>
  <div class="quick-adjust-btn positive" data-value="+10">+10</div>
</div>

<script>
const custUserMap = <?=json_encode($customer_user_map ?? []);?>;

// Haptic feedback for touch devices
function vibrate(duration = 10) {
  if (navigator.vibrate) navigator.vibrate(duration);
}

// Quick adjust menu state
let holdTimer = null;
let currentAdjustId = null;
let menuTriggered = false;
const quickAdjustMenu = document.getElementById('quickAdjustMenu');

// Quantity adjustment with animations
function adjQty(id, delta) {
  // Prevent action if menu was just triggered
  if (menuTriggered) {
    menuTriggered = false;
    return;
  }
  
  vibrate();
  const input = document.getElementById('qty-' + id);
  const listInput = document.getElementById('qty-list-' + id);
  const card = document.getElementById('card-' + id);
  
  let v = parseFloat(input.value) || 0;
  v += delta;
  if (v < 0) v = 0;
  
  // Animate the change
  if (card) {
    card.style.transform = 'scale(0.95)';
    setTimeout(() => { card.style.transform = ''; }, 100);
  }
  
  input.value = v;
  if (listInput) listInput.value = v;
  syncHidden(input);
}

// Show quick adjust menu
function showQuickAdjust(event, id, isNegative) {
  event.preventDefault();
  event.stopPropagation();
  
  // Mark that menu was triggered to prevent onclick from firing
  menuTriggered = true;
  
  currentAdjustId = id;
  const rect = event.target.closest('.adjQty').getBoundingClientRect();
  
  // Position menu near the button
  const menu = quickAdjustMenu;
  const menuWidth = 240; // Approximate width
  const menuHeight = 64;
  
  let top = rect.top - menuHeight - 10;
  let left = rect.left + (rect.width / 2);
  
  // Adjust if menu goes off screen
  if (top < 10) top = rect.bottom + 10;
  if (left - (menuWidth / 2) < 10) left = menuWidth / 2 + 10;
  if (left + (menuWidth / 2) > window.innerWidth - 10) left = window.innerWidth - (menuWidth / 2) - 10;
  
  // Set position before showing
  menu.style.top = top + 'px';
  menu.style.left = left + 'px';
  
  // Show only relevant buttons
  const buttons = menu.querySelectorAll('.quick-adjust-btn');
  buttons.forEach(btn => {
    const value = parseInt(btn.dataset.value);
    if (isNegative) {
      btn.style.display = value < 0 ? 'flex' : 'none';
    } else {
      btn.style.display = value > 0 ? 'flex' : 'none';
    }
  });
  
  // Show menu with display first, then animate in next frame
  menu.style.display = 'flex';
  requestAnimationFrame(() => {
    menu.classList.add('show');
    vibrate(20);
  });
}

// Hide quick adjust menu
function hideQuickAdjust() {
  quickAdjustMenu.classList.remove('show');
  // Wait for animation to complete before hiding
  setTimeout(() => {
    if (!quickAdjustMenu.classList.contains('show')) {
      quickAdjustMenu.style.display = 'none';
    }
  }, 200);
  currentAdjustId = null;
}

// Sync hidden form fields
function syncHidden(input) {
  const id = input.dataset.id;
  const name = input.dataset.name;
  const v = parseFloat(input.value) || 0;
  const hiddenWrap = document.getElementById('hidden-items');
  const card = document.getElementById('card-' + id);
  const listItem = document.getElementById('list-item-' + id);
  
  // Toggle active state with animation
  if (v > 0) {
    if (card) card.classList.add('active');
    if (listItem) listItem.classList.add('active');
    vibrate(15);
  } else {
    if (card) card.classList.remove('active');
    if (listItem) listItem.classList.remove('active');
  }
  
  // Manage hidden inputs
  let row = hiddenWrap.querySelector(`div[data-id='${id}']`);
  if (v <= 0) {
    if (row) row.remove();
  } else {
    if (!row) {
      row = document.createElement('div');
      row.dataset.id = id;
      row.innerHTML = `<input type='hidden' name='item_product_id[]' value='${id}'><input type='hidden' name='item_qty[]' value='${v}'><input type='hidden' name='item_name_snapshot[]' value='${name}'>`;
      hiddenWrap.appendChild(row);
    } else {
      row.querySelector("input[name='item_qty[]']").value = v;
    }
  }
  updateTotal();
}

// Update total items counter
function updateTotal() {
  const inputs = document.querySelectorAll("input[name='item_qty[]']");
  let total = 0;
  inputs.forEach(inp => total += parseFloat(inp.value) || 0);
  const totalEl = document.getElementById('totalItems');
  
  // Animate total change
  totalEl.style.transform = 'scale(1.2)';
  setTimeout(() => { totalEl.style.transform = ''; }, 200);
  
  totalEl.textContent = total;
  document.getElementById('summaryBadge').textContent = total;
  document.getElementById('summaryTotal').textContent = total;
  
  // Update summary panel
  updateSummaryPanel();
  
  // Update category selected counts
  updateCategorySelectedCounts();
}

// Sync list view input
function syncHiddenList(input, id) {
  const cardInput = document.getElementById('qty-' + id);
  cardInput.value = input.value;
  syncHidden(cardInput);
}

// Update summary panel content
function updateSummaryPanel() {
  const summaryContent = document.getElementById('summaryContent');
  const hiddenItems = document.getElementById('hidden-items');
  const items = hiddenItems.querySelectorAll('div[data-id]');
  
  if (items.length === 0) {
    summaryContent.innerHTML = `
      <div class="text-center text-muted py-5">
        <i class="fas fa-shopping-cart fa-3x mb-3 opacity-50"></i>
        <p><?= __('orders.empty_cart', 'No items added yet') ?></p>
      </div>
    `;
    return;
  }
  
  let html = '<div class="summary-items">';
  items.forEach(item => {
    const id = item.dataset.id;
    const qty = item.querySelector("input[name='item_qty[]']").value;
    const name = item.querySelector("input[name='item_name_snapshot[]']").value;
    
    html += `
      <div class="summary-item">
        <div class="summary-item-name flex-grow-1">${name}</div>
        <div class="summary-item-qty">${qty}</div>
        <div class="summary-item-remove ms-2" onclick="removeFromSummary(${id})">
          <i class="fas fa-times"></i>
        </div>
      </div>
    `;
  });
  html += '</div>';
  summaryContent.innerHTML = html;
}

// Remove item from summary
function removeFromSummary(id) {
  const input = document.getElementById('qty-' + id);
  const listInput = document.getElementById('qty-list-' + id);
  input.value = 0;
  if (listInput) listInput.value = 0;
  syncHidden(input);
  vibrate();
}

// Toggle summary panel
function toggleSummary() {
  const offcanvas = new bootstrap.Offcanvas(document.getElementById('summaryPanel'));
  offcanvas.toggle();
  vibrate();
}

// Switch view mode
let currentView = 'cards';
function switchView(mode) {
  currentView = mode;
  const cardsViews = document.querySelectorAll('.cards-view');
  const listViews = document.querySelectorAll('.list-view');
  const btnCards = document.getElementById('viewCards');
  const btnList = document.getElementById('viewList');
  
  if (mode === 'cards') {
    cardsViews.forEach(el => el.classList.remove('d-none'));
    listViews.forEach(el => el.classList.add('d-none'));
    btnCards.classList.add('active');
    btnList.classList.remove('active');
  } else {
    cardsViews.forEach(el => el.classList.add('d-none'));
    listViews.forEach(el => el.classList.remove('d-none'));
    btnList.classList.add('active');
    btnCards.classList.remove('active');
    
    // Sync list inputs with card inputs
    document.querySelectorAll('.qty-input').forEach(input => {
      const id = input.dataset.id;
      const listInput = document.getElementById('qty-list-' + id);
      if (listInput) listInput.value = input.value;
    });
  }
  vibrate();
}

// Toggle show selected items only
let showSelectedOnly = false;
function toggleShowSelected() {
  showSelectedOnly = !showSelectedOnly;
  const btn = document.getElementById('btnShowSelected');
  
  if (showSelectedOnly) {
    btn.classList.add('active');
    // Hide items with quantity 0
    document.querySelectorAll('.product-item, .product-item-list').forEach(item => {
      const id = item.querySelector('.qty-input, .qty-input-list').dataset.id;
      const input = document.getElementById('qty-' + id);
      const qty = parseFloat(input.value) || 0;
      item.style.display = qty > 0 ? '' : 'none';
    });
    
    // Unfold all collapsed groups that have selected items
    document.querySelectorAll('.category-section.collapsed').forEach(section => {
      const selectedItems = section.querySelectorAll('.product-item:not([style*="display: none"]), .product-item-list:not([style*="display: none"])');
      if (selectedItems.length > 0) {
        section.classList.remove('collapsed');
      }
    });
  } else {
    btn.classList.remove('active');
    // Show all items (respecting search filter)
    const searchTerm = document.getElementById('productSearch').value.toLowerCase().trim();
    document.querySelectorAll('.product-item, .product-item-list').forEach(item => {
      if (searchTerm === '') {
        item.style.display = '';
      } else {
        const name = item.dataset.name;
        const category = item.dataset.category || '';
        item.style.display = (name.includes(searchTerm) || category.includes(searchTerm)) ? '' : 'none';
      }
    });
  }
  
  // Hide empty categories
  document.querySelectorAll('.category-section').forEach(section => {
    const visibleItems = section.querySelectorAll('.product-item:not([style*="display: none"]), .product-item-list:not([style*="display: none"])');
    section.style.display = visibleItems.length > 0 ? '' : 'none';
  });
  
  vibrate();
}

// Toggle category section by clicking header
function toggleCategoryByHeader(headerContainer) {
  const section = headerContainer.closest('.category-section');
  section.classList.toggle('collapsed');
  vibrate();
}

// Toggle category section (kept for compatibility)
function toggleCategory(btn) {
  const section = btn.closest('.category-section');
  section.classList.toggle('collapsed');
  vibrate();
}

// Submit form with validation
function submitForm() {
  const form = document.getElementById('tablet-order-form');
  const totalItems = parseInt(document.getElementById('totalItems').textContent);
  
  if (!form.checkValidity()) {
    form.reportValidity();
    return;
  }
  
  if (totalItems === 0) {
    showNotification('<?= __('orders.add_items', 'Please add at least one item') ?>', 'warning');
    return;
  }
  
  vibrate(30);
  showNotification('<?= __('orders.submitting', 'Submitting order...') ?>', 'info');
  form.submit();
}

// Product search with debounce
let searchTimeout;
document.getElementById('productSearch').addEventListener('input', function() {
  clearTimeout(searchTimeout);
  const term = this.value.toLowerCase().trim();
  
  searchTimeout = setTimeout(() => {
    // Deactivate selected filter when searching
    if (term !== '' && showSelectedOnly) {
      showSelectedOnly = false;
      document.getElementById('btnShowSelected').classList.remove('active');
    }
    
    // Search in both view modes
    document.querySelectorAll('.product-item, .product-item-list').forEach(item => {
      const name = item.dataset.name;
      const category = item.dataset.category || '';
      const matches = name.includes(term) || category.includes(term);
      item.style.display = matches ? '' : 'none';
      
      if (matches) {
        item.style.animation = 'fadeIn 0.3s ease-out';
      }
    });
    
    // Hide empty categories
    document.querySelectorAll('.category-section').forEach(section => {
      const visibleItems = section.querySelectorAll('.product-item:not([style*="display: none"]), .product-item-list:not([style*="display: none"])');
      section.style.display = visibleItems.length > 0 ? '' : 'none';
    });
  }, 200);
});

// Customer selection handler
const customerSelect = document.getElementById('customerSelect');
if(customerSelect) {
  customerSelect.addEventListener('change', function(){
    const cid = this.value;
    const list = custUserMap[cid] || [];
    const sel = document.getElementById('assignedUser');
    const cur = sel.value;
    
    sel.innerHTML = '<option value=""><?= __('common.select', 'Select') ?></option>' + 
                    list.map(u => `<option value='${u.id}'>${u.name}</option>`).join('');
    
    if(list.find(u => u.id == cur)) sel.value = cur;
    
    vibrate();
  });
}

// Quick add functionality - double tap to add
let lastTap = {};
document.querySelectorAll('.product-card').forEach(card => {
  card.addEventListener('dblclick', function() {
    const id = this.id.replace('card-', '');
    adjQty(id, 1);
  });
});

// Notification system
function showNotification(message, type = 'info') {
  const colors = {
    success: '#28a745',
    warning: '#ffc107',
    danger: '#dc3545',
    info: '#17a2b8'
  };
  
  const notification = document.createElement('div');
  notification.style.cssText = `
    position: fixed;
    top: 80px;
    left: 50%;
    transform: translateX(-50%);
    background: ${colors[type]};
    color: white;
    padding: 12px 24px;
    border-radius: 50px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.3);
    z-index: 9999;
    font-weight: 600;
    animation: fadeIn 0.3s ease-out;
  `;
  notification.textContent = message;
  document.body.appendChild(notification);
  
  setTimeout(() => {
    notification.style.opacity = '0';
    notification.style.transform = 'translateX(-50%) translateY(-20px)';
    setTimeout(() => notification.remove(), 300);
  }, 2000);
}

// Keyboard shortcuts for desktop
document.addEventListener('keydown', function(e) {
  // Enter to submit
  if (e.key === 'Enter' && e.ctrlKey) {
    e.preventDefault();
    submitForm();
  }
  // Escape to clear search
  if (e.key === 'Escape') {
    document.getElementById('productSearch').value = '';
    document.getElementById('productSearch').dispatchEvent(new Event('input'));
  }
});

// Prevent accidental zoom on double-tap (iOS)
let lastTouchEnd = 0;
document.addEventListener('touchend', function(event) {
  const now = Date.now();
  if (now - lastTouchEnd <= 300) {
    event.preventDefault();
  }
  lastTouchEnd = now;
}, false);

// Quick adjust menu click handlers
quickAdjustMenu.addEventListener('click', function(e) {
  const btn = e.target.closest('.quick-adjust-btn');
  if (btn && currentAdjustId) {
    const delta = parseInt(btn.dataset.value);
    adjQty(currentAdjustId, delta);
    hideQuickAdjust();
  }
});

// Close quick adjust menu when clicking outside
document.addEventListener('click', function(e) {
  if (!e.target.closest('#quickAdjustMenu') && !e.target.closest('.adjQty')) {
    hideQuickAdjust();
  }
});

// Add long-press handlers to all +/- buttons
function setupLongPress() {
  document.querySelectorAll('.adjQty').forEach(btn => {
    // Mouse events
    btn.addEventListener('mousedown', function(e) {
      const id = parseInt(this.getAttribute('onclick').match(/\d+/)[0]);
      const isNegative = this.classList.contains('adjQty-minus');
      
      // Reset flag at start of press
      menuTriggered = false;
      
      holdTimer = setTimeout(() => {
        showQuickAdjust(e, id, isNegative);
      }, 500);
    });
    
    btn.addEventListener('mouseup', function() {
      if (holdTimer) {
        clearTimeout(holdTimer);
        holdTimer = null;
      }
      // Reset flag after short delay to allow click event to check it
      setTimeout(() => {
        menuTriggered = false;
      }, 50);
    });
    
    btn.addEventListener('mouseleave', function() {
      if (holdTimer) {
        clearTimeout(holdTimer);
        holdTimer = null;
      }
      menuTriggered = false;
    });
    
    // Touch events
    btn.addEventListener('touchstart', function(e) {
      const id = parseInt(this.getAttribute('onclick').match(/\d+/)[0]);
      const isNegative = this.classList.contains('adjQty-minus');
      
      // Reset flag at start of press
      menuTriggered = false;
      
      holdTimer = setTimeout(() => {
        showQuickAdjust(e.touches[0], id, isNegative);
      }, 500);
    });
    
    btn.addEventListener('touchend', function(e) {
      if (holdTimer) {
        clearTimeout(holdTimer);
        holdTimer = null;
      }
      // Prevent click event if menu was triggered
      if (menuTriggered) {
        e.preventDefault();
      }
      // Reset flag after short delay
      setTimeout(() => {
        menuTriggered = false;
      }, 50);
    });
    
    btn.addEventListener('touchcancel', function() {
      if (holdTimer) {
        clearTimeout(holdTimer);
        holdTimer = null;
      }
      menuTriggered = false;
    });
  });
}

// Update category selected counts
function updateCategorySelectedCounts() {
  document.querySelectorAll('.category-section').forEach(section => {
    const items = section.querySelectorAll('.product-item, .product-item-list');
    let selectedCount = 0;
    
    items.forEach(item => {
      const id = item.querySelector('.qty-input, .qty-input-list').dataset.id;
      const input = document.getElementById('qty-' + id);
      const qty = parseFloat(input.value) || 0;
      if (qty > 0) selectedCount++;
    });
    
    const badge = section.querySelector('.selected-count');
    if (badge) {
      if (selectedCount > 0) {
        badge.textContent = selectedCount / 2;
        badge.style.display = 'inline-block';
      } else {
        badge.style.display = 'none';
      }
    }
  });
}

// Initialize - focus on customer select
window.addEventListener('load', function() {
  if (window.innerWidth > 768) {
    setTimeout(() => customerSelect.focus(), 300);
  }
  setupLongPress();
  updateCategorySelectedCounts();
});
</script>
<?php $content=ob_get_clean(); require __DIR__.'/../layout.php'; ?>