<?php // app/Views/admin/settings/index.php ?>
<div class="space-y-6" x-data="settingsCalc()">

    <!-- Toast Notifications -->
    <?php if (isset($_GET['msg'])): ?>
    <div x-data="{ show: true }" x-show="show" x-init="setTimeout(() => show = false, 4000)" class="fixed bottom-5 right-5 z-50 flex items-center p-4 rounded-xl border shadow-lg text-emerald-400 bg-slate-900 border-emerald-500/30 transition-all duration-300 transform hover:scale-105">
        <i class="fas fa-check-circle text-lg mr-3"></i>
        <span class="text-sm font-medium"><?php echo htmlspecialchars($_GET['msg']); ?></span>
    </div>
    <?php endif; ?>

    <?php if (isset($_GET['error'])): ?>
    <div x-data="{ show: true }" x-show="show" x-init="setTimeout(() => show = false, 4000)" class="fixed bottom-5 right-5 z-50 flex items-center p-4 rounded-xl border shadow-lg text-red-400 bg-slate-900 border-red-500/30 transition-all duration-300 transform hover:scale-105">
        <i class="fas fa-exclamation-circle text-lg mr-3"></i>
        <span class="text-sm font-medium"><?php echo htmlspecialchars($_GET['error']); ?></span>
    </div>
    <?php endif; ?>

    <!-- Header -->
    <div class="rounded-2xl p-6 flex items-center justify-between shadow-xl" style="background: linear-gradient(135deg, #1e1b4b, #0d1117); border: 1px solid rgba(255,255,255,0.03)">
        <div>
            <h2 class="text-2xl font-bold text-white mb-1"><i class="fas fa-sliders-h mr-2 text-purple-400"></i>Restaurant Settings</h2>
            <p class="text-purple-300/70 text-sm">Configure restaurant profile details, tax rates, and default checkout discounts.</p>
        </div>
        <div class="hidden md:flex w-14 h-14 rounded-2xl items-center justify-center shadow-inner" style="background:rgba(139,92,246,0.12); border:1px solid rgba(139,92,246,0.2)">
            <i class="fas fa-cog text-2xl text-purple-400"></i>
        </div>
    </div>

    <!-- Main Settings Form -->
    <form action="/restpo/admin/settings/update" method="POST" enctype="multipart/form-data">
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">

            <!-- Left 2 Columns: Profile & Branding Settings -->
            <div class="lg:col-span-2 space-y-6">
                
                <!-- Restaurant Profile Card -->
                <div class="rounded-2xl p-6 shadow-md" style="background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06)">
                    <div class="flex items-center gap-3 mb-6">
                        <div class="w-10 h-10 rounded-xl flex items-center justify-center shadow-inner" style="background:rgba(139,92,246,0.15)">
                            <i class="fas fa-store text-purple-400"></i>
                        </div>
                        <div>
                            <h3 class="text-white font-semibold text-sm">Restaurant Info</h3>
                            <p class="text-slate-500 text-xs">Branding, address and customer contact credentials</p>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <!-- Name -->
                        <div>
                            <label class="block text-xs font-semibold text-slate-400 mb-1.5">Restaurant Name *</label>
                            <input type="text" name="name" required 
                                   value="<?php echo htmlspecialchars($restaurant['name'] ?? ''); ?>"
                                   class="w-full px-4 py-2.5 rounded-lg text-white text-sm outline-none transition focus:ring-2 focus:ring-purple-500/50" 
                                   style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                        </div>

                        <!-- Phone -->
                        <div>
                            <label class="block text-xs font-semibold text-slate-400 mb-1.5">Contact Phone</label>
                            <input type="text" name="phone" 
                                   value="<?php echo htmlspecialchars($restaurant['phone'] ?? ''); ?>"
                                   class="w-full px-4 py-2.5 rounded-lg text-white text-sm outline-none transition focus:ring-2 focus:ring-purple-500/50" 
                                   style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                        </div>

                        <!-- Address -->
                        <div class="md:col-span-2">
                            <label class="block text-xs font-semibold text-slate-400 mb-1.5">Physical Address</label>
                            <textarea name="address" rows="3" placeholder="Enter physical restaurant address to print on receipts..." 
                                      class="w-full px-4 py-2.5 rounded-lg text-white text-sm outline-none transition focus:ring-2 focus:ring-purple-500/50 resize-none" 
                                      style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)"><?php echo htmlspecialchars($restaurant['address'] ?? ''); ?></textarea>
                        </div>

                        <!-- Currency Selector -->
                        <div>
                            <label class="block text-xs font-semibold text-slate-400 mb-1.5">Default Currency</label>
                            <select name="currency" class="w-full px-4 py-2.5 rounded-lg text-white text-sm outline-none transition focus:ring-2 focus:ring-purple-500/50" style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                                <option value="$" <?php echo ($restaurant['currency'] ?? '$') === '$' ? 'selected' : ''; ?>>$ (USD)</option>
                                <option value="৳" <?php echo ($restaurant['currency'] ?? '') === '৳' ? 'selected' : ''; ?>>৳ (BDT)</option>
                            </select>
                        </div>

                        <!-- Custom URL Slug Checker -->
                        <div class="md:col-span-2" x-data="slugChecker('<?php echo htmlspecialchars($restaurant['slug'] ?? ''); ?>')">
                            <label class="block text-xs font-semibold text-slate-400 mb-1.5">Custom Menu Slug (Unique URL)</label>
                            <div class="relative">
                                <span class="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500 text-xs font-semibold">/restpo/</span>
                                <input type="text" name="slug" x-model="slug" @input.debounce.300ms="checkSlug()" placeholder="myburger"
                                       class="w-full pl-20 pr-10 py-2.5 rounded-lg text-white text-sm outline-none transition focus:ring-2 focus:ring-purple-500/50" 
                                       style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                                <span class="absolute right-4 top-1/2 -translate-y-1/2 text-sm">
                                    <i x-show="checking" class="fas fa-spinner fa-spin text-purple-400"></i>
                                    <i x-show="!checking && slug && available" class="fas fa-check-circle text-emerald-400"></i>
                                    <i x-show="!checking && slug && !available" class="fas fa-times-circle text-red-400"></i>
                                </span>
                            </div>
                            <p class="text-[10px] mt-1.5 text-slate-500" x-show="!slug">Custom slug allows guests to access your menu via a shorter URL. e.g. /myburger/table_code</p>
                            <p class="text-[10px] mt-1.5 text-emerald-400" x-show="slug && available && !checking" style="display: none;">Slug is available! Menu link: <span class="font-semibold" x-text="'/' + slug"></span></p>
                            <p class="text-[10px] mt-1.5 text-red-400" x-show="slug && !available && !checking" style="display: none;">Slug is already taken or invalid.</p>
                        </div>
                    </div>
                </div>

                <!-- Operations & Printer Settings -->
                <div class="rounded-2xl p-6 shadow-md" style="background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06)">
                    <div class="flex items-center gap-3 mb-6">
                        <div class="w-10 h-10 rounded-xl flex items-center justify-center shadow-inner" style="background:rgba(139,92,246,0.15)">
                            <i class="fas fa-print text-purple-400"></i>
                        </div>
                        <div>
                            <h3 class="text-white font-semibold text-sm">Operations &amp; POS Printing</h3>
                            <p class="text-slate-500 text-xs">Configure order ID sequential flows and thermal slip controls</p>
                        </div>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <!-- Order ID Sequence Method -->
                        <div>
                            <label class="block text-xs font-semibold text-slate-400 mb-1.5">Order ID Sequence Flow</label>
                            <select name="order_id_flow" class="w-full px-4 py-2.5 rounded-lg text-white text-sm outline-none transition focus:ring-2 focus:ring-purple-500/50" style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                                <option value="global" <?php echo ($settings['order_id_flow'] ?? 'global') === 'global' ? 'selected' : ''; ?>>Global Sequence (Restaurant-wide)</option>
                                <option value="session" <?php echo ($settings['order_id_flow'] ?? '') === 'session' ? 'selected' : ''; ?>>Session Sequence (Per Cashier Session)</option>
                                <option value="cashier" <?php echo ($settings['order_id_flow'] ?? '') === 'cashier' ? 'selected' : ''; ?>>Cashier Sequence (Per Cashier User)</option>
                            </select>
                            <p class="text-[10px] text-slate-500 mt-1.5">Determines how daily order serial numbers are incremented.</p>
                        </div>

                        <!-- Thermal Printer size selection -->
                        <div>
                            <label class="block text-xs font-semibold text-slate-400 mb-1.5">Thermal Print Size</label>
                            <select name="thermal_printing_size" class="w-full px-4 py-2.5 rounded-lg text-white text-sm outline-none transition focus:ring-2 focus:ring-purple-500/50" style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                                <option value="80mm" <?php echo ($settings['thermal_printing_size'] ?? '80mm') === '80mm' ? 'selected' : ''; ?>>80mm Standard Roll Width</option>
                                <option value="58mm" <?php echo ($settings['thermal_printing_size'] ?? '') === '58mm' ? 'selected' : ''; ?>>58mm Small Roll Width</option>
                            </select>
                            <p class="text-[10px] text-slate-500 mt-1.5">Configures page margins and styling widths for layout receipts.</p>
                        </div>

                        <!-- Print popup configuration modes -->
                        <div class="md:col-span-2 border-t border-white/5 pt-4 space-y-4">
                            <h4 class="text-xs font-bold text-slate-300">POS Slip Printing Interactions</h4>
                            <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                                <!-- KOT print mode -->
                                <div class="p-3 rounded-lg border border-white/5 space-y-2" style="background:rgba(255,255,255,0.01)">
                                    <span class="text-xs font-bold text-white block">KOT Print Mode</span>
                                    <div class="space-y-1">
                                        <label class="flex items-center gap-2 text-2xs text-slate-400 cursor-pointer font-medium">
                                            <input type="radio" name="print_popup_kot" value="preview" <?php echo ($settings['print_popup_kot'] ?? 'silent') === 'preview' ? 'checked' : ''; ?> class="accent-purple-500">
                                            Show Preview Modal
                                        </label>
                                        <label class="flex items-center gap-2 text-2xs text-slate-400 cursor-pointer font-medium">
                                            <input type="radio" name="print_popup_kot" value="silent" <?php echo ($settings['print_popup_kot'] ?? 'silent') === 'silent' ? 'checked' : ''; ?> class="accent-purple-500">
                                            Silent / Auto-Print
                                        </label>
                                    </div>
                                </div>

                                <!-- Unpaid Bill print mode -->
                                <div class="p-3 rounded-lg border border-white/5 space-y-2" style="background:rgba(255,255,255,0.01)">
                                    <span class="text-xs font-bold text-white block">Draft Bill Mode</span>
                                    <div class="space-y-1">
                                        <label class="flex items-center gap-2 text-2xs text-slate-400 cursor-pointer font-medium">
                                            <input type="radio" name="print_popup_bill" value="preview" <?php echo ($settings['print_popup_bill'] ?? 'silent') === 'preview' ? 'checked' : ''; ?> class="accent-purple-500">
                                            Show Preview Modal
                                        </label>
                                        <label class="flex items-center gap-2 text-2xs text-slate-400 cursor-pointer font-medium">
                                            <input type="radio" name="print_popup_bill" value="silent" <?php echo ($settings['print_popup_bill'] ?? 'silent') === 'silent' ? 'checked' : ''; ?> class="accent-purple-500">
                                            Silent / Auto-Print
                                        </label>
                                    </div>
                                </div>

                                <!-- Paid Receipt print mode -->
                                <div class="p-3 rounded-lg border border-white/5 space-y-2" style="background:rgba(255,255,255,0.01)">
                                    <span class="text-xs font-bold text-white block">Final Receipt Mode</span>
                                    <div class="space-y-1">
                                        <label class="flex items-center gap-2 text-2xs text-slate-400 cursor-pointer font-medium">
                                            <input type="radio" name="print_popup_receipt" value="preview" <?php echo ($settings['print_popup_receipt'] ?? 'silent') === 'preview' ? 'checked' : ''; ?> class="accent-purple-500">
                                            Show Preview Modal
                                        </label>
                                        <label class="flex items-center gap-2 text-2xs text-slate-400 cursor-pointer font-medium">
                                            <input type="radio" name="print_popup_receipt" value="silent" <?php echo ($settings['print_popup_receipt'] ?? 'silent') === 'silent' ? 'checked' : ''; ?> class="accent-purple-500">
                                            Silent / Auto-Print
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Restaurant Logo Card -->
                <div class="rounded-2xl p-6 shadow-md" style="background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06)">
                    <div class="flex items-center gap-3 mb-6">
                        <div class="w-10 h-10 rounded-xl flex items-center justify-center shadow-inner" style="background:rgba(139,92,246,0.15)">
                            <i class="fas fa-image text-purple-400"></i>
                        </div>
                        <div>
                            <h3 class="text-white font-semibold text-sm">Restaurant Logo</h3>
                            <p class="text-slate-500 text-xs">Used on the cashier POS header, KOT print, and invoices</p>
                        </div>
                    </div>

                    <div x-data="{ logoPreview: '<?php echo !empty($restaurant['logo']) ? '/restpo/' . htmlspecialchars($restaurant['logo']) : ''; ?>' }">
                        <div class="flex flex-col sm:flex-row items-center gap-6 p-4 rounded-xl" style="background:rgba(255,255,255,0.015); border: 1px dashed rgba(255,255,255,0.08)">
                            <!-- Preview Box -->
                            <div class="relative w-28 h-28 rounded-2xl overflow-hidden border border-white/10 bg-slate-950 flex items-center justify-center flex-shrink-0 shadow-inner group">
                                <template x-if="logoPreview">
                                    <img :src="logoPreview" class="w-full h-full object-cover group-hover:scale-105 transition duration-300" alt="Logo preview">
                                </template>
                                <template x-if="!logoPreview">
                                    <div class="text-center text-slate-600">
                                        <i class="fas fa-store text-3xl mb-1"></i>
                                        <p class="text-[9px]">NO LOGO</p>
                                    </div>
                                </template>
                            </div>
                            
                            <!-- Controls -->
                            <div class="flex-1 text-center sm:text-left space-y-3">
                                <div>
                                    <input type="file" name="logo" id="logo-upload" accept="image/*" class="hidden" 
                                           @change="const file = $event.target.files[0]; if (file) { const reader = new FileReader(); reader.onload = (e) => { logoPreview = e.target.result; }; reader.readAsDataURL(file); }">
                                    <label for="logo-upload" class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl font-semibold text-slate-300 text-sm hover:text-white hover:bg-white/10 border border-white/15 cursor-pointer shadow-md transition active:scale-95" style="background:rgba(255,255,255,0.04)">
                                        <i class="fas fa-cloud-upload-alt text-purple-400"></i> Choose New Logo
                                    </label>
                                </div>
                                <p class="text-[11px] text-slate-500"><i class="fas fa-info-circle mr-1 text-purple-400/70"></i>Supports PNG, JPG, JPEG, WEBP or GIF formats. Maximum file size of 2MB.</p>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

            <!-- Right 1 Column: Configurations & Taxes -->
            <div class="space-y-6">

                <!-- Tax Rate Card -->
                <div class="rounded-2xl p-6 shadow-md" style="background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06)">
                    <div class="flex items-center gap-3 mb-5">
                        <div class="w-10 h-10 rounded-xl flex items-center justify-center shadow-inner" style="background:rgba(139,92,246,0.15)">
                            <i class="fas fa-percent text-purple-400"></i>
                        </div>
                        <div>
                            <h3 class="text-white font-semibold text-sm">Tax Rate</h3>
                            <p class="text-slate-500 text-xs">Standard tax rate on subtotals</p>
                        </div>
                    </div>
                    <div class="relative">
                        <input type="number" name="tax_rate" step="0.01" min="0" max="100"
                               value="<?php echo htmlspecialchars($tax_rate); ?>"
                               x-model.number="taxRate"
                               class="w-full pl-4 pr-10 py-2.5 rounded-lg text-white font-bold text-sm outline-none transition focus:ring-2 focus:ring-purple-500/50" 
                               style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                        <span class="absolute right-4 top-1/2 -translate-y-1/2 text-slate-500 font-bold text-sm">%</span>
                    </div>
                    <p class="text-[10px] text-slate-500 mt-2"><i class="fas fa-info-circle mr-1"></i>Applied after auto-discounts. Enter 0 to disable.</p>
                </div>

                <!-- Discount Rate Card -->
                <div class="rounded-2xl p-6 shadow-md" style="background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.06)">
                    <div class="flex items-center gap-3 mb-5">
                        <div class="w-10 h-10 rounded-xl flex items-center justify-center shadow-inner" style="background:rgba(245,158,11,0.15)">
                            <i class="fas fa-tag text-amber-400"></i>
                        </div>
                        <div>
                            <h3 class="text-white font-semibold text-sm">Default Discount</h3>
                            <p class="text-slate-500 text-xs">Global auto-applied customer discount</p>
                        </div>
                    </div>
                    <div class="relative">
                        <input type="number" name="discount_rate" step="0.01" min="0" max="100"
                               value="<?php echo htmlspecialchars($discount_rate); ?>"
                               x-model.number="discountRate"
                               class="w-full pl-4 pr-10 py-2.5 rounded-lg text-white font-bold text-sm outline-none transition focus:ring-2 focus:ring-amber-500/50" 
                               style="background:rgba(255,255,255,0.05); border:1px solid rgba(255,255,255,0.08)">
                        <span class="absolute right-4 top-1/2 -translate-y-1/2 text-slate-500 font-bold text-sm">%</span>
                    </div>
                    <p class="text-[10px] text-slate-500 mt-2"><i class="fas fa-info-circle mr-1"></i>Automatically deducted from checkout. Enter 0 to disable.</p>
                </div>

                <!-- Live Preview Card -->
                <div class="rounded-2xl p-6 shadow-lg border" style="background:rgba(139,92,246,0.04); border-color:rgba(139,92,246,0.15)">
                    <div class="flex items-center gap-2 mb-4">
                        <i class="fas fa-calculator text-purple-400 text-sm"></i>
                        <h4 class="text-white font-bold text-xs uppercase tracking-wider">Calculation Preview</h4>
                    </div>
                    <div class="space-y-3">
                        <div class="flex justify-between text-xs py-1.5 border-b border-white/5">
                            <span class="text-slate-400">Sample Order</span>
                            <span class="text-white font-semibold">$100.00</span>
                        </div>
                        <div class="flex justify-between text-xs py-1.5 border-b border-white/5">
                            <span class="text-amber-400/80">Discount (<span x-text="discountRate"></span>%)</span>
                            <span class="text-amber-400 font-semibold">-$<span x-text="discountAmount"></span></span>
                        </div>
                        <div class="flex justify-between text-xs py-1.5 border-b border-white/5">
                            <span class="text-purple-400/80">Tax (<span x-text="taxRate"></span>%)</span>
                            <span class="text-purple-400 font-semibold">+$<span x-text="taxAmount"></span></span>
                        </div>
                        <div class="flex justify-between text-sm py-2 font-bold">
                            <span class="text-emerald-400">Total Order</span>
                            <span class="text-emerald-400">$<span x-text="totalAmount"></span></span>
                        </div>
                    </div>
                </div>



            </div>

        </div>

        <!-- Form Submission -->
        <div class="flex justify-end mt-6">
            <button type="submit" class="inline-flex items-center gap-2 px-8 py-3 rounded-xl text-white font-bold text-sm shadow-xl active:scale-95 transition" style="background:linear-gradient(135deg, #a855f7, #7c3aed)">
                <i class="fas fa-save"></i> Save Settings Profile
            </button>
        </div>
    </form>
