<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/utils.php';

try {
  if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']); exit;
  }

  $id = trim($_POST['id'] ?? '');
  if ($id === '') { echo json_encode(['error' => 'Parameter id wajib']); exit; }

  $db = read_db();
  $idx = -1;
  foreach ($db as $k => $row) {
    if (!empty($row['id']) && $row['id'] === $id) { $idx = $k; break; }
  }
  if ($idx === -1) { echo json_encode(['error' => 'Data tidak ditemukan']); exit; }

  $file = __DIR__ . '/uploads/' . $db[$idx]['filename'];
  if (is_file($file)) { @unlink($file); }

  array_splice($db, $idx, 1);
  if (!write_db($db)) {
    echo json_encode(['error' => 'Gagal menyimpan perubahan']); exit;
  }

  echo json_encode(['ok' => true, 'message' => 'Berhasil dihapus']);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['error' => 'Kesalahan internal', 'detail' => $e->getMessage()]);
}