<?php
$page_title = 'Manage Gallery';
require_once 'header.php';

$success = '';
$error = '';

// Delete
if (isset($_GET['delete']) && $pdo) {
    $id = (int)$_GET['delete'];
    $stmt = $pdo->prepare("SELECT image FROM gallery WHERE id=?");
    $stmt->execute([$id]);
    $item = $stmt->fetch();
    if ($item) {
        $imgPath = __DIR__ . '/../' . $item['image'];
        if ($item['image'] && file_exists($imgPath)) unlink($imgPath);
        $pdo->prepare("DELETE FROM gallery WHERE id=?")->execute([$id]);
        $success = 'Image removed from gallery.';
    }
}

// Add
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save'])) {
    $title = sanitize($_POST['title'] ?? '');
    $alt_text = sanitize($_POST['alt_text'] ?? '');
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $existingId = (int)($_POST['id'] ?? 0);

    if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
        $allowed = ['jpg','jpeg','png','gif','webp'];
        $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        if (in_array($ext, $allowed) && $_FILES['image']['size'] <= UPLOAD_MAX_SIZE) {
            $filename = uniqid('gal_') . '.' . $ext;
            $dest = __DIR__ . '/../uploads/gallery/' . $filename;
            if (move_uploaded_file($_FILES['image']['tmp_name'], $dest)) {
                $imagePath = 'uploads/gallery/' . $filename;

                if ($existingId) {
                    $stmt = $pdo->prepare("SELECT image FROM gallery WHERE id=?");
                    $stmt->execute([$existingId]);
                    $old = $stmt->fetch();
                    if ($old && $old['image']) {
                        $oldPath = __DIR__ . '/../' . $old['image'];
                        if (file_exists($oldPath)) unlink($oldPath);
                    }
                    $pdo->prepare("UPDATE gallery SET title=?, image=?, alt_text=?, sort_order=? WHERE id=?")->execute([$title, $imagePath, $alt_text, $sort_order, $existingId]);
                } else {
                    $pdo->prepare("INSERT INTO gallery (title, image, alt_text, sort_order) VALUES (?, ?, ?, ?)")->execute([$title, $imagePath, $alt_text, $sort_order]);
                }
                $success = $existingId ? 'Image updated.' : 'Image added to gallery.';
            } else {
                $error = 'Failed to upload image.';
            }
        } else {
            $error = 'Invalid file. Max 2MB, allowed: jpg, png, gif, webp.';
        }
    } else {
        $error = 'Please select an image.';
    }
}

$images = [];
if ($pdo) {
    $images = $pdo->query("SELECT * FROM gallery ORDER BY sort_order ASC, created_at DESC")->fetchAll();
}

$editItem = null;
if (isset($_GET['edit']) && $pdo) {
    $stmt = $pdo->prepare("SELECT * FROM gallery WHERE id=?");
    $stmt->execute([(int)$_GET['edit']]);
    $editItem = $stmt->fetch();
}
?>

<h1>Manage Gallery</h1>
<p class="subtitle">Upload and manage gallery images</p>

<?php if ($success): ?><div class="alert alert-success"><?php echo $success; ?></div><?php endif; ?>
<?php if ($error): ?><div class="alert alert-danger"><?php echo $error; ?></div><?php endif; ?>

<div class="card-admin mb-4">
  <h5 class="fw-bold mb-3"><?php echo $editItem ? 'Edit Image' : 'Add New Image'; ?></h5>
  <form method="post" enctype="multipart/form-data">
    <input type="hidden" name="id" value="<?php echo $editItem['id'] ?? 0; ?>">
    <div class="row g-3">
      <div class="col-md-6">
        <label class="form-label fw-semibold">Title</label>
        <input type="text" name="title" class="form-control" value="<?php echo $editItem ? htmlspecialchars($editItem['title']) : ''; ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label fw-semibold">Sort Order</label>
        <input type="number" name="sort_order" class="form-control" value="<?php echo $editItem ? (int)$editItem['sort_order'] : 0; ?>">
      </div>
      <div class="col-md-3">
        <label class="form-label fw-semibold">Image</label>
        <input type="file" name="image" class="form-control" accept="image/*" <?php echo $editItem ? '' : 'required'; ?>>
        <?php if ($editItem && $editItem['image']): ?>
        <img src="../<?php echo htmlspecialchars($editItem['image']); ?>" style="height:60px;border-radius:8px;margin-top:8px;">
        <?php endif; ?>
      </div>
      <div class="col-md-12">
        <label class="form-label fw-semibold">Alt Text</label>
        <input type="text" name="alt_text" class="form-control" value="<?php echo $editItem ? htmlspecialchars($editItem['alt_text']) : ''; ?>">
      </div>
      <div class="col-12">
        <button type="submit" name="save" class="btn btn-primary"><?php echo $editItem ? 'Update' : 'Upload'; ?></button>
        <?php if ($editItem): ?><a href="gallery.php" class="btn btn-outline-secondary">Cancel</a><?php endif; ?>
      </div>
    </div>
  </form>
</div>

<div class="card-admin">
  <div class="table-responsive">
    <table class="table table-admin mb-0">
      <thead>
        <tr>
          <th>Preview</th>
          <th>Title</th>
          <th>Alt Text</th>
          <th>Sort</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($images as $img): ?>
        <tr>
          <td><img src="../<?php echo htmlspecialchars($img['image']); ?>" style="height:50px;width:70px;object-fit:cover;border-radius:6px;"></td>
          <td><?php echo htmlspecialchars($img['title']); ?></td>
          <td><?php echo htmlspecialchars($img['alt_text']); ?></td>
          <td><?php echo (int)$img['sort_order']; ?></td>
          <td>
            <a href="?edit=<?php echo $img['id']; ?>" class="btn btn-sm btn-outline-primary btn-admin">Edit</a>
            <a href="?delete=<?php echo $img['id']; ?>" class="btn btn-sm btn-outline-danger btn-admin" onclick="return confirm('Delete this image?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

  </main>
</div>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
