<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POS Terminal - <?= e(Auth::tenant()['business_name']) ?></title>
    <link rel="stylesheet" href="<?= APP_URL ?>/assets/css/app.css">
    <style>
        :root { 
            --pos-header-h: 72px; 
            --pos-cart-w: 380px;
            --pos-cat-h: 60px;
            
            /* Modern Palette */
            --primary: #8b5cf6;
            --primary-dark: #7c3aed;
            --primary-light: #a78bfa;
            --primary-glow: rgba(139, 92, 246, 0.3);
            --secondary: #06b6d4;
            --accent: #f472b6;
            --success: #10b981;
            --warning: #f59e0b;
            --danger: #ef4444;
            --dark: #1e1b4b;
            --dark-light: #312e81;
            --light: #f8fafc;
            --gray-50: #f9fafb;
            --gray-100: #f3f4f6;
            --gray-200: #e5e7eb;
            --gray-300: #d1d5db;
            --gray-400: #9ca3af;
            --gray-500: #6b7280;
            --gray-600: #4b5563;
            
            /* Glassmorphism Enhanced */
            --glass-bg: rgba(255, 255, 255, 0.75);
            --glass-bg-dark: rgba(30, 27, 75, 0.9);
            --glass-border: rgba(255, 255, 255, 0.5);
            --glass-blur: blur(20px);
            --glass-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
            
            /* Modern Shadows */
            --shadow-xs: 0 1px 2px rgba(0,0,0,0.05);
            --shadow-sm: 0 2px 4px rgba(0,0,0,0.06);
            --shadow-md: 0 4px 6px rgba(0,0,0,0.07);
            --shadow-lg: 0 10px 15px rgba(0,0,0,0.1);
            --shadow-xl: 0 20px 25px rgba(0,0,0,0.15);
            --shadow-2xl: 0 25px 50px rgba(0,0,0,0.25);
            --shadow-primary: 0 10px 40px rgba(139, 92, 246, 0.2);
            --shadow-glow: 0 0 20px rgba(139, 92, 246, 0.15);
            
            /* Border Radius */
            --radius-sm: 8px;
            --radius-md: 12px;
            --radius-lg: 16px;
            --radius-xl: 20px;
            --radius-2xl: 24px;
            --radius-full: 9999px;
            
            /* Transitions */
            --transition-fast: 0.15s ease;
            --transition-base: 0.2s ease;
            --transition-slow: 0.3s ease;
        }

        body { 
            overflow: hidden; 
            background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
            background-attachment: fixed;
            height: 100vh;
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            font-size: 14px;
            line-height: 1.5;
            color: var(--dark);
        }

        .pos-wrapper { display: flex; flex-direction: column; height: 100vh; }
        
        /* Modern Header */
        .pos-header {
            background: var(--glass-bg);
            backdrop-filter: var(--glass-blur);
            -webkit-backdrop-filter: var(--glass-blur);
            border-bottom: 1px solid var(--glass-border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 28px;
            gap: 24px;
            height: var(--pos-header-h);
            flex-shrink: 0;
            z-index: 100;
            box-shadow: var(--glass-shadow);
        }

        .pos-header-left {
            display: flex;
            align-items: center;
            gap: 24px;
        }

        .pos-brand {
            display: flex;
            align-items: center;
            gap: 14px;
            padding-right: 24px;
            border-right: 2px solid var(--glass-border);
        }
        .pos-brand-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            border-radius: var(--radius-lg);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            box-shadow: var(--shadow-primary);
            transition: var(--transition-base);
        }
        .pos-brand-icon:hover {
            transform: scale(1.05);
            box-shadow: var(--shadow-glow);
        }
        .pos-brand-name {
            font-weight: 800;
            font-size: 1.25rem;
            letter-spacing: -0.03em;
            background: linear-gradient(135deg, var(--primary), var(--secondary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        /* Modern Controls */
        .pos-controls { display: flex; align-items: center; gap: 14px; }

        .pos-location-select, .pos-customer-btn {
            height: 44px;
            border: 2px solid var(--glass-border);
            background: rgba(255, 255, 255, 0.9);
            border-radius: var(--radius-md);
            font-weight: 600;
            font-size: 0.85rem;
            transition: var(--transition-base);
            box-shadow: var(--shadow-sm);
            padding: 0 16px;
            color: var(--gray-600);
        }
        .pos-location-select:hover, .pos-customer-btn:hover {
            border-color: var(--primary);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
            color: var(--primary);
        }
        .pos-location-select:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 3px var(--primary-glow);
        }

        .pos-customer-btn {
            display: flex;
            align-items: center;
            gap: 10px;
            cursor: pointer;
        }

        .pos-customer-avatar {
            width: 32px; height: 32px;
            background: linear-gradient(135deg, var(--primary), var(--primary-light));
            box-shadow: var(--shadow-md);
            border-radius: var(--radius-full);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 0.8rem;
            font-weight: bold;
        }

        /* Modern Search Bar */
        .pos-header-right { flex: 1; display: flex; justify-content: flex-end; max-width: 420px; }
        .pos-search { width: 100%; position: relative; }
        .pos-search input {
            width: 100%;
            height: 48px;
            padding: 0 20px 0 52px;
            background: rgba(255, 255, 255, 0.95);
            border: 2px solid var(--glass-border);
            border-radius: var(--radius-xl);
            font-size: 0.95rem;
            box-shadow: var(--shadow-sm);
            transition: var(--transition-base);
            color: var(--gray-600);
        }
        .pos-search input::placeholder {
            color: var(--gray-400);
        }
        .pos-search input:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 4px var(--primary-glow);
            background: #fff;
            color: var(--dark);
        }
        .pos-search svg { 
            position: absolute;
            left: 18px; 
            top: 50%;
            transform: translateY(-50%);
            width: 20px; 
            color: var(--primary); 
            opacity: 0.7;
            transition: var(--transition-base);
        }
        .pos-search input:focus + svg,
        .pos-search svg {
            opacity: 1;
        }

        /* Main Container */
        .pos-main { 
            flex: 1; 
            display: flex; 
            overflow: hidden; 
            background: rgba(255, 255, 255, 0.4);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }
        .pos-products { flex: 1; display: flex; flex-direction: column; overflow: hidden; }

        /* Modern Category Pills */
        .pos-categories {
            height: var(--pos-cat-h);
            padding: 0 28px;
            gap: 12px;
            background: transparent;
            border-bottom: none;
            margin-top: 16px;
            display: flex;
            align-items: center;
            overflow-x: auto;
            flex-shrink: 0;
            scrollbar-width: none;
        }
        .pos-categories::-webkit-scrollbar { display: none; }
        
        .cat-tab {
            padding: 10px 24px;
            border-radius: var(--radius-full);
            background: rgba(255, 255, 255, 0.9);
            color: var(--gray-600);
            font-weight: 600;
            font-size: 0.85rem;
            border: 2px solid var(--glass-border);
            transition: var(--transition-base);
            box-shadow: var(--shadow-sm);
            white-space: nowrap;
            cursor: pointer;
        }
        .cat-tab:hover { 
            background: var(--primary-glow);
            color: var(--primary);
            border-color: var(--primary);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }
        .cat-tab.active {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: #fff;
            border-color: var(--primary);
            box-shadow: var(--shadow-primary);
            transform: translateY(-2px);
        }

        /* Modern Product Cards */
        .pos-products-grid { padding: 24px 28px; flex: 1; overflow-y: auto; }
        .product-grid { 
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); 
            gap: 20px; 
        }

        .product-item {
            background: rgba(255, 255, 255, 0.95);
            border: 2px solid var(--glass-border);
            border-radius: var(--radius-xl);
            box-shadow: var(--shadow-md);
            transition: var(--transition-slow);
            cursor: pointer;
            overflow: hidden;
            position: relative;
        }
        .product-item:hover { 
            transform: translateY(-6px) scale(1.02);
            box-shadow: var(--shadow-xl);
            border-color: var(--primary);
        }
        .product-item:active {
            transform: translateY(-2px) scale(0.98);
        }
        
        /* Out of Stock Modern */
        .product-item.out-of-stock {
            filter: grayscale(0.8);
            opacity: 0.5;
            cursor: not-allowed;
        }
        .product-item.out-of-stock::after {
            content: 'OUT OF STOCK';
            position: absolute;
            inset: 0;
            background: rgba(30, 27, 75, 0.7);
            backdrop-filter: blur(4px);
            -webkit-backdrop-filter: blur(4px);
            color: #fff;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 900;
            font-size: 0.9rem;
            letter-spacing: 0.1em;
            z-index: 20;
        }
        .product-item.out-of-stock:hover {
            transform: none;
            box-shadow: var(--shadow-md);
        }

        .product-qty-badge {
            position: absolute;
            top: 12px;
            right: 12px;
            background: linear-gradient(135deg, var(--success), #059669);
            color: #fff;
            padding: 4px 10px;
            border-radius: var(--radius-full);
            font-size: 0.75rem;
            font-weight: 700;
            z-index: 10;
            box-shadow: var(--shadow-md);
            display: none;
        }
        .product-item.in-cart .product-qty-badge { display: block; animation: badge-pop 0.3s ease; }

        @keyframes badge-pop {
            0% { transform: scale(0); }
            50% { transform: scale(1.2); }
            100% { transform: scale(1); }
        }

        .product-img {
            width: 100%;
            aspect-ratio: 1.1;
            background: linear-gradient(135deg, var(--gray-100), var(--gray-50));
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow: hidden;
        }
        .product-img img { width: 100%; height: 100%; object-fit: cover; transition: var(--transition-slow); }
        .product-item:hover .product-img img { transform: scale(1.05); }
        .product-placeholder { width: 56px; height: 56px; color: var(--primary); opacity: 0.3; }

        .product-img::before {
            content: '';
            position: absolute;
            inset: 0;
            background: linear-gradient(135deg, rgba(139, 92, 246, 0.05), transparent);
            opacity: 0;
            transition: var(--transition-base);
        }
        .product-item:hover .product-img::before { opacity: 1; }

        .product-info { padding: 16px; }
        .product-name { 
            font-size: 0.9rem; 
            font-weight: 700; 
            color: var(--dark); 
            margin-bottom: 8px; 
            white-space: nowrap; 
            overflow: hidden; 
            text-overflow: ellipsis;
            line-height: 1.4;
        }
        .product-price-row { display: flex; align-items: center; justify-content: space-between; }
        .product-price { 
            font-size: 1rem; 
            font-weight: 800; 
            color: var(--primary);
            background: var(--primary-glow);
            padding: 4px 10px;
            border-radius: var(--radius-md);
        }
        .product-stock { 
            font-size: 0.7rem; 
            border-radius: var(--radius-full); 
            padding: 4px 10px; 
            font-weight: 700; 
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        .product-stock.in { background: rgba(16, 185, 129, 0.15); color: var(--success); }
        .product-stock.low { background: rgba(245, 158, 11, 0.15); color: var(--warning); }
        .product-stock.out { background: rgba(239, 68, 68, 0.15); color: var(--danger); }

        /* Modern Cart Sidebar */
        .pos-cart {
            width: var(--pos-cart-w);
            background: var(--glass-bg);
            backdrop-filter: var(--glass-blur);
            -webkit-backdrop-filter: var(--glass-blur);
            border-left: 2px solid var(--glass-border);
            box-shadow: -8px 0 32px rgba(0,0,0,0.08);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .cart-header { 
            padding: 24px 28px; 
            display: flex; 
            justify-content: space-between; 
            align-items: center;
            background: rgba(255, 255, 255, 0.5);
            border-bottom: 2px solid var(--glass-border);
        }
        .cart-title { display: flex; align-items: center; gap: 12px; }
        .cart-icon { 
            width: 40px; 
            height: 40px; 
            border-radius: var(--radius-md); 
            background: var(--primary-glow); 
            color: var(--primary); 
            display: flex; 
            align-items: center; 
            justify-content: center;
            box-shadow: var(--shadow-sm);
        }
        .cart-count { 
            background: linear-gradient(135deg, var(--primary), var(--primary-dark)); 
            color: #fff; 
            font-size: 0.75rem; 
            font-weight: 700;
            padding: 4px 10px; 
            border-radius: var(--radius-full);
            box-shadow: var(--shadow-sm);
        }

        .cart-items { flex: 1; overflow-y: auto; }
        .cart-items::-webkit-scrollbar { width: 6px; }
        .cart-items::-webkit-scrollbar-thumb { background: var(--gray-300); border-radius: var(--radius-full); }
        .cart-items::-webkit-scrollbar-track { background: transparent; }

        .cart-item {
            padding: 16px 28px;
            border-bottom: 1px solid var(--gray-200);
            background: rgba(255, 255, 255, 0.3);
            display: flex;
            align-items: center;
            gap: 14px;
            animation: item-pop 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
            transition: var(--transition-base);
        }
        .cart-item:hover { 
            background: rgba(255, 255, 255, 0.6);
            transform: translateX(-4px);
        }

        .cart-item-thumb { 
            width: 48px; 
            height: 48px; 
            border-radius: var(--radius-md); 
            overflow: hidden; 
            background: var(--gray-100); 
            flex-shrink: 0;
            box-shadow: var(--shadow-sm);
        }
        .cart-item-thumb img { width: 100%; height: 100%; object-fit: cover; }
        .cart-item-info { flex: 1; min-width: 0; }
        .cart-item-name { 
            font-size: 0.9rem; 
            font-weight: 700; 
            color: var(--dark);
            white-space: nowrap; 
            overflow: hidden; 
            text-overflow: ellipsis; 
            margin-bottom: 4px;
        }
        .cart-item-price { 
            font-size: 0.8rem; 
            color: var(--gray-500); 
            font-weight: 500;
        }

        .cart-item-actions { display: flex; align-items: center; gap: 10px; }
        .qty-control { 
            display: flex; 
            align-items: center; 
            background: rgba(255, 255, 255, 0.9); 
            border: 2px solid var(--gray-200); 
            padding: 4px; 
            border-radius: var(--radius-md); 
            box-shadow: var(--shadow-sm);
            transition: var(--transition-base);
        }
        .qty-control:hover {
            border-color: var(--primary);
            box-shadow: var(--shadow-md);
        }
        .qty-btn { 
            width: 28px; 
            height: 28px; 
            border: none; 
            background: transparent; 
            cursor: pointer; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            color: var(--gray-500); 
            border-radius: var(--radius-sm);
            transition: var(--transition-fast);
        }
        .qty-btn:hover { 
            background: var(--primary); 
            color: #fff;
            transform: scale(1.1);
        }
        .cart-qty-input { 
            width: 36px; 
            border: none; 
            text-align: center; 
            font-size: 0.9rem; 
            font-weight: 700; 
            background: transparent;
            color: var(--dark);
        }
        .qty-btn.remove:hover { background: var(--danger); }

        .cart-item-total { 
            font-weight: 800; 
            color: var(--primary); 
            font-size: 0.95rem; 
            min-width: 70px; 
            text-align: right;
            background: var(--primary-glow);
            padding: 6px 12px;
            border-radius: var(--radius-md);
        }

        /* Empty Cart State */
        .cart-empty { 
            flex: 1; 
            display: flex; 
            flex-direction: column; 
            align-items: center; 
            justify-content: center; 
            color: var(--gray-400); 
            opacity: 0.7;
            padding: 40px;
        }
        .cart-empty-icon { 
            margin-bottom: 16px;
            color: var(--primary);
            opacity: 0.5;
        }

        /* Modern Checkout Area */
        .cart-footer {
            padding: 28px;
            background: rgba(255, 255, 255, 0.7);
            border-top: 2px solid var(--glass-border);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
        }

        .cart-actions-row { display: flex; gap: 12px; margin-bottom: 20px; }
        .cart-action-btn { 
            flex: 1; 
            background: rgba(255, 255, 255, 0.9); 
            border: 2px solid var(--gray-200); 
            border-radius: var(--radius-lg); 
            padding: 12px 8px; 
            font-size: 0.75rem; 
            font-weight: 700; 
            display: flex; 
            flex-direction: column; 
            align-items: center; 
            gap: 6px; 
            cursor: pointer; 
            transition: var(--transition-base); 
            color: var(--gray-600);
            box-shadow: var(--shadow-sm);
        }
        .cart-action-btn:hover { 
            border-color: var(--primary); 
            color: var(--primary); 
            background: var(--primary-glow);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .cart-summary { margin-bottom: 20px; }
        .cart-summary-row { 
            display: flex; 
            justify-content: space-between; 
            margin-bottom: 8px; 
            font-size: 0.85rem; 
            font-weight: 600; 
            color: var(--gray-500); 
        }
        .cart-summary-row.discount { color: var(--warning); }
        .cart-summary-label { display: flex; align-items: center; gap: 8px; }

        .cart-total {
            background: linear-gradient(135deg, var(--dark), var(--dark-light));
            border-radius: var(--radius-xl);
            margin: 16px 0 24px;
            padding: 20px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            color: #fff;
            box-shadow: var(--shadow-xl);
            position: relative;
            overflow: hidden;
        }
        .cart-total::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(255,255,255,0.1), transparent);
            transform: rotate(45deg);
            animation: shimmer 3s infinite;
        }
        @keyframes shimmer {
            0% { transform: translateX(-100%) rotate(45deg); }
            100% { transform: translateX(100%) rotate(45deg); }
        }
        .cart-total-icon { 
            display: flex; 
            align-items: center; 
            gap: 10px; 
            font-size: 0.85rem; 
            font-weight: 700; 
            opacity: 0.9;
            position: relative;
            z-index: 1;
        }
        .cart-total #summary-total {
            font-size: 2rem;
            font-weight: 800;
            text-shadow: 0 2px 10px rgba(0,0,0,0.3);
            position: relative;
            z-index: 1;
        }

        .btn-checkout {
            width: 100%;
            height: 58px;
            border: none;
            border-radius: var(--radius-xl);
            font-size: 1.1rem;
            font-weight: 700;
            color: #fff;
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            letter-spacing: 0.02em;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
            cursor: pointer;
            transition: var(--transition-base);
            box-shadow: var(--shadow-primary);
            position: relative;
            overflow: hidden;
        }
        .btn-checkout::before {
            content: '';
            position: absolute;
            inset: 0;
            background: linear-gradient(135deg, transparent, rgba(255,255,255,0.2), transparent);
            transform: translateX(-100%);
            transition: var(--transition-slow);
        }
        .btn-checkout:not(:disabled):hover { 
            transform: translateY(-3px); 
            box-shadow: var(--shadow-xl);
        }
        .btn-checkout:not(:disabled):hover::before {
            transform: translateX(100%);
        }
        .btn-checkout:not(:disabled) { animation: pulse-glow 2.5s infinite; }
        .btn-checkout:disabled { 
            opacity: 0.5; 
            cursor: not-allowed; 
            animation: none; 
            filter: grayscale(0.5);
            transform: none;
        }

        @keyframes pulse-glow {
            0% { box-shadow: 0 0 0 0 rgba(139, 92, 246, 0.5); }
            70% { box-shadow: 0 0 0 15px rgba(139, 92, 246, 0); }
            100% { box-shadow: 0 0 0 0 rgba(139, 92, 246, 0); }
        }

        /* Modern Modal Styling */
        .modal-overlay { 
            position: fixed; 
            inset: 0; 
            background: rgba(30, 27, 75, 0.6); 
            backdrop-filter: blur(8px);
            -webkit-backdrop-filter: blur(8px);
            display: none; 
            align-items: center; 
            justify-content: center; 
            z-index: 1000;
            animation: modal-fade-in 0.2s ease;
        }
        .modal-overlay.show { display: flex; }
        @keyframes modal-fade-in { from { opacity: 0; } to { opacity: 1; } }

        .checkout-modal {
            background: rgba(255, 255, 255, 0.98);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border-radius: var(--radius-2xl);
            width: 100%;
            max-width: 480px;
            overflow: hidden;
            box-shadow: var(--shadow-2xl);
            border: 2px solid var(--glass-border);
            transform: scale(0.9) translateY(20px);
            transition: var(--transition-slow);
        }
        .modal-overlay.show .checkout-modal { transform: scale(1) translateY(0); }

        .modal-header { 
            padding: 24px 28px; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            border-bottom: 2px solid var(--gray-100);
            background: linear-gradient(135deg, var(--gray-50), #fff);
        }
        .modal-title { 
            font-size: 1.2rem; 
            font-weight: 800; 
            color: var(--dark);
            letter-spacing: -0.02em;
        }
        .modal-close { 
            background: var(--gray-100); 
            border: none; 
            cursor: pointer; 
            color: var(--gray-500); 
            padding: 8px; 
            border-radius: var(--radius-md);
            transition: var(--transition-base);
        }
        .modal-close:hover { 
            background: var(--danger); 
            color: #fff;
            transform: rotate(90deg);
        }

        .modal-body { padding: 28px; }
        .payable-amount {
            background: linear-gradient(135deg, var(--dark), var(--dark-light));
            color: #fff;
            padding: 32px;
            border-radius: var(--radius-xl);
            text-align: center;
            margin-bottom: 28px;
            box-shadow: var(--shadow-xl);
            position: relative;
            overflow: hidden;
        }
        .payable-amount::before {
            content: '';
            position: absolute;
            top: -50%;
            left: -50%;
            width: 200%;
            height: 200%;
            background: linear-gradient(45deg, transparent, rgba(255,255,255,0.05), transparent);
            transform: rotate(45deg);
            animation: shimmer 3s infinite;
        }
        .payable-label { 
            font-size: 0.85rem; 
            font-weight: 600; 
            opacity: 0.8; 
            margin-bottom: 12px;
            text-transform: uppercase;
            letter-spacing: 0.1em;
            position: relative;
            z-index: 1;
        }
        .payable-value {
            font-size: 2.8rem;
            font-weight: 800;
            background: linear-gradient(135deg, #fff, rgba(255,255,255,0.7));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            position: relative;
            z-index: 1;
        }

        .payment-methods { 
            display: grid; 
            grid-template-columns: repeat(3, 1fr); 
            gap: 16px; 
            margin-bottom: 28px; 
        }
        .payment-method { 
            border: 2px solid var(--gray-200); 
            border-radius: var(--radius-xl); 
            padding: 16px 12px; 
            text-align: center; 
            cursor: pointer; 
            transition: var(--transition-base);
            background: rgba(255, 255, 255, 0.8);
        }
        .payment-method:hover { 
            border-color: var(--primary); 
            background: var(--primary-glow);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }
        .payment-method.active { 
            border-color: var(--primary); 
            background: var(--primary-glow);
            box-shadow: var(--shadow-primary);
        }
        .payment-method-icon { 
            width: 44px; 
            height: 44px; 
            background: var(--gray-100); 
            border-radius: var(--radius-lg); 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            margin: 0 auto 10px; 
            color: var(--gray-500); 
            transition: var(--transition-base);
        }
        .payment-method.active .payment-method-icon { 
            background: linear-gradient(135deg, var(--primary), var(--primary-dark)); 
            color: #fff;
            box-shadow: var(--shadow-md);
        }
        .payment-method-label { 
            font-size: 0.8rem; 
            font-weight: 700; 
            color: var(--gray-600); 
        }
        .payment-method.active .payment-method-label {
            color: var(--primary);
        }

        .quick-amounts { 
            display: flex; 
            gap: 10px; 
            flex-wrap: wrap; 
            margin-bottom: 24px; 
        }
        .quick-amount { 
            background: var(--gray-100); 
            border: 2px solid var(--gray-200); 
            border-radius: var(--radius-full); 
            padding: 10px 20px; 
            font-size: 0.85rem; 
            font-weight: 700; 
            color: var(--gray-600); 
            cursor: pointer; 
            transition: var(--transition-base);
        }
        .quick-amount:hover { 
            background: var(--primary); 
            color: #fff;
            border-color: var(--primary);
            transform: translateY(-2px);
            box-shadow: var(--shadow-md);
        }

        .received-input-group label { 
            display: block; 
            font-size: 0.85rem; 
            font-weight: 700; 
            color: var(--gray-500); 
            margin-bottom: 10px;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        .received-input { 
            width: 100%; 
            background: var(--gray-50); 
            border: 2px solid var(--gray-200); 
            border-radius: var(--radius-xl); 
            padding: 18px; 
            font-size: 1.8rem; 
            font-weight: 800; 
            text-align: center; 
            transition: var(--transition-base);
            color: var(--dark);
        }
        .received-input:focus { 
            outline: none; 
            border-color: var(--primary); 
            background: #fff; 
            box-shadow: 0 0 0 4px var(--primary-glow);
        }

        .change-display { 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            padding: 18px 24px; 
            border-radius: var(--radius-xl); 
            margin-top: 24px;
            transition: var(--transition-base);
        }
        .change-label { 
            font-size: 0.9rem; 
            font-weight: 700; 
            color: var(--gray-600);
        }
        .change-value { 
            font-size: 1.6rem; 
            font-weight: 800; 
        }

        .modal-footer { 
            padding: 24px 28px; 
            border-top: 2px solid var(--gray-100); 
            display: flex; 
            gap: 14px;
            background: var(--gray-50);
        }
        .btn { 
            border: none; 
            border-radius: var(--radius-lg); 
            padding: 14px 28px; 
            font-size: 0.95rem; 
            font-weight: 700; 
            cursor: pointer; 
            transition: var(--transition-base);
        }
        .btn-ghost { 
            background: var(--gray-200); 
            color: var(--gray-600); 
            flex: 1;
        }
        .btn-ghost:hover { 
            background: var(--gray-300);
            color: var(--dark);
        }
        .btn-primary { 
            background: linear-gradient(135deg, var(--primary), var(--primary-dark)); 
            color: #fff; 
            flex: 2; 
            display: flex; 
            align-items: center; 
            justify-content: center; 
            gap: 10px;
            box-shadow: var(--shadow-primary);
        }
        .btn-primary:hover { 
            transform: translateY(-2px); 
            box-shadow: var(--shadow-xl);
        }

        /* Modern Micro-animations */
        @keyframes item-pop {
            0% { transform: scale(0.85); opacity: 0; }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); opacity: 1; }
        }

        .shortcuts-hint {
            position: fixed;
            bottom: 24px;
            left: 24px;
            display: flex;
            gap: 14px;
            z-index: 50;
            background: var(--glass-bg);
            backdrop-filter: var(--glass-blur);
            -webkit-backdrop-filter: var(--glass-blur);
            padding: 10px 20px;
            border-radius: var(--radius-full);
            border: 2px solid var(--glass-border);
            box-shadow: var(--shadow-lg);
            font-size: 0.75rem;
            color: var(--gray-600);
            font-weight: 600;
        }
        .kbd { 
            background: rgba(255, 255, 255, 0.9); 
            border: 2px solid var(--gray-200); 
            border-radius: var(--radius-sm); 
            padding: 4px 8px; 
            color: var(--primary); 
            font-weight: 800; 
            box-shadow: var(--shadow-sm); 
            margin-right: 6px;
            min-width: 28px;
            text-align: center;
        }

        /* Modern Mobile Responsiveness */
        @media (max-width: 1024px) {
            .pos-cart { width: 340px; }
            .product-grid { grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); }
        }
        @media (max-width: 768px) {
            .pos-main { flex-direction: column; overflow-y: auto; }
            .pos-cart { 
                width: 100%; 
                height: auto; 
                border-left: none; 
                border-top: 2px solid var(--glass-border); 
                position: sticky; 
                bottom: 0; 
                max-height: 70vh; 
                z-index: 200;
                border-radius: var(--radius-2xl) var(--radius-2xl) 0 0;
            }
            .pos-header { 
                padding: 0 16px; 
                gap: 12px; 
                height: auto; 
                min-height: auto; 
                flex-direction: column; 
                padding: 16px; 
                align-items: stretch;
            }
            .pos-header-left { 
                flex-direction: column; 
                align-items: flex-start; 
                gap: 12px; 
            }
            .pos-header-right { 
                max-width: none; 
                order: 3;
            }
            .pos-brand { 
                border-right: none; 
                padding-right: 0; 
            }
            .pos-categories { 
                padding: 0 16px; 
                gap: 8px;
            }
            .pos-products-grid { 
                padding: 16px; 
            }
            .product-grid { 
                grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); 
                gap: 16px;
            }
            .shortcuts-hint { display: none; }
            
            .cart-item { 
                padding: 12px 16px; 
                gap: 10px; 
            }
            .cart-item-thumb { 
                width: 40px; 
                height: 40px; 
            }
            .cart-item-name { 
                font-size: 0.85rem; 
            }
            .cart-item-total { 
                font-size: 0.85rem; 
                min-width: 55px; 
                padding: 4px 8px;
            }
            .qty-control { 
                padding: 3px; 
            }
            .qty-btn { 
                width: 24px; 
                height: 24px; 
            }
            .cart-qty-input { 
                width: 28px; 
                font-size: 0.85rem; 
            }
            
            .cart-footer {
                padding: 20px 16px;
            }
            
            .btn-checkout {
                height: 52px;
                font-size: 1rem;
            }
            
            .checkout-modal {
                max-width: 95%;
                margin: 16px;
            }
        }

        .spinner {
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,0.3);
            border-top-color: #fff;
            border-radius: 50%;
            animation: spin 0.8s linear infinite;
        }
        @keyframes spin { to { transform: rotate(360deg); } }
        .hidden { display: none !important; }
        
        /* Empty State */
        .empty-state {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 60px 20px;
            color: var(--gray-400);
            text-align: center;
        }
        .empty-state svg {
            width: 64px;
            height: 64px;
            margin-bottom: 16px;
            opacity: 0.5;
        }
        .empty-state h3 {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--gray-500);
            margin-bottom: 8px;
        }
        .empty-state p {
            font-size: 0.9rem;
            color: var(--gray-400);
        }
    </style>
