<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>
<?php
$s        = ROS_DB::get_all_settings();
$currency = $s['currency_symbol'] ?? '$';
$receipts = ROS_DB::get_receipts( 500 );
?>
<div class="ros-admin-wrap">
  <div class="ros-admin-header">
    <h1>🧾 Bonnen Archief</h1>
    <small style="color:#888;font-weight:400">Alle afgeronde bonnen</small>
  </div>

  <?php if ( empty( $receipts ) ): ?>
    <div class="ros-form-card"><p style="color:#888;text-align:center;padding:30px">Nog geen bonnen opgeslagen.</p></div>
  <?php else: ?>
  <table class="widefat ros-table">
    <thead>
      <tr>
        <th>#</th>
        <th>Tafel</th>
        <th>Datum & Tijd</th>
        <th>Betaalwijze</th>
        <th>Totaal</th>
        <th>Orders</th>
        <th>Actie</th>
      </tr>
    </thead>
    <tbody>
    <?php foreach ( $receipts as $r ):
      $pay_labels  = [ 'cash' => '💵 Cash', 'pin' => '💳 Pin', 'paypal' => '📱 PayPal' ];
      $pay_label   = $pay_labels[ $r['payment_method'] ] ?? ucfirst( $r['payment_method'] ?? '—' );
      $data        = json_decode( $r['receipt_data'], true );
      $order_count = $data ? count( $data['orders'] ?? [] ) : count( explode( ',', $r['order_ids'] ) );
    ?>
      <tr>
        <td><strong>#<?php echo esc_html( $r['id'] ); ?></strong></td>
        <td><?php echo esc_html( $r['table_name'] ); ?></td>
        <td><?php echo esc_html( date( 'd-m-Y H:i', strtotime( $r['created_at'] ) ) ); ?></td>
        <td><?php echo esc_html( $pay_label ); ?></td>
        <td><strong><?php echo esc_html( $currency . number_format( $r['grand_total'], 2 ) ); ?></strong></td>
        <td>
          <details>
            <summary><?php echo esc_html( $order_count ); ?> order<?php echo $order_count > 1 ? 's' : ''; ?></summary>
            <?php if ( $data && ! empty( $data['orders'] ) ): ?>
              <?php foreach ( $data['orders'] as $order ): ?>
                <div style="margin:6px 0 0 8px">
                  <strong style="font-size:0.8rem">Order #<?php echo esc_html( $order['id'] ); ?></strong>
                  <?php if ( $order['notes'] ?? '' ): ?> — <em style="font-size:0.75rem;color:#888"><?php echo esc_html( $order['notes'] ); ?></em><?php endif; ?>
                  <ul style="margin:3px 0 0 12px;font-size:0.78rem">
                    <?php foreach ( $data['items'] ?? [] as $item ): ?>
                      <?php if ( $item['order_id'] == $order['id'] ): ?>
                        <li><?php echo esc_html( $item['quantity'] . '× ' . $item['dish_name'] . ' — ' . $currency . number_format( $item['subtotal'], 2 ) ); ?></li>
                      <?php endif; ?>
                    <?php endforeach; ?>
                  </ul>
                </div>
              <?php endforeach; ?>
            <?php endif; ?>
          </details>
        </td>
        <td>
          <?php /* Use receipt ID — data fetched in JS from inline script tag, not from data- attribute */ ?>
          <button class="button button-small ros-admin-print" data-id="<?php echo intval( $r['id'] ); ?>">🖨️ Herdrukken</button>
        </td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
  <?php endif; ?>
</div>

<?php
/* Embed all receipt data safely as a JS object — no HTML encoding issues */
$receipts_js = [];
foreach ( $receipts as $r ) {
    $receipts_js[ intval( $r['id'] ) ] = json_decode( $r['receipt_data'], true );
}
?>
<script>
var ROS_RECEIPT_DATA = <?php echo wp_json_encode( $receipts_js ); ?>;

jQuery(function($){
  $('.ros-admin-print').on('click', function(){
    var id   = $(this).data('id');
    var data = ROS_RECEIPT_DATA[id];

    if(!data){
      alert('Geen bondata gevonden voor bon #'+id);
      return;
    }
    if(!data.items || !data.items.length){
      alert('Geen items gevonden in bon #'+id);
      return;
    }

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

    var html = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Bon #'+id+'</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;}'
             + '.order-hdr{font-weight:bold;font-size:11px;margin:6px 0 2px;padding-bottom:2px;border-bottom:1px solid #ccc;}'
             + '@media print{body{width:72mm;}@page{margin:0;size:72mm auto;}}'
             + '</style></head><body>';

    // Header
    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">'+(s.restaurant_name||'Restaurant')+'</div>';
    if(s.restaurant_address) html += '<div>'+s.restaurant_address+'</div>';
    if(s.restaurant_phone)   html += '<div>'+s.restaurant_phone+'</div>';
    html += '</div>';
    html += '<div class="line"></div>';
    html += '<div class="row"><span>'+(data.table_name||'Tafel')+'</span><span>'+dateStr+' '+timeStr+'</span></div>';
    html += '<div class="line"></div>';

    // Orders + items
    (data.orders||[]).forEach(function(order){
      html += '<div class="order-hdr">Order #'+order.id+'</div>';
      (data.items||[]).filter(function(i){ return String(i.order_id)===String(order.id); }).forEach(function(item){
        html += '<div class="row"><span>'+item.quantity+'x '+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">📝 '+order.notes+'</div>';
      }
    });

    // Total + payment
    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>';
    html += '<div class="center"><div class="stamp">BETAALD</div></div>';
    html += '<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  alert('Pop-up geblokkeerd. Sta pop-ups toe voor printen.');
  });
});
</script>
