<?php
include '_head.php';
if($_SERVER['REQUEST_METHOD']=='POST'){
  $parent=(int)$_POST['parent_id'];
  $en=mysqli_real_escape_string($conn,$_POST['name_en']);
  $ar=mysqli_real_escape_string($conn,$_POST['name_ar']);
  $ku=mysqli_real_escape_string($conn,$_POST['name_ku']);
  $sort=(int)$_POST['sort_order'];
  $status=isset($_POST['status'])?1:0;
  $img=upload_file('image','uploads/categories');
  $banner=upload_file('banner_image','uploads/banners');
  mysqli_query($conn,"INSERT INTO categories(parent_id,name_en,name_ar,name_ku,image,banner_image,sort_order,status) VALUES($parent,'$en','$ar','$ku','$img','$banner',$sort,$status)");
}
if(isset($_GET['delete'])){mysqli_query($conn,"DELETE FROM categories WHERE id=".(int)$_GET['delete']);}
$parents=mysqli_query($conn,"SELECT * FROM categories WHERE parent_id=0 OR parent_id IS NULL ORDER BY sort_order ASC,id ASC");
$rs=mysqli_query($conn,"SELECT c.*, p.name_en parent_name FROM categories c LEFT JOIN categories p ON c.parent_id=p.id ORDER BY c.parent_id ASC,c.sort_order ASC,c.id ASC");
?>
<h1>Categories / الأقسام</h1>
<form class="admin-card admin-form" method="post" enctype="multipart/form-data">
  <label>Parent category / القسم الأب</label>
  <select name="parent_id"><option value="0">Main Category / قسم رئيسي</option><?php if($parents): while($p=mysqli_fetch_assoc($parents)): ?><option value="<?php echo (int)$p['id']; ?>"><?php echo e($p['name_en'].' - '.$p['name_ar']); ?></option><?php endwhile; endif; ?></select>
  <input name="name_en" placeholder="English name" required>
  <input name="name_ar" placeholder="Arabic name">
  <input name="name_ku" placeholder="Kurdish name">
  <label>Category icon/image / صورة صغيرة للقسم</label>
  <input type="file" name="image" accept="image/*">
  <label>Section banner image / صورة عرض القسم مثل 00</label>
  <input type="file" name="banner_image" accept="image/*">
  <input name="sort_order" placeholder="Sort order" value="0">
  <label><input type="checkbox" name="status" checked> Active</label>
  <button class="primary-btn">Add Category</button>
</form>
<table class="table"><tr><th>ID</th><th>Icon</th><th>Banner</th><th>Name</th><th>Parent</th><th>Sort</th><th>Status</th><th></th></tr><?php while($r=mysqli_fetch_assoc($rs)): ?><tr><td><?php echo (int)$r['id']; ?></td><td><?php if($r['image']): ?><img class="admin-thumb" src="../<?php echo e($r['image']); ?>"><?php endif; ?></td><td><?php if($r['banner_image']): ?><img class="admin-banner-thumb" src="../<?php echo e($r['banner_image']); ?>"><?php endif; ?></td><td><?php echo e($r['name_en']); ?><br><small><?php echo e($r['name_ar']); ?></small></td><td><?php echo e($r['parent_name']); ?></td><td><?php echo (int)$r['sort_order']; ?></td><td><?php echo $r['status']?'Active':'Hidden'; ?></td><td><a onclick="return confirm('Delete?')" href="?delete=<?php echo (int)$r['id']; ?>">Delete</a></td></tr><?php endwhile; ?></table>
<?php include '_foot.php'; ?>