</head>

<body>

<div class="pos-wrapper">
    <header class="pos-header">
        <div class="pos-header-left">
            <div class="pos-brand">
                <div class="pos-brand-icon">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20"><rect x="2" y="3" width="20" height="14" rx="2" ry="2"></rect><line x1="8" y1="21" x2="16" y2="21"></line><line x1="12" y1="17" x2="12" y2="21"></line></svg>
                </div>
                <span class="pos-brand-name">TellerPro</span>
            </div>

            <div class="pos-controls">
                <select id="location-select" class="pos-location-select">
                    <?php foreach ($locations as $l): ?>
                        <option value="<?= $l['id'] ?>" <?= ($l['is_default'] ?? false) ? 'selected' : '' ?>><?= e($l['name']) ?></option>
                    <?php endforeach; ?>
                </select>

                <button class="pos-customer-btn" onclick="document.getElementById('customerModal').classList.add('show')">
                    <div class="pos-customer-avatar" id="customer-avatar">W</div>
                    <span id="selected-customer-name">Walk-in</span>
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14"><polyline points="6 9 12 15 18 9"></polyline></svg>
                </button>
            </div>
        </div>

        <div class="pos-header-right">
            <div class="pos-search">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                <input type="text" id="product-search" placeholder="Search products, SKU, barcode..." autocomplete="off">
            </div>
        </div>
    </header>

    <main class="pos-main">
        <section class="pos-products">
            <div class="pos-categories" id="category-tabs">
                <button class="cat-tab active" data-category="all">All Products</button>
                <!-- Categories loaded via JS -->
            </div>
            
            <div class="pos-products-grid">
                <div id="product-list" class="product-grid"></div>
                <div id="no-results" class="empty-state hidden">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                    <h3>No products found</h3>
                    <p>Try a different search or select a category</p>
                </div>
            </div>
        </section>

        <aside class="pos-cart">
            <div class="cart-header">
                <div class="cart-title">
                    <div class="cart-icon">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
                    </div>
                    <span class="font-bold">Current Order</span>
                    <span class="cart-count" id="cart-count">0</span>
                </div>
                <button class="btn btn-ghost btn-sm" onclick="cart.clear()" title="Clear cart" style="border-radius: 8px; padding: 4px;">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
                </button>
            </div>
            
            <div class="cart-items" id="cart-item-list"></div>
            
            <div class="cart-empty" id="cart-empty">
                <div class="cart-empty-icon">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="36"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
                </div>
                <p class="font-medium">Cart is empty</p>
                <p class="text-sm">Click products to add them</p>
            </div>

            <div class="cart-footer">
                <div class="cart-actions-row">
                    <button class="cart-action-btn" onclick="discount.open()">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18"><path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z"></path><line x1="7" y1="7" x2="7.01" y2="7"></line></svg>
                        Discount
                    </button>
                    <button class="cart-action-btn" onclick="order.hold()">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="12" y1="18" x2="12" y2="12"></line><line x1="9" y1="15" x2="15" y2="15"></line></svg>
                        Hold
                    </button>
                    <button class="cart-action-btn" onclick="order.recall()">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="18"><polyline points="1 4 1 10 7 10"></polyline><path d="M3.51 15a9 9 0 1 0 2.13-9.36L1 10"></path></svg>
                        Recall
                    </button>
                </div>
                
                <div class="cart-summary">
                    <div class="cart-summary-row">
                        <span class="cart-summary-label">Subtotal</span>
                        <span class="cart-summary-value" id="summary-subtotal"><?= setting('currency_symbol', 'GH₵') ?>0.00</span>
                    </div>
                    <div class="cart-summary-row">
                        <span class="cart-summary-label">Tax (<?= e(setting('tax_rate', '0%')) ?>)</span>
                        <span class="cart-summary-value" id="summary-tax"><?= setting('currency_symbol', 'GH₵') ?>0.00</span>
                    </div>
                    <div class="cart-summary-row discount">
                        <span class="cart-summary-value" id="summary-discount">-<?= setting('currency_symbol', 'GH₵') ?>0.00</span>
                    </div>
                    <div class="cart-total">
                        <span class="cart-total-icon">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20"><rect x="1" y="4" width="22" height="16" rx="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg>
                            Total
                        </span>
                        <span id="summary-total"><?= setting('currency_symbol', 'GH₵') ?>0.00</span>
                    </div>
                </div>

                <button class="btn-checkout" id="checkout-btn" disabled onclick="checkout.open()">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect><line x1="1" y1="10" x2="23" y2="10"></line></svg>
                    Checkout
                </button>
            </div>
        </aside>
    </main>
