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

function stars_cancel_json(array $data, int $code = 200): void {
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') stars_cancel_json(['ok'=>false,'error'=>'POST required'], 405);
$input = json_decode(file_get_contents('php://input'), true) ?: $_POST;
$userId = (int)($input['user_id'] ?? 0);
$orderId = (int)($input['order_id'] ?? 0);
$auto = !empty($input['auto']) || !empty($input['auto_cancel']);
if (!$userId || !$orderId) stars_cancel_json(['ok'=>false,'error'=>'user_id and order_id required'], 400);

try {
    if (function_exists('gemaccStarsAutoCancelPendingOrder')) {
        $res = gemaccStarsAutoCancelPendingOrder($pdo, $orderId, $userId, $auto, $auto);
        if (!empty($res['not_expired'])) {
            stars_cancel_json(['ok'=>false,'not_expired'=>true,'message'=>'زمان لغو خودکار هنوز نرسیده است.'], 409);
        }
        stars_cancel_json($res, !empty($res['ok']) ? 200 : 400);
    }

    // Legacy fallback: manual cancellation without auto-notification.
    $pdo->beginTransaction();
    $st = $pdo->prepare("SELECT * FROM orders WHERE id=? AND user_id=? AND UPPER(COALESCE(payment_method,''))='STARS' FOR UPDATE");
    $st->execute([$orderId, $userId]);
    $order = $st->fetch(PDO::FETCH_ASSOC);
    if (!$order) throw new RuntimeException('سفارش استارز یافت نشد.');
    if (strtolower((string)($order['payment_status'] ?? '')) === 'paid') throw new RuntimeException('این سفارش پرداخت شده و قابل لغو نیست.');

    if (!in_array((string)($order['status'] ?? ''), ['CANCELLED','REJECTED','DELIVERED'], true)) {
        try {
            $du = $pdo->prepare("SELECT discount_id FROM discount_usages WHERE order_id=?");
            $du->execute([$orderId]);
            $discountIds = array_map('intval', $du->fetchAll(PDO::FETCH_COLUMN));
            foreach ($discountIds as $did) {
                if ($did > 0) $pdo->prepare("UPDATE discount_codes SET used_count=GREATEST(used_count-1,0) WHERE id=?")->execute([$did]);
            }
            $pdo->prepare("DELETE FROM discount_usages WHERE order_id=?")->execute([$orderId]);
        } catch (Throwable $ignored) {}
        $pdo->prepare("UPDATE orders SET payment_status='cancelled', delivery_status='cancelled', status='CANCELLED', updated_at=NOW() WHERE id=?")->execute([$orderId]);
    }
    $pdo->commit();
    stars_cancel_json(['ok'=>true,'message'=>'سفارش استارز لغو شد.']);
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    stars_cancel_json(['ok'=>false,'error'=>$e->getMessage()], 400);
}
