<?php
ob_start();
require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';

header('Content-Type: application/json; charset=utf-8');

if (empty($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true
    || empty($_SESSION['role'])   || $_SESSION['role'] !== 'admin') {
    ob_clean();
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$pdo = og_session_get_pdo();
if (!$pdo) {
    ob_clean();
    echo json_encode(['success' => false, 'error' => 'DB unavailable']);
    exit;
}

$type = $_POST['type'] ?? '';
$id   = (int)($_POST['id'] ?? 0);

if ($id <= 0) {
    ob_clean();
    echo json_encode(['success' => false, 'error' => 'Invalid id']);
    exit;
}

try {
    if ($type === 'result') {
        // Usuwa wiersz z match_results
        $stmt = $pdo->prepare('DELETE FROM match_results WHERE id = ?');
        $stmt->execute([$id]);
        $deleted = $stmt->rowCount();
    } elseif ($type === 'match') {
        // Usuwa tylko zakonczone mecze (Status = 'end') — nigdy aktywnych
        $stmt = $pdo->prepare("DELETE FROM matches WHERE ID = ? AND Status = 'end'");
        $stmt->execute([$id]);
        $deleted = $stmt->rowCount();
        if ($deleted === 0) {
            ob_clean();
            echo json_encode(['success' => false, 'error' => 'Mecz nie istnieje lub nie jest zakonczony']);
            exit;
        }
    } else {
        ob_clean();
        echo json_encode(['success' => false, 'error' => 'Unknown type']);
        exit;
    }

    ob_clean();
    echo json_encode(['success' => true, 'deleted' => $deleted]);
} catch (Exception $e) {
    ob_clean();
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