</div>

<div class="shortcuts-hint">
    <span class="kbd">F1</span> Search
    <span class="kbd">F3</span> Suspend
    <span class="kbd">F4</span> Payment
    <span class="kbd">Enter</span> Print
    <span class="kbd">Esc</span> Close
</div>

<!-- Customer Modal -->
<div class="modal-overlay" id="customerModal">
    <div class="checkout-modal" style="max-width: 420px;">
        <div class="modal-header">
            <h3 class="modal-title">Select Customer</h3>
            <button class="modal-close" onclick="document.getElementById('customerModal').classList.remove('show')">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
        </div>
        <div class="modal-body">
            <div class="pos-search mb-4">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>
                <input type="text" placeholder="Search customers..." class="received-input" style="font-size: 1rem; border-radius: 10px; padding-left: 44px; text-align: left;" onkeyup="customer.search(this.value)">
            </div>
            <div id="customer-results" class="flex flex-column gap-2" style="max-height: 300px; overflow-y: auto; margin-top: 15px;">
                <div class="p-3 border rounded cursor-pointer hover-bg" onclick="customer.select(0, 'Walk-in Customer', 'W')" style="border: 1px solid #f1f5f9; padding: 12px; border-radius: 10px; cursor: pointer; transition: all 0.2s;">
                    <strong>Walk-in Customer</strong>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Discount Modal -->
