<?php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../admin/auth.php';
header('Content-Type: application/json');

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

$input = json_decode(file_get_contents('php://input'), true) ?? $_POST;

if (empty($input['id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Package ID is required']);
    exit;
}

$packages = readJSON(PACKAGES_FILE);
$originalCount = count($packages);
$packages = array_values(array_filter($packages, fn($p) => $p['id'] !== $input['id']));

if (count($packages) === $originalCount) {
    http_response_code(404);
    echo json_encode(['success' => false, 'error' => 'Package not found']);
    exit;
}

writeJSON(PACKAGES_FILE, $packages);
echo json_encode(['success' => true, 'deleted_id' => $input['id'], 'remaining' => count($packages)]);
exit;
