<?php
session_start();

// เริ่มต้นเกม
if (!isset($_SESSION['board'])) {
    $_SESSION['board'] = array_fill(0, 9, '');
    $_SESSION['turn'] = 'X';
}

// ตรวจสอบการชนะ
function check_winner($board) {
    $winning_combinations = [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8],
        [0, 3, 6],
        [1, 4, 7],
        [2, 5, 8],
        [0, 4, 8],
        [2, 4, 6]
    ];

    foreach ($winning_combinations as $combo) {
        if ($board[$combo[0]] && $board[$combo[0]] == $board[$combo[1]] && $board[$combo[1]] == $board[$combo[2]]) {
            return $board[$combo[0]];
        }
    }

    return null;
}

// เมื่อผู้เล่นเลือกตำแหน่ง
if (isset($_POST['position']) && $_SESSION['board'][$_POST['position']] == '') {
    $_SESSION['board'][$_POST['position']] = $_SESSION['turn'];
    $_SESSION['turn'] = $_SESSION['turn'] == 'X' ? 'O' : 'X';
}

// ตรวจสอบผู้ชนะ
$winner = check_winner($_SESSION['board']);
?>

<!DOCTYPE html>
<html lang="th">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>เกม XO</title>
    <style>
        .board { display: grid; grid-template-columns: repeat(3, 100px); gap: 5px; }
        .cell { width: 100px; height: 100px; text-align: center; line-height: 100px; border: 1px solid black; font-size: 24px; cursor: pointer; }
        .winner { color: green; font-size: 20px; }
    </style>
</head>
<body>
    <h1>เกม XO</h1>
    <?php if ($winner): ?>
        <p class="winner">ผู้ชนะคือ: <?php echo $winner; ?></p>
        <form method="post">
            <button type="submit" name="reset" value="true">เริ่มเกมใหม่</button>
        </form>
    <?php else: ?>
        <p>ผลหมุนเวียน: <?php echo $_SESSION['turn']; ?></p>
    <?php endif; ?>

    <div class="board">
        <?php foreach ($_SESSION['board'] as $index => $value): ?>
            <form method="post" style="margin: 0;">
                <button type="submit" name="position" value="<?php echo $index; ?>" class="cell">
                    <?php echo $value; ?>
                </button>
            </form>
        <?php endforeach; ?>
    </div>

    <?php
    // รีเซ็ตเกม
    if (isset($_POST['reset'])) {
        session_unset();
        session_destroy();
        header("Location: index.php");
    }
    ?>
</body>
</html>