<div class="modal-overlay" id="discountModal">
    <div class="checkout-modal" style="max-width: 380px;">
        <div class="modal-header">
            <h3 class="modal-title">Apply Discount</h3>
            <button class="modal-close" onclick="document.getElementById('discountModal').classList.remove('show')">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
        </div>
        <div class="modal-body">
            <div class="received-input-group">
                <label>Discount Amount</label>
                <input type="number" id="discount-value" class="received-input" placeholder="0.00" step="0.01" min="0">
            </div>
            <div class="quick-amounts" style="margin-top: 15px;">
                <button class="quick-amount" onclick="setDiscount(5)">5%</button>
                <button class="quick-amount" onclick="setDiscount(10)">10%</button>
                <button class="quick-amount" onclick="setDiscount(15)">15%</button>
                <button class="quick-amount" onclick="setDiscount(20)">20%</button>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-ghost" onclick="document.getElementById('discountModal').classList.remove('show')">Cancel</button>
            <button class="btn btn-primary" onclick="discount.apply()">Apply</button>
        </div>
    </div>
</div>

<!-- Out of Stock Warning Modal -->
<div class="modal-overlay" id="outOfStockModal">
    <div class="checkout-modal" style="max-width: 400px; border: 2px solid #ef4444;">
        <div class="modal-header" style="background: linear-gradient(135deg, #ef4444, #dc2626); border-bottom: none;">
            <h3 class="modal-title" style="color: #fff;">⚠️ Out of Stock</h3>
            <button class="modal-close" onclick="document.getElementById('outOfStockModal').classList.remove('show')" style="color: #fff;">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
        </div>
        <div class="modal-body" style="text-align: center; padding: 32px 24px;">
            <div style="width: 80px; height: 80px; background: #fef2f2; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px;">
                <svg viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2" width="40"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>
            </div>
            <h4 style="font-size: 1.2rem; font-weight: 800; color: #1f2937; margin-bottom: 8px;">This product is out of stock</h4>
            <p style="color: #6b7280; font-size: 0.9rem; margin-bottom: 20px;">Please select a different product or check inventory.</p>
            <button class="btn btn-primary" onclick="document.getElementById('outOfStockModal').classList.remove('show')" style="width: 100%; background: #ef4444;">Got it</button>
        </div>
    </div>
