<?php
require_once 'config.inc.php';require_login();
if($_SERVER['REQUEST_METHOD']==='POST'){check_csrf();$op=$_POST['op']??'';
 if($op==='save'){ $id=(int)$_POST['id'];$name=trim($_POST['name']);
  try{if($id){$s=db()->prepare("UPDATE brands SET name=? WHERE id=?");$s->bind_param("si",$name,$id);}else{$s=db()->prepare("INSERT INTO brands(name) VALUES(?)");$s->bind_param("s",$name);}$s->execute();flash('success','Brand saved.');}
  catch(mysqli_sql_exception $e){flash('danger','Brand already exists.');} redirect('brands.php');
 }
 if($op==='delete'){try{$id=(int)$_POST['id'];$s=db()->prepare("DELETE FROM brands WHERE id=?");$s->bind_param("i",$id);$s->execute();flash('success','Brand deleted.');}catch(Throwable $e){flash('danger','Brand is being used and cannot be deleted.');}redirect('brands.php');}
}
$edit=null;if(isset($_GET['edit'])){$id=(int)$_GET['edit'];$s=db()->prepare("SELECT * FROM brands WHERE id=?");$s->bind_param("i",$id);$s->execute();$edit=$s->get_result()->fetch_assoc();}
$pageTitle='Brands';include 'partials/header.php';?>
<div class="row g-4"><div class="col-lg-4"><div class="card p-4"><h5><?=$edit?'Edit':'Add'?> Brand</h5><form method="post"><input type="hidden" name="csrf" value="<?=e(csrf())?>"><input type="hidden" name="op" value="save"><input type="hidden" name="id" value="<?=e($edit['id']??0)?>"><input class="form-control my-3" name="name" value="<?=e($edit['name']??'')?>" placeholder="Brand name" required><button class="btn btn-primary">Save</button></form></div></div>
<div class="col-lg-8"><div class="card p-4"><h5>Brand List</h5><table class="table align-middle"><thead><tr><th>Brand</th><th>Actions</th></tr></thead><tbody><?php $r=db()->query("SELECT * FROM brands ORDER BY name");while($b=$r->fetch_assoc()):?><tr><td><?=e($b['name'])?></td><td><a class="btn btn-sm btn-outline-secondary" href="?edit=<?=$b['id']?>">Edit</a><form class="d-inline" method="post"><input type="hidden" name="csrf" value="<?=e(csrf())?>"><input type="hidden" name="op" value="delete"><input type="hidden" name="id" value="<?=$b['id']?>"><button class="btn btn-sm btn-outline-danger" data-confirm="Delete this brand?">Delete</button></form></td></tr><?php endwhile;?></tbody></table></div></div></div>
<?php include 'partials/footer.php';?>
