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

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

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

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

    if ($id) {
        $stmt = $conn->prepare("UPDATE projects SET name=?, description=? WHERE id=?");
        $stmt->bind_param('ssi', $name, $desc, $id);
        $stmt->execute();
        $pid = $id;
    } else {
        $stmt = $conn->prepare("INSERT INTO projects (name, description) VALUES (?,?)");
        $stmt->bind_param('ss', $name, $desc);
        $stmt->execute();
        $pid = $stmt->insert_id;
    }

    // delete selected images
    if (!empty($_POST['delete_images'])) {
        foreach ($_POST['delete_images'] as $img_id) {
            $img_id = (int)$img_id;
            $r = $conn->query("SELECT image_path FROM project_images WHERE id=$img_id AND project_id=$pid")->fetch_assoc();
            if ($r) { delete_image_file($r['image_path']); $conn->query("DELETE FROM project_images WHERE id=$img_id"); }
        }
    }

    // upload new
    if (!empty($_FILES['images']['name'][0])) {
        $paths = upload_images($_FILES['images'], 'projects');
        foreach ($paths as $p) {
            $stmt = $conn->prepare("INSERT INTO project_images (project_id, image_path) VALUES (?,?)");
            $stmt->bind_param('is', $pid, $p);
            $stmt->execute();
        }
    }

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

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">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 (check to delete)</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 (multiple)</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'; ?>