</div>

<!-- Checkout Modal -->
<div class="modal-overlay" id="checkoutModal">
    <div class="checkout-modal">
        <div class="modal-header">
            <h3 class="modal-title">Checkout</h3>
            <button class="modal-close" onclick="document.getElementById('checkoutModal').classList.remove('show')">
                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
            </button>
        </div>
        <div class="modal-body">
            <div class="payable-amount">
                <div class="payable-label">Payable Amount</div>
                <div class="payable-value" id="checkout-payable-amount"><?= setting('currency_symbol', 'GH₵') ?>0.00</div>
            </div>

            <div class="payment-methods" id="payment-methods-container">
                <?php
                // Hardcode to only show Cash payment method for now or use settings
                $paymentMethods = ['cash'];
                $paymentMethodLabels = [];
                $defaultPaymentMethod = 'cash';
                $defaultMethods = ['cash' => 'Cash'];
                foreach ($paymentMethods as $index => $method):
                    $label = $paymentMethodLabels[$method] ?? ($defaultMethods[$method] ?? ucfirst($method));
                    $isActive = $method === $defaultPaymentMethod ? 'active' : '';
                ?>
                <div class="payment-method <?= $isActive ?>" onclick="checkout.setMethod('<?= $method ?>', this)" data-method="<?= $method ?>">
                    <div class="payment-method-icon">
                        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="20"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"></rect><line x1="1" y1="10" x2="23" y2="10"></line></svg>
                    </div>
                    <div class="payment-method-label"><?= e($label) ?></div>
                </div>
                <?php endforeach; ?>
            </div>

            <div class="quick-amounts" id="quick-amounts"></div>

            <div class="received-input-group">
                <label>Amount Received</label>
                <input type="number" id="received-amount" class="received-input" placeholder="0.00" step="0.01" onkeyup="checkout.calcChange()">
            </div>

            <div class="change-display" id="change-display">
                <div class="change-label">Change to Return</div>
                <div class="change-value" id="return-change"><?= setting('currency_symbol', 'GH₵') ?>0.00</div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-ghost" onclick="document.getElementById('checkoutModal').classList.remove('show')">Back</button>
            <button class="btn btn-primary" id="confirmCheckoutBtn" onclick="checkout.process()">
                Complete Sale
                <div class="spinner hidden" id="checkout-spinner" style="margin-left: 8px;"></div>
            </button>
        </div>
    </div>
