/* Restaurant Order System — Kitchen JS v1.6.0
   Multi-order per table. Each order shown separately.
   Table card shows customer_closed when customer has requested to pay.
*/
(function($){
  'use strict';

  var KITCHEN = {
    orders:        [],
    tables:        [],
    tableSummary:  {},
    settings:      {},
    currentTable:  null,   // table_id being viewed
    pollTimer:     null,

    init: function(){
      this.loadSettings();
      this.startClock();
      this.bindEvents();
      this.fetchOrders();
      this.fetchReceipts();
      this.fetchReservations();
      this.pollTimer = setInterval(function(){
        KITCHEN.fetchOrders();
        KITCHEN.fetchReservations();
      }, 4000);
    },

    ajax: function(action, data, cb){
      $.post(rosData.ajax_url, $.extend({ action: action, nonce: rosData.nonce }, data), cb, 'json');
    },

    toast: function(msg, type){
      var t = $('<div class="ros-toast '+(type||'')+'">'+msg+'</div>');
      $('body').append(t);
      setTimeout(function(){ t.addClass('show'); }, 10);
      setTimeout(function(){ t.removeClass('show'); setTimeout(function(){ t.remove(); }, 400); }, 3500);
    },

    cur: function(){ return this.settings.currency_symbol || '$'; },

    startClock: function(){
      function tick(){
        var d=new Date();
        $('#ros-kitchen-clock').text(
          String(d.getHours()).padStart(2,'0')+':'+
          String(d.getMinutes()).padStart(2,'0')+':'+
          String(d.getSeconds()).padStart(2,'0')
        );
      }
      tick(); setInterval(tick,1000);
    },

    loadSettings: function(){
      this.ajax('ros_get_settings',{},function(r){
        if(!r.success) return;
        KITCHEN.settings = r.data;
        $('#ros-k-restaurant-name').text(r.data.restaurant_name||'Kitchen Display');
        if(r.data.logo_url) $('#ros-kitchen-logo').html('<img src="'+r.data.logo_url+'" alt="">');
      });
    },

    fetchOrders: function(){
      this.ajax('ros_kitchen_orders',{},function(r){
        if(!r.success) return;
        KITCHEN.orders       = r.orders||[];
        KITCHEN.tables       = r.tables||[];
        KITCHEN.tableSummary = r.table_summary||{};
        KITCHEN.renderTables();
        // Refresh detail view if open
        if(KITCHEN.currentTable !== null){
          KITCHEN.renderTableDetail(KITCHEN.currentTable);
        }
      });
    },

    /* ── TABLE OVERVIEW ── */
    renderTables: function(){
      var active=0, ready=0, needPay=0;
      Object.values(KITCHEN.tableSummary).forEach(function(s){
        active++;
        if(s.customer_closed) needPay++;
        else {
          var allReady = s.orders.every(function(o){ return o.status==='ready'; });
          if(allReady && s.orders.length) ready++;
        }
      });
      $('#ros-k-active-count').text(active);
      $('#ros-k-ready-count').text(ready+needPay);

      // Build map of active reservations
      var reservedMap = {};
      (this.reservations||[]).forEach(function(r){ reservedMap[r.table_id] = r; });

      var html='';
      KITCHEN.tables.forEach(function(t){
        var summary  = KITCHEN.tableSummary[t.id];
        var reserved = reservedMap[t.id];
        var tableNum = t.name.replace(/[^0-9]/g,'')||t.sort_order||'?';
        var labels   = { free:'Vrij', pending:'Nieuw!', accepted:'Geaccepteerd', preparing:'Bereiding', ready:'Klaar!', customer_closed:'Betalen!' };

        var shapes = window.ROS_SHAPES;
        var shapeSvg = function(state){ return shapes ? shapes.get(t.shape||'rect_4', state) : ''; };

        if(reserved && !summary){
          // Reserved, no active order
          var dt = new Date(reserved.arrival_time.replace(' ','T'));
          var timeStr = dt.toLocaleTimeString('nl-NL',{hour:'2-digit',minute:'2-digit'});
          html += '<div class="ros-k-table-card ros-k-card-reserved has-reservation" data-reservation="'+reserved.id+'" data-table="'+t.id+'">'
                + '<div class="ros-k-shape-svg">'+shapeSvg('reserved')+'</div>'
                + '<div class="ros-k-table-label">'+KITCHEN.esc(t.name)+'</div>'
                + '<div class="ros-k-table-status-tag ros-k-tag-reserved">Gereserveerd</div>'
                + '<div style="font-size:0.75rem;color:#bb8fe8;margin-top:5px;font-weight:700;">'+KITCHEN.esc(reserved.guest_name)+'</div>'
                + '<div style="font-size:0.7rem;color:rgba(255,255,255,0.35);">🕐 '+timeStr+' &nbsp;👥 '+reserved.persons+'p</div>'
                + '</div>';
          return;
        }

        if(!summary){
          // Truly free
          html += '<div class="ros-k-table-card ros-k-card-free" data-table="'+t.id+'">'
                + '<div class="ros-k-shape-svg">'+shapeSvg('free')+'</div>'
                + '<div class="ros-k-table-label">'+KITCHEN.esc(t.name)+'</div>'
                + '<div class="ros-k-table-status-tag ros-k-tag-free">Vrij</div>'
                + '</div>';
          return;
        }

        var orders    = summary.orders;
        var isClosed  = summary.customer_closed;
        var cardStatus;
        if(isClosed){
          cardStatus = 'customer_closed';
        } else {
          var priority = { pending:0, accepted:1, preparing:2, ready:3 };
          var worst    = 'ready';
          orders.forEach(function(o){
            if(typeof priority[o.status]!=='undefined' && priority[o.status]<priority[worst]) worst=o.status;
          });
          cardStatus = worst;
        }

        var blink = (cardStatus==='pending') ? ' ros-blink-card' : '';
        var orderCountTxt = orders.length > 1 ? orders.length+' orders' : '1 order';

        var svgState = cardStatus==='customer_closed' ? 'ready' : cardStatus;
        html += '<div class="ros-k-table-card ros-k-card-'+cardStatus+' has-order'+blink+'" data-table="'+t.id+'">'
              + '<div class="ros-k-shape-svg">'+shapeSvg(svgState)+'</div>'
              + '<div class="ros-k-table-label">'+KITCHEN.esc(t.name)+'</div>'
              + '<div class="ros-k-table-status-tag ros-k-tag-'+cardStatus+'">'+(labels[cardStatus]||cardStatus)+'</div>'
              + '<div class="ros-k-table-total">'+KITCHEN.cur()+parseFloat(summary.grand_total).toFixed(2)+'</div>'
              + '<div class="ros-k-table-items">'+orderCountTxt+'</div>'
              + '</div>';
      });

      if(!html) html='<p style="color:rgba(255,255,255,0.25);text-align:center;padding:60px;grid-column:1/-1">Geen tafels.</p>';
      $('#ros-kitchen-tables-grid').html(html);
    },


    /* ── TABLE DETAIL — shows ALL orders for that table ── */
    renderTableDetail: function(tableId){
      this.currentTable = tableId;
      var summary = this.tableSummary[tableId];
      var table   = this.tables.find(function(t){ return t.id==tableId; });
      if(!summary || !table){
        // Table is now free — go back
        this.currentTable = null;
        this.showKScreen('tables');
        return;
      }

      var tableName    = table.name;
      var isClosed     = summary.customer_closed;
      var orders       = summary.orders;
      var grandTotal   = summary.grand_total;

      // Header
      $('#ros-k-order-title').text(tableName+' — '+orders.length+' order'+(orders.length>1?'s':''));
      // Show payment method chosen by customer
      var payMethod = '';
      if(isClosed){
        var payMethods = orders.map(function(o){ return o.payment_method; }).filter(Boolean);
        var pm = payMethods[0]||'';
        var payLabels = { cash:'💵 Cash', pin:'🏦 Pin', stripe:'💳 Kaart betaald via Stripe', unknown:'—' };
        payMethod = payLabels[pm]||(pm?pm:'Niet opgegeven');
      }
      var timeInfo = isClosed
        ? '⚠️ Afgerond — Betaalwijze klant: '+payMethod
        : 'Actief';
      $('#ros-k-order-time').text(timeInfo);

      var statusCls = isClosed ? 'customer_closed' : '';
      var statusLbl = isClosed ? 'Betalen!' : 'Actief';
      $('#ros-k-status-badge').attr('class','ros-k-badge '+(isClosed?'customer_closed':'accepted')).text(statusLbl);

      // Render each order separately
      var self   = this;
      var itemsHtml = '';
      orders.forEach(function(order, idx){
        var statusLabels = { pending:'Nieuw', accepted:'Geaccepteerd', preparing:'Bereiding', ready:'Klaar!', customer_closed:'Afgerond' };
        var sLabel = statusLabels[order.status]||order.status;
        var sCls   = order.status;

        itemsHtml += '<div class="ros-k-order-block">';
        itemsHtml += '<div class="ros-k-order-block-header">';
        itemsHtml +=   '<span class="ros-k-order-block-num">Order #'+order.id+'</span>';
        itemsHtml +=   '<span class="ros-k-badge '+sCls+'" style="font-size:0.68rem;padding:3px 10px">'+sLabel+'</span>';
        itemsHtml += '</div>';

        (order.items||[]).forEach(function(item){
          itemsHtml += '<div class="ros-k-item">'
                    +  '<span class="ros-k-item-name">'+self.esc(item.dish_name)+'</span>'
                    +  '<span class="ros-k-item-meta">×'+item.quantity+'</span>'
                    +  '<span class="ros-k-item-sub">'+self.cur()+parseFloat(item.subtotal||0).toFixed(2)+'</span>'
                    +  '<span class="ros-k-item-qty">'+item.quantity+'</span>'
                    +  '</div>';
        });

        // Notes from customer
        if(order.notes && order.notes.trim()){
          itemsHtml += '<div class="ros-k-notes-block visible">📝 '+self.esc(order.notes)+'</div>';
        }

        // Per-order action buttons (only if not customer_closed and not already done)
        if(!isClosed && order.status !== 'customer_closed'){
          itemsHtml += '<div class="ros-k-order-actions">';
          if(order.status==='pending'){
            itemsHtml += '<button class="ros-k-action-btn ros-k-action-accept ros-k-do-status" style="font-size:0.82rem;padding:10px 16px" data-order="'+order.id+'" data-status="accepted">✅ Accepteren</button>';
          }
          if(order.status==='accepted'){
            itemsHtml += '<button class="ros-k-action-btn ros-k-action-prepare ros-k-do-status" style="font-size:0.82rem;padding:10px 16px" data-order="'+order.id+'" data-status="preparing">🔥 Bereiding</button>';
          }
          if(order.status==='preparing'){
            itemsHtml += '<button class="ros-k-action-btn ros-k-action-ready ros-k-do-status" style="font-size:0.82rem;padding:10px 16px" data-order="'+order.id+'" data-status="ready">🎉 Klaar</button>';
          }
          itemsHtml += '</div>';
        }

        itemsHtml += '</div>'; // ros-k-order-block
      });

      // Grand total row
      itemsHtml += '<div class="ros-k-total-row"><span>Totaal alle orders</span><strong>'+this.cur()+parseFloat(grandTotal).toFixed(2)+'</strong></div>';

      $('#ros-k-order-items').html(itemsHtml);
      $('#ros-k-order-notes').removeClass('visible').html('');

      // Payment section — only when customer has closed
      var actHtml = '';
      if(isClosed){
        actHtml += '<div class="ros-k-payment-block">';
        actHtml +=   '<div class="ros-k-panel-label" style="margin-bottom:10px">Betaalwijze kiezen & afsluiten</div>';
        actHtml +=   '<div class="ros-k-pay-methods">';
        actHtml +=     '<button class="ros-k-pay-btn" data-table="'+tableId+'" data-method="cash">💵 Cash</button>';
        actHtml +=     '<button class="ros-k-pay-btn" data-table="'+tableId+'" data-method="pin">💳 Pin</button>';
        actHtml +=     '<button class="ros-k-pay-btn" data-table="'+tableId+'" data-method="paypal">📱 PayPal</button>';
        actHtml +=   '</div>';
        actHtml += '</div>';
        actHtml += '<button class="ros-k-action-btn ros-k-action-print" data-table="'+tableId+'">🖨️ Bon Afdrukken (Preview)</button>';
      } else {
        actHtml += '<p style="color:rgba(255,255,255,0.3);font-size:0.82rem;text-align:center;padding:10px">Betaalknop verschijnt zodra klant afrondt.</p>';
        actHtml += '<button class="ros-k-action-btn ros-k-action-print" data-table="'+tableId+'">🖨️ Tussentijdse Bon</button>';
      }
      $('#ros-k-actions').html(actHtml);

      this.showKScreen('order');
    },

    /* ── RECEIPTS ARCHIVE ── */
    fetchReceipts: function(){
      $.post(rosData.ajax_url, { action:'ros_get_receipts', nonce:rosData.nonce }, function(r){
        if(!r||!r.success) return;
        KITCHEN.renderReceipts(r.receipts||[]);
      },'json');
    },

    renderReceipts: function(receipts){
      var cur = this.cur();
      if(!receipts.length){
        $('#ros-k-receipts-body').html('<tr><td colspan="5" style="text-align:center;padding:30px;color:rgba(255,255,255,0.3)">Nog geen bonnen opgeslagen.</td></tr>');
        return;
      }
      var html='';
      receipts.forEach(function(r){
        var payLabels={cash:'💵 Cash',pin:'💳 Pin',paypal:'📱 PayPal',''  :'—'};
        var payLabel=payLabels[r.payment_method||'']||(r.payment_method||'—');
        var dt = r.created_at ? new Date(r.created_at.replace(' ','T')) : new Date();
        var dateStr = dt.toLocaleDateString('nl-NL')+' '+dt.toLocaleTimeString('nl-NL',{hour:'2-digit',minute:'2-digit'});
        html+='<tr>'
            +'<td style="color:rgba(255,255,255,0.5)">#'+r.id+'</td>'
            +'<td><strong>'+KITCHEN.esc(r.table_name)+'</strong></td>'
            +'<td>'+dateStr+'</td>'
            +'<td>'+payLabel+'</td>'
            +'<td><strong style="color:#C9A96E">'+cur+parseFloat(r.grand_total).toFixed(2)+'</strong></td>'
            +'<td><button class="ros-k-reprint-btn" data-receipt="'+r.id+'">🖨️ Herdrukken</button>'
            +'<span class="ros-k-receipt-data" style="display:none">'+KITCHEN.esc(r.receipt_data||'{}')+'</span></td>'
            +'</tr>';
      });
      $('#ros-k-receipts-body').html(html);
    },

    /* ── RESERVATIONS ── */
    reservations: [],

    fetchReservations: function(){
      var self = this;
      this.ajax('ros_get_reservations',{},function(r){
        if(!r.success) return;
        self.reservations = r.reservations||[];
        self.renderReservations();
        self.populateTableSelect();
      });
    },

    populateTableSelect: function(){
      var self = this;
      var opts = '<option value="">— Kies tafel —</option>';
      // Only show free tables (no active order, no active reservation)
      var reservedIds = this.reservations.map(function(r){ return String(r.table_id); });
      var occupiedIds = Object.keys(this.tableSummary);
      this.tables.forEach(function(t){
        var isReserved = reservedIds.indexOf(String(t.id)) !== -1;
        var isOccupied = occupiedIds.indexOf(String(t.id)) !== -1;
        if(!isReserved && !isOccupied){
          opts += '<option value="'+t.id+'">'+self.esc(t.name)+' ('+t.seats+' pers.)</option>';
        }
      });
      $('#ros-reserv-table').html(opts);
    },

    renderReservations: function(){
      var self = this;
      if(!this.reservations.length){
        $('#ros-reserv-list').html('<p style="color:rgba(255,255,255,0.3);font-size:0.85rem;text-align:center;padding:20px">Geen actieve reserveringen.</p>');
        return;
      }
      var html='';
      this.reservations.forEach(function(r){
        var dt = new Date(r.arrival_time.replace(' ','T'));
        var dateStr = dt.toLocaleDateString('nl-NL',{weekday:'short',day:'numeric',month:'short'});
        var timeStr = dt.toLocaleTimeString('nl-NL',{hour:'2-digit',minute:'2-digit'});
        html += '<div class="ros-reserv-item">';
        html +=   '<div class="ros-reserv-item-info">';
        html +=     '<div class="ros-reserv-item-name">'+self.esc(r.guest_name)+'</div>';
        html +=     '<div class="ros-reserv-item-meta">';
        html +=       '<span>🕐 '+dateStr+' om '+timeStr+'</span>';
        html +=       '<span>👥 '+r.persons+' personen</span>';
        if(r.notes && r.notes.trim()) html += '<span>📝 '+self.esc(r.notes)+'</span>';
        html +=     '</div>';
        html +=   '</div>';
        html +=   '<span class="ros-reserv-table-badge">'+self.esc(r.table_name||'Tafel')+'</span>';
        html +=   '<button class="ros-reserv-release-btn" data-id="'+r.id+'" data-table="'+r.table_id+'">✖ Vrijgeven</button>';
        html += '</div>';
      });
      $('#ros-reserv-list').html(html);
    },

    /* ── RECEIPT PRINT ── */
    printReceipt: function(tableId, paymentMethod){
      // Preview print — fetches CURRENT session data only
      this.ajax('ros_get_receipt',{table_id:tableId},function(r){
        if(!r.success){KITCHEN.toast('Fout bij ophalen bon.','error');return;}
        var data = { table_name:r.table_name, orders:r.orders, items:r.items, grand_total:r.grand_total, settings:r.settings, payment_method:paymentMethod };
        KITCHEN.openPrintWindow(data, paymentMethod);
      });
    },

    openPrintWindow: function(data, paymentMethod){
      var s        = data.settings||{};
      var cur      = s.currency_symbol||'$';
      var method   = paymentMethod||data.payment_method||'';
      var now      = new Date();
      var dateStr  = now.toLocaleDateString('nl-NL');
      var timeStr  = now.toLocaleTimeString('nl-NL',{hour:'2-digit',minute:'2-digit'});
      var payLabels= {cash:'Cash',pin:'Pin/Kaart',paypal:'PayPal',''  :'—'};
      var payLabel = payLabels[method]||method||'—';

      var html = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Bon</title>'
               + '<style>*{margin:0;padding:0;box-sizing:border-box;}'
               + 'body{font-family:"Courier New",monospace;font-size:13px;color:#000;background:#fff;width:72mm;padding:4mm;}'
               + '.center{text-align:center;}.bold{font-weight:bold;}.large{font-size:15px;}'
               + '.line{border-top:1px dashed #000;margin:5px 0;}'
               + '.row{display:flex;justify-content:space-between;margin:2px 0;}'
               + '.logo{width:56px;height:56px;border-radius:50%;object-fit:cover;border:2px solid #000;margin:0 auto 6px;display:block;}'
               + '.stamp{border:3px solid #000;display:inline-block;padding:3px 12px;font-size:18px;font-weight:900;letter-spacing:3px;transform:rotate(-8deg);margin:8px auto;}'
               + '.section{margin:6px 0;}'
               + '.order-hdr{font-weight:bold;font-size:11px;margin:6px 0 2px;border-bottom:1px solid #ccc;}'
               + '@media print{body{width:72mm;}@page{margin:0;size:72mm auto;}}'
               + '</style></head><body>';

      html += '<div class="center">';
      if(s.logo_url) html+='<img class="logo" src="'+s.logo_url+'" alt="">';
      else           html+='<div style="font-size:26px;margin-bottom:6px">🍽️</div>';
      html += '<div class="bold large">'+KITCHEN.esc(s.restaurant_name||'Restaurant')+'</div>';
      if(s.restaurant_address) html+='<div>'+KITCHEN.esc(s.restaurant_address)+'</div>';
      if(s.restaurant_phone)   html+='<div>'+KITCHEN.esc(s.restaurant_phone)+'</div>';
      html += '</div><div class="line"></div>';
      html += '<div class="row"><span>'+KITCHEN.esc(data.table_name||'Tafel')+'</span><span>'+dateStr+' '+timeStr+'</span></div>';
      html += '<div class="line"></div>';

      // Each order with its items and notes
      var orders = data.orders||[];
      var items  = data.items||[];
      orders.forEach(function(order){
        html += '<div class="order-hdr">Order #'+order.id+'</div>';
        items.filter(function(i){ return String(i.order_id)===String(order.id); }).forEach(function(item){
          html += '<div class="row"><span>'+item.quantity+'x '+KITCHEN.esc(item.dish_name)+'</span><span>'+cur+parseFloat(item.subtotal||0).toFixed(2)+'</span></div>';
        });
        if(order.notes && order.notes.trim()){
          html += '<div style="font-size:11px;color:#555;margin:2px 0">📝 '+KITCHEN.esc(order.notes)+'</div>';
        }
      });

      html += '<div class="line"></div>';
      html += '<div class="row bold large"><span>TOTAAL</span><span>'+cur+parseFloat(data.grand_total||0).toFixed(2)+'</span></div>';
      html += '<div class="row"><span>Betaalwijze</span><span>'+payLabel+'</span></div>';
      html += '<div class="line"></div>';
      if(method) html += '<div class="center"><div class="stamp">BETAALD</div></div><div class="line"></div>';
      html += '<div class="center" style="font-size:11px">Bedankt voor uw bezoek!<br>Eet smakelijk!</div>';
      html += '<div style="height:20mm"></div>';
      html += '<script>window.onload=function(){window.print();window.onafterprint=function(){window.close();};};<\/script>';
      html += '</body></html>';

      var w=window.open('','_blank','width=400,height=600');
      if(w){w.document.write(html);w.document.close();}
      else KITCHEN.toast('Pop-up geblokkeerd. Sta pop-ups toe.','error');
    },

    showKScreen: function(id){
      $('.ros-kscreen').removeClass('active');
      $('#ros-kscreen-'+id).addClass('active');
    },

    bindEvents: function(){
      // Table card click
      $(document).on('click','.ros-k-table-card.has-order',function(){
        KITCHEN.renderTableDetail($(this).data('table'));
      });

      // Reserved table click — show quick info + release option
      $(document).on('click','.ros-k-table-card.has-reservation',function(){
        var resId   = $(this).data('reservation');
        var tableId = $(this).data('table');
        var name    = $(this).find('[style*="bb8fe8"]').text();
        if(confirm('Reservering voor "'+name+'" vrijgeven?')){
          KITCHEN.ajax('ros_release_reservation',{ reservation_id: resId, table_id: tableId }, function(r){
            if(r.success){
              KITCHEN.toast('✅ Tafel vrijgegeven','success');
              KITCHEN.fetchOrders();
              KITCHEN.fetchReservations();
            }
          });
        }
      });

      // Back
      $(document).on('click','#ros-k-back',function(){
        KITCHEN.currentTable=null;
        KITCHEN.showKScreen('tables');
      });

      // Per-order status update
      $(document).on('click','.ros-k-do-status',function(){
        var $btn=$(this).prop('disabled',true).css('opacity','0.6');
        var orderId=$(this).data('order');
        var status=$(this).data('status');
        var msgs={accepted:'✅ Geaccepteerd',preparing:'🔥 Bereiding gestart',ready:'🎉 Klaar voor tafel!'};

        KITCHEN.ajax('ros_update_status',{order_id:orderId,status:status},function(r){
          $btn.prop('disabled',false).css('opacity','1');
          if(!r.success){KITCHEN.toast('Fout: '+(r.message||'Onbekend'),'error');return;}
          KITCHEN.toast(msgs[status]||'Bijgewerkt','success');
          KITCHEN.fetchOrders();
        });
      });

      // Payment — close entire table
      $(document).on('click','.ros-k-pay-btn',function(){
        var $btn=$(this);
        var tableId=$btn.data('table');
        var method=$btn.data('method');
        $('.ros-k-pay-btn').removeClass('selected');
        $btn.addClass('selected').prop('disabled',true).css('opacity','0.7');

        KITCHEN.ajax('ros_kitchen_close_table',{table_id:tableId,payment_method:method},function(r){
          $btn.prop('disabled',false).css('opacity','1');
          if(!r.success){KITCHEN.toast('Fout bij afsluiten.','error');return;}
          KITCHEN.toast('💰 Betaald & tafel vrijgegeven!','success');
          // Use receipt_data returned directly from server — contains current session only
          KITCHEN.openPrintWindow(r.receipt_data, method);
          KITCHEN.currentTable=null;
          KITCHEN.showKScreen('tables');
          KITCHEN.fetchOrders();
          KITCHEN.fetchReceipts();
        });
      });

      // Print button (preview before payment)
      $(document).on('click','.ros-k-action-print',function(){
        KITCHEN.printReceipt($(this).data('table'),'');
      });

      // Tab switching via CSS class (inline styles in HTML handle defaults)
      function switchTab(activeId, screenId) {
        document.querySelectorAll('.ros-k-itab').forEach(function(el){
          el.classList.remove('ros-k-itab-active');
        });
        var el = document.getElementById(activeId);
        if(el) el.classList.add('ros-k-itab-active');
        KITCHEN.showKScreen(screenId);
      }

      $(document).on('click','#ros-k-tab-tables', function(){
        switchTab('ros-k-tab-tables','tables');
      });
      $(document).on('click','#ros-k-tab-reserv', function(){
        switchTab('ros-k-tab-reserv','reserv');
        KITCHEN.fetchReservations();
      });
      $(document).on('click','#ros-k-tab-receipts', function(){
        switchTab('ros-k-tab-receipts','receipts');
        KITCHEN.fetchReceipts();
      });

      // Submit reservation
      $(document).on('click','#ros-reserv-submit', function(){
        var tableId = $('#ros-reserv-table').val();
        var name    = $('#ros-reserv-name').val().trim();
        var time    = $('#ros-reserv-time').val();
        var persons = $('#ros-reserv-persons').val();
        var notes   = $('#ros-reserv-notes').val().trim();
        var $msg    = $('#ros-reserv-msg');

        if(!tableId || !name || !time){
          $msg.css({display:'block',background:'rgba(231,76,60,0.15)',color:'#e74c3c'}).text('Vul tafel, naam en aankomsttijd in.');
          return;
        }

        KITCHEN.ajax('ros_add_reservation',{
          table_id: tableId, guest_name: name,
          arrival_time: time, persons: persons, notes: notes
        }, function(r){
          if(!r.success){
            $msg.css({display:'block',background:'rgba(231,76,60,0.15)',color:'#e74c3c'}).text(r.message||'Fout bij opslaan.');
          } else {
            $msg.css({display:'block',background:'rgba(39,174,96,0.15)',color:'#27ae60'}).text('✅ Reservering opgeslagen!');
            $('#ros-reserv-name').val('');
            $('#ros-reserv-notes').val('');
            $('#ros-reserv-table').val('');
            KITCHEN.fetchReservations();
            KITCHEN.fetchOrders();
            setTimeout(function(){ $msg.fadeOut(); }, 3000);
          }
        });
      });

      // Release reservation
      $(document).on('click','.ros-reserv-release-btn', function(){
        var resId   = $(this).data('id');
        var tableId = $(this).data('table');
        if(!confirm('Reservering vrijgeven?')) return;
        KITCHEN.ajax('ros_release_reservation',{ reservation_id: resId, table_id: tableId }, function(r){
          if(r.success){
            KITCHEN.toast('Reservering vrijgegeven','success');
            KITCHEN.fetchReservations();
            KITCHEN.fetchOrders();
          }
        });
      });

      // Reprint from archive
      $(document).on('click','.ros-k-reprint-btn',function(){
        var raw=$(this).siblings('.ros-k-receipt-data').text()||'{}';
        try{
          var data=JSON.parse(raw);
          if(data&&data.items) KITCHEN.openPrintWindow(data, data.payment_method||'');
          else KITCHEN.toast('Geen bondata beschikbaar.','error');
        }catch(e){ KITCHEN.toast('Fout bij laden bon.','error'); }
      });
    },

    esc: function(str){ return $('<div>').text(str||'').html(); }
  };

  $(document).ready(function(){
    if($('#ros-kitchen-app').length) KITCHEN.init();
  });

})(jQuery);
