<?php
require_once __DIR__ . '/../../includes/bootstrap.php';
require_login();
$pageTitle='Restaurant Tables';
if(!function_exists('h')){function h($v):string{return htmlspecialchars((string)$v,ENT_QUOTES,'UTF-8');}}
if(!function_exists('rt_flash')){function rt_flash($t,$m):void{$_SESSION['rt_flash'][]=['type'=>$t,'message'=>$m];} function rt_get_flash():array{$x=$_SESSION['rt_flash']??[];unset($_SESSION['rt_flash']);return $x;}}
try{
$pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_areas (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, property_id INT UNSIGNED NULL, area_name VARCHAR(120) NOT NULL, sort_order INT NOT NULL DEFAULT 1, is_active TINYINT(1) NOT NULL DEFAULT 1, created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
$pdo->exec("CREATE TABLE IF NOT EXISTS restaurant_tables (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, property_id INT UNSIGNED NULL, area_id INT UNSIGNED NULL, table_no VARCHAR(40) NOT NULL, table_name VARCHAR(120) NULL, seats INT UNSIGNED NOT NULL DEFAULT 2, pos_x INT NOT NULL DEFAULT 0, pos_y INT NOT NULL DEFAULT 0, shape ENUM('round','square','rect') NOT NULL DEFAULT 'round', status ENUM('available','occupied','reserved','dirty','blocked') NOT NULL DEFAULT 'available', is_active TINYINT(1) NOT NULL DEFAULT 1, created_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, INDEX idx_rest_table_area(area_id), INDEX idx_rest_table_status(status)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
}catch(Throwable $e){$errors[]=$e->getMessage();}
if(($_SERVER['REQUEST_METHOD']??'GET')==='POST'){
 try{if(function_exists('verify_csrf')) verify_csrf(); $a=$_POST['action']??'';
 if($a==='save_area'){ $id=(int)($_POST['id']??0); $n=trim((string)($_POST['area_name']??'')); if($n==='') throw new RuntimeException('Area name required.'); if($id>0){$pdo->prepare("UPDATE restaurant_areas SET area_name=:n,sort_order=:s,is_active=:ia WHERE id=:id")->execute([':n'=>$n,':s'=>(int)($_POST['sort_order']??1),':ia'=>(int)($_POST['is_active']??1),':id'=>$id]);}else{$pdo->prepare("INSERT INTO restaurant_areas(area_name,sort_order,is_active) VALUES(:n,:s,1)")->execute([':n'=>$n,':s'=>(int)($_POST['sort_order']??1)]);} rt_flash('success','Area saved.'); }
 if($a==='save_table'){ $id=(int)($_POST['id']??0); $no=trim((string)($_POST['table_no']??'')); if($no==='') throw new RuntimeException('Table number required.'); $p=[':area'=>(int)($_POST['area_id']??0)?:null,':no'=>$no,':name'=>trim((string)($_POST['table_name']??''))?:null,':seats'=>(int)($_POST['seats']??2),':x'=>(int)($_POST['pos_x']??0),':y'=>(int)($_POST['pos_y']??0),':shape'=>$_POST['shape']??'round',':status'=>$_POST['status']??'available',':active'=>(int)($_POST['is_active']??1)]; if($id>0){$p[':id']=$id;$pdo->prepare("UPDATE restaurant_tables SET area_id=:area,table_no=:no,table_name=:name,seats=:seats,pos_x=:x,pos_y=:y,shape=:shape,status=:status,is_active=:active WHERE id=:id")->execute($p);}else{$pdo->prepare("INSERT INTO restaurant_tables(area_id,table_no,table_name,seats,pos_x,pos_y,shape,status,is_active) VALUES(:area,:no,:name,:seats,:x,:y,:shape,:status,:active)")->execute($p);} rt_flash('success','Table saved.'); }
 header('Location: restaurant_tables.php'); exit;
 }catch(Throwable $e){rt_flash('danger',$e->getMessage());header('Location: restaurant_tables.php');exit;}
}
$flashes=rt_get_flash(); $areas=$pdo->query("SELECT * FROM restaurant_areas ORDER BY sort_order,area_name")->fetchAll(PDO::FETCH_ASSOC); $tables=$pdo->query("SELECT t.*,a.area_name FROM restaurant_tables t LEFT JOIN restaurant_areas a ON a.id=t.area_id ORDER BY a.sort_order,t.table_no")->fetchAll(PDO::FETCH_ASSOC);
require_once __DIR__.'/../../includes/header.php';
?>
<div class="hero-band compact-restaurant-hero"><div class="row align-items-center"><div class="col"><div class="page-eyebrow text-white-50"><i class="bi bi-grid-3x3-gap"></i> Restaurant Setup</div><div class="hero-title mt-1">Tables & Areas</div></div><div class="col-auto"><a href="restaurant_planner.php" class="btn btn-light btn-sm">Planner</a></div></div></div>
<?php foreach($flashes as $f):?><div class="alert alert-<?php echo h($f['type']);?>"><?php echo h($f['message']);?></div><?php endforeach;?>
<div class="row g-3"><div class="col-lg-4"><div class="card panel-card"><div class="card-header"><h5 class="mb-0">Area</h5></div><div class="card-body"><form method="post" id="areaForm"><?php if(function_exists('csrf_field')) echo csrf_field();?><input type="hidden" name="action" value="save_area"><input type="hidden" name="id" id="area_id"><label class="form-label">Area Name</label><input name="area_name" id="area_name" class="form-control" required><div class="row g-2 mt-1"><div class="col"><label class="form-label">Sort</label><input type="number" name="sort_order" id="area_sort" value="1" class="form-control"></div><div class="col"><label class="form-label">Active</label><select name="is_active" id="area_active" class="form-select"><option value="1">Yes</option><option value="0">No</option></select></div></div><button class="btn btn-primary w-100 mt-3">Save Area</button></form><hr><?php foreach($areas as $a):?><button class="btn btn-sm btn-light border mb-1 edit-area" data-json='<?php echo h(json_encode($a));?>'><?php echo h($a['area_name']);?></button> <?php endforeach;?></div></div></div><div class="col-lg-8"><div class="card panel-card"><div class="card-header"><h5 class="mb-0">Table</h5></div><div class="card-body"><form method="post" class="row g-2" id="tableForm"><?php if(function_exists('csrf_field')) echo csrf_field();?><input type="hidden" name="action" value="save_table"><input type="hidden" name="id" id="table_id"><div class="col-md-3"><label class="form-label">Area</label><select name="area_id" id="table_area" class="form-select"><option value="">None</option><?php foreach($areas as $a):?><option value="<?php echo (int)$a['id'];?>"><?php echo h($a['area_name']);?></option><?php endforeach;?></select></div><div class="col-md-2"><label class="form-label">Table No</label><input name="table_no" id="table_no" class="form-control" required></div><div class="col-md-3"><label class="form-label">Name</label><input name="table_name" id="table_name" class="form-control"></div><div class="col-md-2"><label class="form-label">Seats</label><input type="number" name="seats" id="table_seats" value="2" class="form-control"></div><div class="col-md-2"><label class="form-label">Shape</label><select name="shape" id="table_shape" class="form-select"><option>round</option><option>square</option><option>rect</option></select></div><div class="col-md-2"><label class="form-label">X</label><input type="number" name="pos_x" id="table_x" value="0" class="form-control"></div><div class="col-md-2"><label class="form-label">Y</label><input type="number" name="pos_y" id="table_y" value="0" class="form-control"></div><div class="col-md-3"><label class="form-label">Status</label><select name="status" id="table_status" class="form-select"><option>available</option><option>occupied</option><option>reserved</option><option>dirty</option><option>blocked</option></select></div><div class="col-md-2"><label class="form-label">Active</label><select name="is_active" id="table_active" class="form-select"><option value="1">Yes</option><option value="0">No</option></select></div><div class="col-md-3 d-flex align-items-end"><button class="btn btn-primary w-100">Save Table</button></div></form></div></div><div class="card panel-card mt-3"><div class="table-responsive"><table class="table table-modern mb-0"><thead><tr><th>Area</th><th>Table</th><th>Seats</th><th>Status</th><th>Position</th><th></th></tr></thead><tbody><?php foreach($tables as $t):?><tr><td><?php echo h($t['area_name']);?></td><td><strong><?php echo h($t['table_no']);?></strong><div class="small text-muted"><?php echo h($t['table_name']);?></div></td><td><?php echo (int)$t['seats'];?></td><td><span class="badge text-bg-light border"><?php echo h($t['status']);?></span></td><td><?php echo (int)$t['pos_x'];?>, <?php echo (int)$t['pos_y'];?></td><td class="text-end"><button class="btn btn-sm btn-outline-primary edit-table" data-json='<?php echo h(json_encode($t));?>'>Edit</button></td></tr><?php endforeach;?></tbody></table></div></div></div></div>
<style>.compact-restaurant-hero{padding:12px 16px!important;margin-bottom:10px!important}.panel-card{border-radius:16px;box-shadow:0 12px 30px rgba(15,23,42,.07)}.table-modern thead th{font-size:.72rem;text-transform:uppercase;color:#64748b;background:#f8fafc}</style>
<script>document.addEventListener('DOMContentLoaded',function(){document.querySelectorAll('.edit-area').forEach(b=>b.onclick=function(){const x=JSON.parse(this.dataset.json);area_id.value=x.id;area_name.value=x.area_name;area_sort.value=x.sort_order;area_active.value=x.is_active;});document.querySelectorAll('.edit-table').forEach(b=>b.onclick=function(){const x=JSON.parse(this.dataset.json);table_id.value=x.id;table_area.value=x.area_id||'';table_no.value=x.table_no||'';table_name.value=x.table_name||'';table_seats.value=x.seats||2;table_shape.value=x.shape||'round';table_x.value=x.pos_x||0;table_y.value=x.pos_y||0;table_status.value=x.status||'available';table_active.value=x.is_active||1;window.scrollTo({top:0,behavior:'smooth'});});});</script>
<?php require_once __DIR__.'/../../includes/footer.php'; ?>