</div>

<script>
function slugChecker(initialSlug) {
    return {
        slug: initialSlug,
        originalSlug: initialSlug,
        checking: false,
        available: true,
        async checkSlug() {
            this.slug = this.slug.toLowerCase().replace(/[^a-z0-9\-_]/g, '');
            if (this.slug === this.originalSlug) {
                this.available = true;
                return;
            }
            if (!this.slug) {
                this.available = true;
                return;
            }
            this.checking = true;
            try {
                const res = await fetch('/restpo/admin/settings/check-slug', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ slug: this.slug })
                });
                const data = await res.json();
                this.available = data.available;
                this.slug = data.slug;
            } catch (e) {
                this.available = false;
            } finally {
                this.checking = false;
            }
        }
    }
}

function settingsCalc() {
    return {
        taxRate: <?php echo floatval($tax_rate); ?>,
        discountRate: <?php echo floatval($discount_rate); ?>,
        get discountAmount() {
            return (100 * (this.discountRate || 0) / 100).toFixed(2);
        },
        get taxAmount() {
            const afterDiscount = 100 - (100 * (this.discountRate || 0) / 100);
            return (afterDiscount * (this.taxRate || 0) / 100).toFixed(2);
        },
        get totalAmount() {
            const afterDiscount = 100 - (100 * (this.discountRate || 0) / 100);
            const tax = afterDiscount * (this.taxRate || 0) / 100;
            return (afterDiscount + tax).toFixed(2);
        }
    }
}
</script>
