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

if (empty($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true
    || empty($_SESSION['role'])   || $_SESSION['role'] !== 'admin') {
    http_response_code(403);
    exit('Brak dostepu');
}

$pdo = og_session_get_pdo();


$log  = [];
$done = false;

if (isset($_POST['run'])) {
    $steps = [
        'DROP FK fk_match_team1' => "ALTER TABLE `matches` DROP FOREIGN KEY `fk_match_team1`",
        'DROP FK fk_match_team2' => "ALTER TABLE `matches` DROP FOREIGN KEY `fk_match_team2`",
        'DEFAULT Platform'       => "ALTER TABLE `matches` MODIFY COLUMN `Platform`  VARCHAR(50) NOT NULL DEFAULT 'PC'",
        'DEFAULT MatchType'      => "ALTER TABLE `matches` MODIFY COLUMN `MatchType` VARCHAR(50) NOT NULL DEFAULT 'przyjacielski'",
        'ADD EndTime'            => "ALTER TABLE `matches` ADD COLUMN `EndTime` DATETIME NULL AFTER `StartTime`",
        'ADD Score'              => "ALTER TABLE `matches` ADD COLUMN `Score`   VARCHAR(50) NULL AFTER `Status`",
        'ADD WinnerId'           => "ALTER TABLE `matches` ADD COLUMN `WinnerId` BIGINT UNSIGNED NULL AFTER `Score`",
        'ADD LoserId'            => "ALTER TABLE `matches` ADD COLUMN `LoserId`  BIGINT UNSIGNED NULL AFTER `WinnerId`",
    ];

    foreach ($steps as $label => $sql) {
        try {
            $pdo->exec($sql);
            $log[] = ['ok', $label, 'OK'];
        } catch (PDOException $e) {
            $msg = $e->getMessage();
            // Ignorujemy: "Can't DROP" (nie istnieje) i "Duplicate column name"
            if (strpos($msg, "Can't DROP") !== false
                || strpos($msg, 'Duplicate column name') !== false
                || strpos($msg, 'already exists') !== false) {
                $log[] = ['skip', $label, 'Pominieto (juz OK): ' . $msg];
            } else {
                $log[] = ['err', $label, 'BLAD: ' . $msg];
            }
        }
    }
    $done = true;
}

// Diagnostics
$diag = [];
try {
    $fks = $pdo->query(
        "SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME
         FROM information_schema.KEY_COLUMN_USAGE
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = 'matches'
           AND REFERENCED_TABLE_NAME IS NOT NULL
         ORDER BY CONSTRAINT_NAME"
    )->fetchAll(PDO::FETCH_ASSOC);
    $diag['fks'] = $fks;
} catch (Exception $e) { $diag['fks_err'] = $e->getMessage(); }

try {
    $cols = $pdo->query(
        "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT
         FROM information_schema.columns
         WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'matches'
         ORDER BY ORDINAL_POSITION"
    )->fetchAll(PDO::FETCH_ASSOC);
    $diag['cols'] = $cols;
} catch (Exception $e) { $diag['cols_err'] = $e->getMessage(); }

try {
    $mrCount = $pdo->query("SELECT COUNT(*) FROM match_results")->fetchColumn();
    $diag['match_results_count'] = (int)$mrCount;
} catch (Exception $e) { $diag['match_results_err'] = $e->getMessage(); }

try {
    $mCount = $pdo->query("SELECT COUNT(*) FROM matches")->fetchColumn();
    $diag['matches_count'] = (int)$mCount;
} catch (Exception $e) { $diag['matches_err'] = $e->getMessage(); }

function esc($s) { return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
?>
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Fix matches schema</title>
<style>
body { font-family: monospace; background:#111; color:#eee; padding:20px; }
h2 { color:#f90; }
.ok   { color:#4f4; }
.skip { color:#aaa; }
.err  { color:#f44; }
table { border-collapse:collapse; margin-bottom:20px; }
th, td { border:1px solid #444; padding:4px 10px; font-size:12px; }
th { background:#222; color:#aaa; }
.btn { background:#c00; color:#fff; border:0; padding:10px 24px; font-size:15px;
       cursor:pointer; border-radius:4px; margin:16px 0; }
.btn:hover { background:#e00; }
.info { background:#1a1a2e; border:1px solid #333; padding:12px; margin:16px 0; border-radius:4px; }
</style>
</head>
<body>
<h2>Fix matches schema — jednorazowa migracja</h2>

<?php if ($done): ?>
<h3>Wyniki:</h3>
<?php foreach ($log as [$type, $label, $msg]): ?>
<div class="<?=esc($type)?>">
    [<?=esc(strtoupper($type))?>] <?=esc($label)?> — <?=esc($msg)?>
</div>
<?php endforeach; ?>
<p class="ok">Gotowe! Mozesz sprawdzic diagnostyke ponizej.</p>
<hr>
<?php endif; ?>

<form method="POST">
<div class="info">
    <strong>Co robi ten skrypt:</strong><br>
    1. Usuwa klucze obce fk_match_team1 i fk_match_team2<br>
    2. Dodaje DEFAULT do kolumn Platform i MatchType<br>
    3. Dodaje brakujace kolumny EndTime, Score, WinnerId, LoserId
</div>
<button type="submit" name="run" value="1" class="btn"
    onclick="return confirm('Uruchomic migracje?')">
    Uruchom migracje
</button>
</form>

<h3>Diagnostyka — FK constraints w tabeli matches:</h3>
<?php if (!empty($diag['fks_err'])): ?>
<p class="err"><?=esc($diag['fks_err'])?></p>
<?php elseif (empty($diag['fks'])): ?>
<p class="ok">Brak FK constraints (juz ok).</p>
<?php else: ?>
<table>
<tr><th>CONSTRAINT_NAME</th><th>COLUMN_NAME</th><th>REFERENCED_TABLE</th></tr>
<?php foreach ($diag['fks'] as $r): ?>
<tr>
    <td><?=esc($r['CONSTRAINT_NAME'])?></td>
    <td><?=esc($r['COLUMN_NAME'])?></td>
    <td><?=esc($r['REFERENCED_TABLE_NAME'])?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

<h3>Kolumny tabeli matches:</h3>
<?php if (!empty($diag['cols_err'])): ?>
<p class="err"><?=esc($diag['cols_err'])?></p>
<?php else: ?>
<table>
<tr><th>COLUMN_NAME</th><th>TYPE</th><th>NULLABLE</th><th>DEFAULT</th></tr>
<?php foreach (($diag['cols'] ?? []) as $r): ?>
<tr>
    <td><?=esc($r['COLUMN_NAME'])?></td>
    <td><?=esc($r['COLUMN_TYPE'])?></td>
    <td><?=esc($r['IS_NULLABLE'])?></td>
    <td><?=esc($r['COLUMN_DEFAULT'] ?? 'NULL')?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>

<h3>Ilosc rekordow:</h3>
<p>
    matches: <?=esc($diag['matches_count'] ?? ($diag['matches_err'] ?? '?'))?><br>
    match_results: <?=esc($diag['match_results_count'] ?? ($diag['match_results_err'] ?? '?'))?>
</p>

<?php if (!empty($diag['match_results_count'])): ?>
<h3>Ostatnie wyniki (match_results):</h3>
<?php
try {
    $rows = $pdo->query("SELECT id, match_key, discipline, winner_username, loser_username, score, reason, ended_at FROM match_results ORDER BY id DESC LIMIT 10")->fetchAll(PDO::FETCH_ASSOC);
    echo '<table><tr><th>id</th><th>match_key</th><th>discipline</th><th>winner</th><th>loser</th><th>score</th><th>reason</th><th>ended_at</th></tr>';
    foreach ($rows as $r) {
        echo '<tr>';
        foreach ($r as $v) echo '<td>' . esc($v) . '</td>';
        echo '</tr>';
    }
    echo '</table>';
} catch (Exception $e) {
    echo '<p class="err">' . esc($e->getMessage()) . '</p>';
}
?>
<?php endif; ?>

</body>
</html>
