<?php
/**
 * POST /api/delete-order.php
 * Șterge o comandă și liniile ei (ON DELETE CASCADE).
 */
require_once __DIR__ . '/../includes/orders.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['ok' => false, 'error' => 'Doar POST'], 405);
}
if (!csrf_check($_POST['csrf_token'] ?? null)) {
    json_response(['ok' => false, 'error' => 'CSRF invalid'], 403);
}

$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) {
    json_response(['ok' => false, 'error' => 'ID invalid'], 422);
}

try {
    db_exec("DELETE FROM order_items WHERE order_id = ?", [$id]);
    db_exec("DELETE FROM orders WHERE id = ?", [$id]);
    json_response(['ok' => true, 'id' => $id]);
} catch (Throwable $ex) {
    error_log('[delete-order] ' . $ex->getMessage());
    json_response(['ok' => false, 'error' => $ex->getMessage()], 500);
}
