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

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

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

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

    if ($id) {
        $stmt = $conn->prepare("UPDATE categories SET project_id=?, name=?, description=? WHERE id=?");
        $stmt->bind_param('issi', $project_id, $name, $desc, $id);
        $stmt->execute();
        $cid = $id;
    } else {
        $stmt = $conn->prepare("INSERT INTO categories (project_id, name, description) VALUES (?,?,?)");
        $stmt->bind_param('iss', $project_id, $name, $desc);
        $stmt->execute();
        $cid = $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 category_images WHERE id=$img_id AND category_id=$cid")->fetch_assoc();
            if ($r) { delete_image_file($r['image_path']); $conn->query("DELETE FROM category_images WHERE id=$img_id"); }
        }
    }

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

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

$projects = $conn->query("SELECT id, name FROM projects ORDER BY 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">Project *</label>
    <select name="project_id" class="form-select" required>
      <option value="">-- Select Project --</option>
      <?php while ($p = $projects->fetch_assoc()): ?>
      <option value="<?= $p['id'] ?>" <?= $row['project_id']==$p['id']?'selected':'' ?>><?= e($p['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'; ?>
