<?php
// admin/roulette_asset_delete.php
declare(strict_types=1);

// Detect if request is AJAX/JSON
function _wants_json(): bool {
    $h = $_SERVER['HTTP_ACCEPT'] ?? '';
    $xhr = strtolower($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '');
    return (stripos($h, 'application/json') !== false) || ($xhr === 'xmlhttprequest');
}

try {
    require __DIR__ . '/../db/config.php'; // must define $pdo (PDO)

    // Accept POST (preferred) or GET as fallback
    $src = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;

    $assetId    = isset($src['asset_id'])    ? (int)$src['asset_id']    : 0;
    $rouletteId = isset($src['roulette_id']) ? (int)$src['roulette_id'] : 0;
    $assetKey   = isset($src['asset_key'])   ? trim((string)$src['asset_key']) : '';

    if ($assetId <= 0 && ($rouletteId <= 0 || $assetKey === '')) {
        if (_wants_json()) {
            http_response_code(400);
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode(['ok'=>false,'error'=>'Parâmetros insuficientes']);
            exit;
        } else {
            http_response_code(400);
            echo "<meta charset=\"utf-8\"><p>Parâmetros insuficientes.</p>";
            exit;
        }
    }

    // Load asset row
    if ($assetId > 0) {
        $st = $pdo->prepare("SELECT id, roulette_id, asset_key, file_path FROM roulette_assets WHERE id = ?");
        $st->execute([$assetId]);
    } else {
        $st = $pdo->prepare("SELECT id, roulette_id, asset_key, file_path FROM roulette_assets WHERE roulette_id = ? AND asset_key = ? ORDER BY id DESC LIMIT 1");
        $st->execute([$rouletteId, $assetKey]);
    }
    $row = $st->fetch(PDO::FETCH_ASSOC);
    if (!$row) {
        if (_wants_json()) {
            header('Content-Type: application/json; charset=utf-8');
            echo json_encode(['ok'=>true,'deleted'=>false,'note'=>'Registro não existe']);
            exit;
        } else {
            $ref = $_SERVER['HTTP_REFERER'] ?? ('/admin/nova_roleta.php?id=' . $rouletteId);
            header('Location: ' . $ref, true, 302);
            exit;
        }
    }

    $rid      = (int)$row['roulette_id'];
    $filePath = (string)($row['file_path'] ?? '');

    // Resolve absolute path to /public
    $rel = ltrim($filePath, '/');
    $rel = preg_replace('#^public/#i', '', $rel);
    if (stripos($rel, 'uploads/') !== 0 && $rid > 0) {
        $rel = 'uploads/roulette_' . $rid . '/' . basename($rel);
    }
    $absPublic = realpath(__DIR__ . '/../public');
    $abs = $absPublic
        ? $absPublic . DIRECTORY_SEPARATOR . str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $rel)
        : __DIR__ . '/../public/' . $rel;

    $fileDeleted = null;
    if (is_file($abs)) {
        $fileDeleted = @unlink($abs);
    } else {
        $fileDeleted = false;
    }

    // Delete DB row
    $st = $pdo->prepare("DELETE FROM roulette_assets WHERE id = ?");
    $st->execute([(int)$row['id']]);

    // Respond
    $payload = [
        'ok'          => true,
        'deleted'     => true,
        'file_deleted'=> $fileDeleted,
        'abs_path'    => $abs,
        'rel_path'    => $rel,
        'row_id'      => (int)$row['id'],
        'asset_key'   => (string)$row['asset_key'],
        'roulette_id' => $rid,
    ];

    if (_wants_json()) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($payload);
    } else {
        // If user opened directly (no AJAX), redirect back to the admin page
        $ref = $_SERVER['HTTP_REFERER'] ?? ('/admin/nova_roleta.php?id=' . $rid);
        header('Location: ' . $ref, true, 302);
    }
} catch (Throwable $e) {
    if (_wants_json()) {
        http_response_code(500);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['ok'=>false,'error'=>$e->getMessage()]);
    } else {
        http_response_code(500);
        echo "<meta charset=\"utf-8\"><pre>Erro: " . htmlspecialchars($e->getMessage(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . "</pre>";
    }
}
