<?php
session_start();
$page_title = 'Tables & QR Codes';
$active_nav = 'tables';
include("includes/header.php");

$success=$error="";
$action=$_GET['action']??$_POST['action']??'';

// Ensure area_type column exists (Restaurant Table vs Location/Office QR)
$__col=@$conn->query("SHOW COLUMNS FROM restaurant_tables LIKE 'area_type'");
if($__col&&$__col->num_rows===0){
    @$conn->query("ALTER TABLE restaurant_tables ADD COLUMN area_type ENUM('table','location') NOT NULL DEFAULT 'table' AFTER table_number");
}

// Create / Edit table
if ($_SERVER['REQUEST_METHOD']==='POST'&&in_array($action,['create','edit'])&&$is_admin) {
    $table_num =trim($_POST['table_number']??'');
    $label     =trim($_POST['label']??'');
    $capacity  =(int)($_POST['capacity']??4);
    $tid       =(int)($_POST['table_id']??0);
    $area_type =(($_POST['area_type']??'table')==='location')?'location':'table';

    if (!$table_num) { $error=$area_type==='location'?"Location / office name is required.":"Table number is required."; }
    else {
        if ($action==='create') {
            // Build the QR URL (customer scan URL). Location QRs carry &tt=loc so the
            // customer side knows to show "ICT Office" instead of "Table ICT Office".
            $base_url = (isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']==='on'?'https':'http').'://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
            $menu_url = str_replace('/restaurantadmin','/customer',$base_url).'/scan.php?rid='.$__rid.'&table='.urlencode($table_num).($area_type==='location'?'&tt=loc':'');

            $ins=$conn->prepare("INSERT INTO restaurant_tables(restaurant_id,table_number,area_type,label,capacity) VALUES(?,?,?,?,?)");
            $ins->bind_param("isssi",$__rid,$table_num,$area_type,$label,$capacity); $ins->execute();
            $new_tid=$conn->insert_id;

            // Generate QR code path (actual QR library would go here)
            $qr_filename = "qr_r{$__rid}_t{$new_tid}.png";
            // We store the URL; QR rendering done in the view with Google Charts API
            $up=$conn->prepare("UPDATE restaurant_tables SET qr_code_path=? WHERE id=?");
            $up->bind_param("si",$menu_url,$new_tid); $up->execute();
        } else {
            $upd=$conn->prepare("UPDATE restaurant_tables SET table_number=?,area_type=?,label=?,capacity=? WHERE id=? AND restaurant_id=?");
            $upd->bind_param("sssiii",$table_num,$area_type,$label,$capacity,$tid,$__rid); $upd->execute();
        }
        // POST-redirect-GET so a refresh can't resubmit and the modal closes after save.
        header("Location: tables.php?msg=saved"); exit;
    }
}

// Delete table
if ($action==='delete'&&isset($_POST['id'])&&$is_admin) {
    $tid=(int)$_POST['id'];
    $s=$conn->prepare("DELETE FROM restaurant_tables WHERE id=? AND restaurant_id=?");
    $s->bind_param("ii",$tid,$__rid); $s->execute();
    header("Location: tables.php?msg=deleted"); exit;
}

$msg=$_GET['msg']??'';
if($msg==='deleted') $success="Table removed.";
if($msg==='saved')   $success="Saved successfully.";

// Fetch for edit
$edit_table=null;
if($action==='edit'&&isset($_GET['id'])) {
    $edit_id=(int)$_GET['id'];
    $st=$conn->prepare("SELECT * FROM restaurant_tables WHERE id=? AND restaurant_id=?");
    $st->bind_param("ii",$edit_id,$__rid); $st->execute();
    $edit_table=$st->get_result()->fetch_assoc();
}

// Fetch all tables
$tables_stmt=$conn->prepare("SELECT rt.*,
    (SELECT COUNT(*) FROM orders o WHERE o.table_number=rt.table_number AND o.restaurant_id=rt.restaurant_id AND DATE(o.created_at)=CURDATE()) as today_orders
    FROM restaurant_tables rt WHERE rt.restaurant_id=? ORDER BY rt.table_number");
$tables_stmt->bind_param("i",$__rid); $tables_stmt->execute();
$tables=$tables_stmt->get_result();

// Restaurant base URL for QR
$base_url=(isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']==='on'?'https':'http').'://'.$_SERVER['HTTP_HOST'];
$scan_base=$base_url.preg_replace('/\/restaurantadmin.*/','/customer/scan.php',$_SERVER['PHP_SELF']);
?>
<!-- QRCode.js — renders directly to canvas, no external image API needed -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<style>
.qr-target canvas{border-radius:8px;border:1px solid #E2E8F0;background:#fff;display:block!important;margin:0 auto}
@media print{
  *{-webkit-print-color-adjust:exact!important;print-color-adjust:exact!important}
  .sidebar,.topbar,.hamburger,.no-print,.order-alert,.overlay{display:none!important}
}
</style>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Tables & QR Codes</h1>
    <p style="color:var(--text-muted);font-size:.85rem">Each table has its own QR code customers scan to order</p>
  </div>
  <?php if($is_admin): ?>
  <button class="btn btn-primary btn-md" onclick="openModal('addTableModal')">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/></svg>
    Add Table
  </button>
  <?php endif; ?>
</div>

<?php if($success): ?><div class="alert alert-success"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><?php echo $success; ?></div><?php endif; ?>
<?php if($error): ?><div class="alert alert-error"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

<div class="alert alert-info">
  <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
  QR codes link customers directly to your menu. Click <strong>Print QR</strong> on any table to print it out and place it on the table.
</div>

<!-- Tables Grid -->
<?php if($tables->num_rows===0): ?>
<div class="card" style="padding:60px;text-align:center;color:var(--text-muted)">
  <svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block"><rect x="3" y="8" width="18" height="8" rx="2"/><path d="M6 8V6a1 1 0 011-1h10a1 1 0 011 1v2"/></svg>
  <p style="font-weight:700;margin-bottom:6px">No tables yet</p>
  <?php if($is_admin): ?><button class="btn btn-primary btn-md" onclick="openModal('addTableModal')" style="margin-top:12px">Add First Table</button><?php endif; ?>
</div>
<?php else: ?>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:18px">
  <?php while($t=$tables->fetch_assoc()):
    $is_location  = ($t['area_type']??'table')==='location';
    $display_name = $is_location ? $t['table_number'] : 'Table '.$t['table_number'];
    $menu_url = $scan_base.'?rid='.$__rid.'&table='.urlencode($t['table_number']).($is_location?'&tt=loc':'');
    $status_map=['available'=>['badge-success','Available'],'occupied'=>['badge-warning','Occupied'],'reserved'=>['badge-primary','Reserved']];
    [$sbadge,$slabel]=$status_map[$t['status']]??['badge-muted','Unknown'];
  ?>
  <div class="card" style="padding:20px;display:flex;flex-direction:column;gap:16px">
    <!-- QR Code rendered client-side via QRCode.js -->
    <div style="text-align:center;background:#fff;border-radius:12px;border:1px solid var(--border);padding:8px">
      <div class="qr-target" data-url="<?php echo htmlspecialchars($menu_url); ?>" data-size="160" data-id="qr-<?php echo $t['id']; ?>"></div>
    </div>

    <div>
      <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px">
        <div style="font-size:1.1rem;font-weight:800"><?php echo htmlspecialchars($display_name); ?></div>
        <span class="badge <?php echo $sbadge; ?>"><?php echo $slabel; ?></span>
      </div>
      <?php if($is_location): ?>
      <div style="font-size:.68rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--primary);margin-bottom:4px">Location / Office</div>
      <?php endif; ?>
      <?php if($t['label']): ?>
      <div style="font-size:.78rem;color:var(--text-muted);margin-bottom:4px"><?php echo htmlspecialchars($t['label']); ?></div>
      <?php endif; ?>
      <div style="font-size:.75rem;color:var(--text-muted)">
        Capacity: <strong><?php echo $t['capacity']; ?> seats</strong> &bull;
        Today's orders: <strong><?php echo $t['today_orders']; ?></strong>
      </div>
    </div>

    <!-- Actions -->
    <div style="display:flex;gap:7px;flex-wrap:wrap;border-top:1px solid var(--border);padding-top:14px">
      <button onclick="printQR('<?php echo $t['id']; ?>','<?php echo addslashes($display_name); ?>','<?php echo urlencode($menu_url); ?>')"
              class="btn btn-primary btn-sm" style="flex:1">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
        Print QR
      </button>
      <?php if($is_admin): ?>
      <a href="?action=edit&id=<?php echo $t['id']; ?>" class="btn btn-secondary btn-sm">Edit</a>
      <form method="POST" style="display:inline" onsubmit="return confirm('Remove <?php echo addslashes($display_name); ?>?')">
        <input type="hidden" name="action" value="delete">
        <input type="hidden" name="id" value="<?php echo $t['id']; ?>">
        <button class="btn btn-danger btn-sm">Del</button>
      </form>
      <?php endif; ?>
    </div>
  </div>
  <?php endwhile; ?>
</div>
<?php endif; ?>

<!-- Add Table Modal -->
<div class="modal-backdrop" id="addTableModal">
  <div class="modal">
    <div class="modal-header">
      <h3>Add New Table</h3>
      <button class="modal-close" onclick="closeModal('addTableModal')"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="create">
      <div class="modal-body">
        <div class="grid-2">
          <div class="form-group" style="grid-column:1/-1">
            <label>QR Type</label>
            <select name="area_type" class="form-control" onchange="toggleAreaType(this.value,'add')">
              <option value="table">Restaurant Table (dine-in)</option>
              <option value="location">Location / Office (order from anywhere)</option>
            </select>
            <div style="font-size:.72rem;color:var(--text-muted);margin-top:5px">Use <strong>Location / Office</strong> for organizations — e.g. staff ordering from their office.</div>
          </div>
          <div class="form-group"><label id="addNumLabel">Table Number *</label><input type="text" name="table_number" id="addNumInput" class="form-control" placeholder="e.g. 1, 2, VIP-1" required></div>
          <div class="form-group"><label>Capacity (seats)</label><input type="number" name="capacity" class="form-control" value="4" min="1" max="50"></div>
          <div class="form-group" style="grid-column:1/-1"><label>Label (optional)</label><input type="text" name="label" class="form-control" placeholder="e.g. Window Seat, Outdoor, 2nd Floor"></div>
        </div>
        <div class="alert alert-info" style="margin-top:4px">
          <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v4M12 16h.01"/></svg>
          A QR code will be generated automatically. Print it and place it on the table.
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('addTableModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md">Create Table & QR</button>
      </div>
    </form>
  </div>
</div>

<!-- Edit Table Modal -->
<?php if($edit_table): ?>
<div class="modal-backdrop" id="editTableModal" style="display:flex">
  <div class="modal">
    <?php $edit_is_loc = ($edit_table['area_type']??'table')==='location'; ?>
    <div class="modal-header">
      <h3>Edit <?php echo $edit_is_loc ? htmlspecialchars($edit_table['table_number']) : 'Table '.htmlspecialchars($edit_table['table_number']); ?></h3>
      <a href="tables.php" class="modal-close"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></a>
    </div>
    <form method="POST">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="table_id" value="<?php echo $edit_table['id']; ?>">
      <div class="modal-body">
        <div class="grid-2">
          <div class="form-group" style="grid-column:1/-1">
            <label>QR Type</label>
            <select name="area_type" class="form-control" onchange="toggleAreaType(this.value,'edit')">
              <option value="table" <?php echo !$edit_is_loc?'selected':''; ?>>Restaurant Table (dine-in)</option>
              <option value="location" <?php echo $edit_is_loc?'selected':''; ?>>Location / Office (order from anywhere)</option>
            </select>
          </div>
          <div class="form-group"><label id="editNumLabel"><?php echo $edit_is_loc?'Location / Office Name':'Table Number'; ?></label><input type="text" name="table_number" id="editNumInput" class="form-control" value="<?php echo htmlspecialchars($edit_table['table_number']); ?>" required></div>
          <div class="form-group"><label>Capacity</label><input type="number" name="capacity" class="form-control" value="<?php echo $edit_table['capacity']; ?>" min="1"></div>
          <div class="form-group" style="grid-column:1/-1"><label>Label</label><input type="text" name="label" class="form-control" value="<?php echo htmlspecialchars($edit_table['label']??''); ?>"></div>
        </div>
      </div>
      <div class="modal-footer">
        <a href="tables.php" class="btn btn-secondary btn-md">Cancel</a>
        <button type="submit" class="btn btn-primary btn-md">Save</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<!-- Print QR Modal -->
<div class="modal-backdrop" id="printModal">
  <div class="modal" style="max-width:400px">
    <div class="modal-header">
      <h3 id="printTitle">Print QR Code</h3>
      <button class="modal-close" onclick="closeModal('printModal')"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <div class="modal-body" style="text-align:center">
      <div id="printArea" style="padding:24px;border:2px dashed var(--border);border-radius:12px;display:inline-block;width:100%">
        <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:var(--text-muted);margin-bottom:8px">
          <?php echo htmlspecialchars($__rest_name); ?>
        </div>
        <div style="font-weight:800;font-size:1.1rem;margin-bottom:12px" id="printTableLabel">Table</div>
        <div id="printQrBox" style="width:200px;height:200px;margin:0 auto;display:flex;align-items:center;justify-content:center"></div>
        <div style="margin-top:12px;font-size:.75rem;color:var(--text-muted)">Scan to view menu & order</div>
        <div style="margin-top:6px">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round" style="margin:0 auto;display:block"><path d="M3 9l9-7 9 7v11a2 2 0 01-2 2H5a2 2 0 01-2-2z"/><polyline points="9 22 9 12 15 12 15 22"/></svg>
        </div>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary btn-md" onclick="closeModal('printModal')">Close</button>
      <button class="btn btn-primary btn-md" onclick="doPrint()">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><polyline points="6 9 6 2 18 2 18 9"/><path d="M6 18H4a2 2 0 01-2-2v-5a2 2 0 012-2h16a2 2 0 012 2v5a2 2 0 01-2 2h-2"/><rect x="6" y="14" width="12" height="8"/></svg>
        Print
      </button>
    </div>
  </div>
</div>

<script>
const QR_OPTIONS = { correctLevel: QRCode.CorrectLevel.M, colorDark: '#0F172A', colorLight: '#ffffff' };

/* Switch the number/name field label + placeholder with the chosen QR type */
function toggleAreaType(val, which){
  const lbl = document.getElementById(which + 'NumLabel');
  const inp = document.getElementById(which + 'NumInput');
  if (!lbl || !inp) return;
  if (val === 'location') {
    lbl.textContent = 'Location / Office Name *';
    inp.placeholder = 'e.g. ICT Office, HR Department, Reception';
  } else {
    lbl.textContent = 'Table Number *';
    inp.placeholder = 'e.g. 1, 2, VIP-1';
  }
}

/* Render every table's QR code (canvas-based, via QRCode.js) */
function renderAllQr(){
  document.querySelectorAll('.qr-target').forEach(el=>{
    if(el._done) return;
    el._done = true;
    const url = el.dataset.url;
    const size = parseInt(el.dataset.size) || 160;
    if(!url) return;
    try{ new QRCode(el, Object.assign({}, QR_OPTIONS, {text:url, width:size, height:size})); }
    catch(e){ el.innerHTML = '<p style="color:red;font-size:.7rem">QR error</p>'; }
  });
}
document.addEventListener('DOMContentLoaded', renderAllQr);

let _printRestName = <?php echo json_encode($__rest_name); ?>;

function printQR(id, displayName, menuUrlEncoded){
  const menuUrl = decodeURIComponent(menuUrlEncoded);
  document.getElementById('printTitle').textContent = 'Print QR — ' + displayName;
  document.getElementById('printTableLabel').textContent = displayName;

  const box = document.getElementById('printQrBox');
  box.innerHTML = '';
  new QRCode(box, Object.assign({}, QR_OPTIONS, {text: menuUrl, width: 200, height: 200}));

  openModal('printModal');
}

function doPrint(){
  const canvas = document.querySelector('#printQrBox canvas');
  const qrDataUrl = canvas ? canvas.toDataURL('image/png') : '';
  const tableLabel = document.getElementById('printTableLabel').textContent;

  const win = window.open('', '_blank', 'width=400,height=500');
  win.document.write(`<!DOCTYPE html><html><head><title>QR Code — ${tableLabel}</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;700;800&display=swap" rel="stylesheet">
    <style>
      *{box-sizing:border-box;margin:0;padding:0}
      body{font-family:'Plus Jakarta Sans',sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;background:#fff;padding:20px}
      .wrap{text-align:center;padding:26px 22px;border:2px dashed #CBD5E1;border-radius:16px;max-width:270px;width:100%}
      .rest{font-size:.6rem;font-weight:700;text-transform:uppercase;letter-spacing:.12em;color:#64748B;margin-bottom:10px}
      img{width:200px;height:200px;border-radius:9px;border:1px solid #E2E8F0;display:block;margin:0 auto}
      .name{font-size:1rem;font-weight:800;margin-top:12px;color:#0F172A}
      .hint{font-size:.7rem;color:#94A3B8;margin-top:10px}
      @media print{@page{margin:.6cm}}
    </style>
    </head><body><div class="wrap">
      <div class="rest">${_printRestName}</div>
      ${qrDataUrl ? `<img src="${qrDataUrl}" width="200" height="200">` : ''}
      <div class="name">${tableLabel}</div>
      <div class="hint">📱 Scan to view menu &amp; order</div>
    </div></body></html>`);
  win.document.close();
  win.onload = () => { win.focus(); setTimeout(()=>win.print(),400); };
}
</script>

<?php include("includes/footer.php"); ?>