</div>

<script>
const CONFIG = {
    url: '<?= APP_URL ?>',
    taxRate: <?= (float)setting('tax_rate', '0') ?>,
    currency: '<?= setting('currency_symbol', 'GH₵') ?>',
    allowOverselling: <?= isOversellingAllowed() ? 'true' : 'false' ?>,
    csrf: '<?= Security::generateCsrfToken() ?>'
};

const cart = {
    items: [],
    customerId: 0,
    customerName: 'Walk-in Customer',
    customerInitial: 'W',
    discount: 0,

    add: function(product) {
        const stockQty = parseFloat(product.stock_qty || 0);
        const existing = this.items.find(i => i.product_id === product.id);
        
        if (!CONFIG.allowOverselling && stockQty <= 0) {
            document.getElementById('outOfStockModal').classList.add('show');
            return;
        }

        if (existing) {
            if (!CONFIG.allowOverselling && existing.quantity >= stockQty) {
                document.getElementById('outOfStockModal').classList.add('show');
                return;
            }
            existing.quantity++;
        } else {
            this.items.push({
                product_id: product.id,
                name: product.name,
                unit_price: parseFloat(product.selling_price),
                quantity: 1,
                unit: product.unit,
                image: product.image,
                stock_qty: product.stock_qty || 0
            });
        }
        
        const el = document.querySelector(`[data-product-id="${product.id}"]`);
        if (el) {
            el.classList.add('adding');
            setTimeout(() => el.classList.remove('adding'), 150);
        }
        
        this.render();
    },

    updateQty: function(idx, diff) {
        diff = parseFloat(diff);
        const item = this.items[idx];
        const stockQty = parseFloat(item.stock_qty || 0);
        item.quantity += diff;
        if (item.quantity <= 0) {
            this.items.splice(idx, 1);
            this.render();
            return;
        }
        if (stockQty > 0 && item.quantity > stockQty) {
            document.getElementById('outOfStockModal').classList.add('show');
            item.quantity = stockQty;
        }
        this.render();
    },

    setQty: function(idx, qty) {
        qty = parseFloat(qty);
        if (isNaN(qty) || qty <= 0) {
            this.items.splice(idx, 1);
        } else {
            const item = this.items[idx];
            const stockQty = parseFloat(item.stock_qty || 0);
            if (stockQty > 0 && qty > stockQty) {
                document.getElementById('outOfStockModal').classList.add('show');
                qty = stockQty;
            }
            this.items[idx].quantity = qty;
        }
        this.render();
    },

    remove: function(idx) {
        this.items.splice(idx, 1);
        this.render();
    },

    clear: function() {
        if (this.items.length > 0 && confirm('Clear all items from cart?')) {
            this.items = [];
            this.discount = 0;
            this.render();
        }
    },

    render: function() {
        const list = document.getElementById('cart-item-list');
        const empty = document.getElementById('cart-empty');
        const count = document.getElementById('cart-count');
        
        list.innerHTML = '';
        
        if (this.items.length === 0) {
            empty.style.display = 'flex';
            list.style.display = 'none';
            count.textContent = '0';
        } else {
            empty.style.display = 'none';
            list.style.display = 'block';
            count.textContent = this.items.reduce((a, b) => a + (this.items[0].unit === 'pcs' ? Math.floor(b.quantity) : b.quantity), 0);
            
            let subtotal = 0;
            this.items.forEach((item, idx) => {
                const rowTotal = item.unit_price * item.quantity;
                subtotal += rowTotal;

                const div = document.createElement('div');
                div.className = 'cart-item';
                div.innerHTML = `
                    <div class="cart-item-thumb">
                        ${item.image ? `<img src="${CONFIG.url}/uploads/<?= Auth::tenantId() ?>/${item.image}">` : ''}
                    </div>
                    <div class="cart-item-info">
                        <div class="cart-item-name">${item.name}</div>
                        <div class="cart-item-price">${CONFIG.currency}${item.unit_price.toFixed(2)}</div>
                    </div>
                    <div class="cart-item-actions">
                        <div class="qty-control">
                            <button class="qty-btn" onclick="cart.updateQty(${idx}, -1)">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14"><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                            </button>
                            <input type="number" class="cart-qty-input" value="${item.quantity}" min="0.01" step="0.01" onchange="cart.setQty(${idx}, this.value)">
                            <button class="qty-btn" onclick="cart.updateQty(${idx}, 1)">
                                <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                            </button>
                        </div>
                        <button class="qty-btn remove" onclick="cart.remove(${idx})" title="Remove">
                            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path></svg>
                        </button>
                    </div>
                    <div class="cart-item-total">${CONFIG.currency}${rowTotal.toFixed(2)}</div>
                `;
                list.appendChild(div);
            });

            // Update product badges
            document.querySelectorAll('.product-item').forEach(el => el.classList.remove('in-cart'));
            this.items.forEach(item => {
                const el = document.querySelector(`[data-product-id="${item.product_id}"]`);
                if (el) {
                    el.classList.add('in-cart');
                    const badge = el.querySelector('.product-qty-badge');
                    if (badge) badge.textContent = item.quantity;
                }
            });
        }

        const subtotalWithTax = subtotal; 
        const total = subtotalWithTax - this.discount;
        const tax = total - (total / (1 + (CONFIG.taxRate / 100)));

        document.getElementById('summary-subtotal').innerText = CONFIG.currency + subtotal.toFixed(2);
        document.getElementById('summary-tax').innerText = CONFIG.currency + tax.toFixed(2);
        document.getElementById('summary-discount').innerText = '-' + CONFIG.currency + this.discount.toFixed(2);
        document.getElementById('summary-total').innerText = CONFIG.currency + Math.max(0, total).toFixed(2);
        document.getElementById('checkout-btn').disabled = this.items.length === 0;
        
        this.subtotal = subtotal;
        this.tax = tax;
        this.total = Math.max(0, total);
    }
};

