<?php
require_once __DIR__ . '/../includes/auth.php';

$id = (int)($_GET['id'] ?? 0);
$preset_cat = (int)($_GET['category_id'] ?? 0);
$row = ['id'=>0,'category_id'=>$preset_cat,'name'=>'','description'=>''];
$images = [];

if ($id) {
    $row = $conn->query("SELECT * FROM subcategories WHERE id=$id")->fetch_assoc() ?: $row;
    $res = $conn->query("SELECT * FROM subcategory_images WHERE subcategory_id=$id");
    while ($r = $res->fetch_assoc()) $images[] = $r;
}
$pageTitle = $id ? 'Edit Subcategory' : 'Add Subcategory';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $category_id = (int)$_POST['category_id'];
    $name = trim($_POST['name']);
    $desc = trim($_POST['description']);

    if ($id) {
        $stmt = $conn->prepare("UPDATE subcategories SET category_id=?, name=?, description=? WHERE id=?");
        $stmt->bind_param('issi', $category_id, $name, $desc, $id);
        $stmt->execute();
        $sid = $id;
    } else {
        $stmt = $conn->prepare("INSERT INTO subcategories (category_id, name, description) VALUES (?,?,?)");
        $stmt->bind_param('iss', $category_id, $name, $desc);
        $stmt->execute();
        $sid = $stmt->insert_id;
    }

    if (!empty($_POST['delete_images'])) {
        foreach ($_POST['delete_images'] as $img_id) {
            $img_id = (int)$img_id;
            $r = $conn->query("SELECT image_path FROM subcategory_images WHERE id=$img_id AND subcategory_id=$sid")->fetch_assoc();
            if ($r) { delete_image_file($r['image_path']); $conn->query("DELETE FROM subcategory_images WHERE id=$img_id"); }
        }
    }

    if (!empty($_FILES['images']['name'][0])) {
        $paths = upload_images($_FILES['images'], 'subcategories');
        foreach ($paths as $p) {
            $stmt = $conn->prepare("INSERT INTO subcategory_images (subcategory_id, image_path) VALUES (?,?)");
            $stmt->bind_param('is', $sid, $p);
            $stmt->execute();
        }
    }

    flash('success', $id ? 'Subcategory updated' : 'Subcategory added');
    redirect('index.php');
}

$cats = $conn->query("SELECT c.id, c.name, p.name pname FROM categories c JOIN projects p ON p.id=c.project_id ORDER BY p.name, c.name");
include __DIR__ . '/../includes/header.php';
?>
<h2 class="mb-3"><?= $pageTitle ?></h2>
<div class="card"><div class="card-body">
<form method="post" enctype="multipart/form-data">
  <div class="mb-3">
    <label class="form-label">Category *</label>
    <select name="category_id" class="form-select" required>
      <option value="">-- Select Category --</option>
      <?php while ($c = $cats->fetch_assoc()): ?>
      <option value="<?= $c['id'] ?>" <?= $row['category_id']==$c['id']?'selected':'' ?>><?= e($c['pname']) ?> &raquo; <?= e($c['name']) ?></option>
      <?php endwhile; ?>
    </select>
  </div>
  <div class="mb-3">
    <label class="form-label">Name *</label>
    <input type="text" name="name" class="form-control" value="<?= e($row['name']) ?>" required>
  </div>
  <div class="mb-3">
    <label class="form-label">Description</label>
    <textarea name="description" class="form-control" rows="4"><?= e($row['description']) ?></textarea>
  </div>
  <?php if ($images): ?>
  <div class="mb-3">
    <label class="form-label">Existing Images</label>
    <div class="d-flex flex-wrap gap-2">
      <?php foreach ($images as $img): ?>
      <div class="text-center">
        <img src="<?= UPLOAD_URL ?>/<?= e($img['image_path']) ?>" class="img-preview"><br>
        <input type="checkbox" name="delete_images[]" value="<?= $img['id'] ?>"> <small class="text-danger">Delete</small>
      </div>
      <?php endforeach; ?>
    </div>
  </div>
  <?php endif; ?>
  <div class="mb-3">
    <label class="form-label">Add Images</label>
    <input type="file" name="images[]" class="form-control" multiple accept="image/*">
  </div>
  <button class="btn btn-primary"><i class="bi bi-save"></i> Save</button>
  <a href="index.php" class="btn btn-secondary">Cancel</a>
</form>
</div></div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