const customer = {
    select: function(id, name, initial) {
        cart.customerId = id;
        cart.customerName = name;
        cart.customerInitial = initial;
        document.getElementById('selected-customer-name').innerText = name.length > 12 ? name.substring(0, 12) + '...' : name;
        document.getElementById('customer-avatar').innerText = initial;
        document.getElementById('customerModal').classList.remove('show');
    },
    search: function(q) {
        if (!q) return;
        fetch(CONFIG.url + '/customers/search?q=' + q)
        .then(res => res.json())
        .then(data => {
            const results = document.getElementById('customer-results');
            results.innerHTML = `<div class="p-3 border rounded cursor-pointer hover-bg" onclick="customer.select(0, 'Walk-in Customer', 'W')" style="border: 1px solid #f1f5f9; padding: 12px; border-radius: 10px; cursor: pointer;"><strong>Walk-in Customer</strong></div>`;
            data.forEach(c => {
                const initial = c.name ? c.name.charAt(0).toUpperCase() : '?';
                const div = document.createElement('div');
                div.className = 'p-3 border rounded cursor-pointer hover-bg';
                div.style = 'border: 1px solid #f1f5f9; padding: 12px; border-radius: 10px; cursor: pointer; margin-top: 8px;';
                div.onclick = () => customer.select(c.id, c.name, initial);
                div.innerHTML = `<strong>${c.name}</strong><br><small class="text-muted">${c.phone || ''}</small>`;
                results.appendChild(div);
            });
        });
    }
};

const discount = {
    open: function() {
        if (cart.items.length === 0) {
            alert('Add items to cart first');
            return;
        }
        document.getElementById('discount-value').value = '';
        document.getElementById('discountModal').classList.add('show');
    },
    apply: function() {
        const val = parseFloat(document.getElementById('discount-value').value) || 0;
        if (val > 0) {
            cart.discount = val;
            cart.render();
        }
        document.getElementById('discountModal').classList.remove('show');
    }
};

function setDiscount(percent) {
    cart.discount = (cart.subtotal) * (percent / 100);
    cart.render();
    document.getElementById('discountModal').classList.remove('show');
}

const order = {
    hold: function() { alert('Order hold feature coming soon'); },
    recall: function() { alert('Order recall feature coming soon'); }
};

const checkout = {
    method: 'cash',
    open: function() {
        document.getElementById('checkout-payable-amount').innerText = CONFIG.currency + cart.total.toFixed(2);
        document.getElementById('received-amount').value = cart.total.toFixed(2);
        
        // Generate quick amounts
        const base = Math.ceil(cart.total);
        const quickAmounts = [base, base + 10, base + 20, base + 50, base + 100];
        const qaContainer = document.getElementById('quick-amounts');
        qaContainer.innerHTML = quickAmounts.map(a => `<button class="quick-amount" onclick="checkout.setReceived(${a})">${CONFIG.currency}${a}</button>`).join('');
        
        this.calcChange();
        document.getElementById('checkoutModal').classList.add('show');
    },
    setMethod: function(method, el) {
        this.method = method;
        document.querySelectorAll('.payment-method').forEach(m => m.classList.remove('active'));
        el.classList.add('active');
    },
    setReceived: function(amount) {
        document.getElementById('received-amount').value = amount;
        this.calcChange();
    },
    calcChange: function() {
        const received = parseFloat(document.getElementById('received-amount').value) || 0;
        const change = Math.max(0, received - cart.total);
        document.getElementById('return-change').innerText = CONFIG.currency + change.toFixed(2);
        
        const display = document.getElementById('change-display');
        if (received >= cart.total) {
            display.style.background = 'var(--aura-emerald)';
            display.style.color = '#fff';
        } else if (received > 0) {
            display.style.background = '#f59e0b';
            display.style.color = '#fff';
        } else {
            display.style.background = '#f1f5f9';
            display.style.color = 'var(--aura-slate)';
        }
    },
    process: function() {
        const received = parseFloat(document.getElementById('received-amount').value) || 0;
        if (received < cart.total) {
            alert('Insufficient amount received');
            return;
        }
        
        const btn = document.getElementById('confirmCheckoutBtn');
        const spinner = document.getElementById('checkout-spinner');
        
        btn.disabled = true;
        spinner.classList.remove('hidden');

        const payload = {
            location_id: document.getElementById('location-select').value,
            customer_id: cart.customerId,
            items: cart.items,
            subtotal: cart.subtotal,
            tax: cart.tax,
            discount: cart.discount,
            total: cart.total,
            paid_amount: received,
            payment_method: this.method
        };

        fetch(CONFIG.url + '/sales/pos/store', {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': CONFIG.csrf
            },
            body: JSON.stringify(payload)
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                alert('Sale completed successfully!');
                window.location = CONFIG.url + '/sales/' + data.sale_id;
            } else {
                alert('Error: ' + (data.error || 'Check server logs'));
                btn.disabled = false;
                spinner.classList.add('hidden');
            }
        })
        .catch(err => {
            alert('Request failed');
            btn.disabled = false;
            spinner.classList.add('hidden');
        });
    }
};

const products = {
    currentCategory: 'all',
    
    loadCategories: function() {
        fetch(CONFIG.url + '/sales/pos/categories')
        .then(res => res.json())
        .then(data => {
            const tabs = document.getElementById('category-tabs');
            // Keep the 'All' button but clear the rest
            tabs.innerHTML = '<button class="cat-tab active" data-category="all">All Products</button>';
            
            data.forEach(cat => {
                const btn = document.createElement('button');
                btn.className = 'cat-tab';
                btn.dataset.category = cat.id;
                btn.textContent = cat.name;
                btn.onclick = () => {
                    document.querySelectorAll('.cat-tab').forEach(t => t.classList.remove('active'));
                    btn.classList.add('active');
                    products.load(document.getElementById('product-search').value, cat.id);
                };
                tabs.appendChild(btn);
            });
        });
    },
    
    load: function(q = '', category = 'all') {
        const list = document.getElementById('product-list');
        const empty = document.getElementById('no-results');
        
        this.currentCategory = category;
        const categoryParam = category === 'all' ? '' : '&category_id=' + category;
        
        fetch(CONFIG.url + '/sales/pos/products?q=' + q + categoryParam)
        .then(res => res.json())
        .then(data => {
            list.innerHTML = '';
            if (data.length === 0) {
                empty.classList.remove('hidden');
            } else {
                empty.classList.add('hidden');
                data.forEach(p => {
                    const inCart = cart.items.find(i => i.product_id === p.id);
                    const qty = inCart ? inCart.quantity : 0;
                    const stockQty = parseFloat(p.stock_qty);
                    const stockClass = stockQty <= 0 ? 'out' : stockQty < 10 ? 'low' : 'in';
                    const stockLabel = stockQty <= 0 ? 'Out' : stockQty < 10 ? 'Low' : 'In stock';
                    
                    const div = document.createElement('div');
                    div.className = 'product-item' + (qty > 0 ? ' in-cart' : '') + (stockQty <= 0 ? ' out-of-stock' : '');
                    div.setAttribute('data-product-id', p.id);
                    div.onclick = () => {
                        if (stockQty <= 0 && !CONFIG.allowOverselling) {
                            document.getElementById('outOfStockModal').classList.add('show');
                            return;
                        }
                        cart.add(p);
                    };
                    div.innerHTML = `
                        <div class="product-qty-badge">${qty}</div>
                        <div class="product-img">
                            ${p.image ? `<img src="${CONFIG.url}/uploads/<?= Auth::tenantId() ?>/${p.image}">` : '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" class="product-placeholder"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect><circle cx="8.5" cy="8.5" r="1.5"></circle><polyline points="21 15 16 10 5 21"></polyline></svg>'}
                        </div>
                        <div class="product-info">
                            <div class="product-name">${p.name}</div>
                            <div class="product-price-row">
                                <span class="product-price">${CONFIG.currency}${parseFloat(p.selling_price).toFixed(2)}</span>
                                <span class="product-stock ${stockClass}">${stockQty <= 0 ? 'OUT OF STOCK' : stockLabel}</span>
                            </div>
                        </div>
                    `;
                    list.appendChild(div);
                });
            }
        });
    }
};

// Category Selection
document.querySelectorAll('.cat-tab').forEach(tab => {
    tab.onclick = function() {
        document.querySelectorAll('.cat-tab').forEach(t => t.classList.remove('active'));
        this.classList.add('active');
        products.load(document.getElementById('product-search').value, this.dataset.category);
    };
});

// Search debouncing
let searchTimeout;
document.getElementById('product-search').oninput = function(e) {
    clearTimeout(searchTimeout);
    searchTimeout = setTimeout(() => products.load(e.target.value, products.currentCategory), 300);
};

// Key bindings
document.addEventListener('keydown', (e) => {
    if (e.key === 'F1') {
        e.preventDefault();
        document.getElementById('product-search').focus();
    } else if (e.key === 'F4') {
        e.preventDefault();
        if (cart.items.length > 0) checkout.open();
    } else if (e.key === 'Escape') {
        document.querySelectorAll('.modal-overlay.show').forEach(m => m.classList.remove('show'));
    }
});

// Initial load
products.loadCategories();
products.load();
</script>

</body>
</html>
