<?php
session_start();
header('Content-Type: application/json');

// 1. Database Connection


//xxx
$hostName="intelliHometech.com";
$hostName="localhost";
$dbLogin="intel145_drumhill";
$dbPasswd="Rick-Beach-732-319-6727-1P";
$dbName="intel145_apps";
$dbTable="players";
$yourfield = "fidComment";

  #$pdo = new PDO("mysql:host=localhost;dbname=your_db", $dbLogin, $dbPassw);
  $pdo = new PDO($dsn, "$dbLogin", "$dbPasswd", $options);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  #$stmt = $pdo->query("SELECT name, position, office, age FROM employees");
?>

/*
$host="weFixYourTech.com";
$user="wefixy5_drumhill";
$pass="drumhill1";
$db="wefixy5_test";
$dbTable="users";
$yourfield = "Name";

#$db   = 'local_game_network';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$db;charset=utf8mb4", $user, $pass, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]);
} catch (PDOException $e) {
    echo json_encode(["error" => "Database connection failed"]);
    exit;
}
**/

// Automatically create a session token for this machine/browser if it doesn't exist
if (!isset($_SESSION['player_token'])) {
    $_SESSION['player_token'] = bin2hex(random_bytes(32));
}
$myToken = $_SESSION['player_token'];

// Get Request Data
$action = $_GET['action'] ?? '';
$roomCode = $_GET['room'] ?? 'ROOM1'; // Hardcoded room for simple local setup
$input = json_decode(file_get_contents('php://input'), true);

// Fetch Game & Current Player Info
$stmt = $pdo->prepare("SELECT * FROM games WHERE room_code = ?");
$stmt->execute([$roomCode]);
$game = $stmt->fetch();

// If room doesn't exist, auto-initialize it for testing convenience
if (!$game) {
    $pdo->prepare("INSERT INTO games (room_code, game_data) VALUES (?, ?)")
        ->execute([$roomCode, json_encode(["pile" => [], "logs" => ["Game initialized."]])]);
    
    $stmt->execute([$roomCode]);
    $game = $stmt->fetch();
}

switch ($action) {
    case 'join':
        // Count existing players to assign turn index
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM players WHERE game_id = ?");
        $stmt->execute([$game['id']]);
        $playerCount = $stmt->fetchColumn();

        if ($playerCount >= 4) { // Max 4 players
            echo json_encode(["error" => "Room Full"]);
            exit;
        }

        // Check if this browser already joined
        $stmt = $pdo->prepare("SELECT * FROM players WHERE game_id = ? AND session_token = ?");
        $stmt->execute([$game['id'], $myToken]);
        $existing = $stmt->fetch();

        if (!$existing) {
            $name = "Player " . ($playerCount + 1);
            // Give them some private data (e.g., a hidden starting hand of items or cards)
            $privateData = json_encode(["secret_hand" => ["Card A", "Card B"]]);
            
            $stmt = $pdo->prepare("INSERT INTO players (game_id, player_name, player_index, session_token, private_data) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$game['id'], $name, $playerCount, $myToken, $privateData]);
        }
        echo json_encode(["status" => "joined"]);
        break;

    case 'get_state':
        // Fetch all players in this game
        $stmt = $pdo->prepare("SELECT id, player_name, player_index, session_token FROM players WHERE game_id = ? ORDER BY player_index ASC");
        $stmt->execute([$game['id']]);
        $players = $stmt->fetchAll();

        // Identify who is calling this API
        $me = null;
        foreach ($players as &$p) {
            if ($p['session_token'] === $myToken) {
                $me = $p;
            }
            unset($p['session_token']); // Remove sensitive tokens before sending to frontend
        }

        // Get private data only for the requesting player
        $myPrivateData = null;
        if ($me) {
            $stmt = $pdo->prepare("SELECT private_data FROM players WHERE id = ?");
            $stmt->execute([$me['id']]);
            $myPrivateData = json_decode($stmt->fetchColumn(), true);
        }

        echo json_encode([
            "game_status" => $game['status'],
            "turn_index" => (int)$game['turn_index'],
            "game_data" => json_decode($game['game_data'], true),
            "players" => $players,
            "my_info" => $me,
            "my_private_data" => $myPrivateData
        ]);
        break;

    case 'start_game':
        $pdo->prepare("UPDATE games SET status = 'active', turn_index = 0 WHERE id = ?")->execute([$game['id']]);
        echo json_encode(["status" => "started"]);
        break;

    case 'make_move':
        // Verify identity and look up their index
        $stmt = $pdo->prepare("SELECT player_index FROM players WHERE game_id = ? AND session_token = ?");
        $stmt->execute([$game['id'], $myToken]);
        $playerIndex = $stmt->fetchColumn();

        if ($playerIndex === false || $game['status'] !== 'active') {
            echo json_encode(["error" => "Unauthorized or game not active."]);
            exit;
        }

        // CRITICAL TURN BLOCKING VALIDATION
        if ((int)$playerIndex !== (int)$game['turn_index']) {
            echo json_encode(["error" => "Strict Block: It is not your turn!"]);
            exit;
        }

        // Process Move (Example: Player logs an action text string)
        $gameData = json_decode($game['game_data'], true);
        $moveText = filter_var($input['move_text'], FILTER_SANITIZE_SPECIAL_CHARS);
        $gameData['logs'][] = "Player " . ($playerIndex + 1) . " performed action: " . $moveText;

        // Calculate Next Player Turn: Formula: (current_turn + 1) % total_players
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM players WHERE game_id = ?");
        $stmt->execute([$game['id']]);
        $totalPlayers = $stmt->fetchColumn();
        
        $nextTurn = ((int)$game['turn_index'] + 1) % $totalPlayers;

        // Update DB securely
        $stmt = $pdo->prepare("UPDATE games SET turn_index = ?, game_data = ? WHERE id = ?");
        $stmt->execute([$nextTurn, json_encode($gameData), $game['id']]);

        echo json_encode(["status" => "success"]);
        break;

    case 'save_game':
        // Pause current game state loop in place
        $pdo->prepare("UPDATE games SET status = 'saved' WHERE id = ?")->execute([$game['id']]);
        echo json_encode(["status" => "saved"]);
        break;

    case 'restart':
        // Wipe players, reset room defaults
        $pdo->prepare("DELETE FROM players WHERE game_id = ?")->execute([$game['id']]);
        $defaultData = json_encode(["pile" => [], "logs" => ["Game reset by admin."]]);
        $pdo->prepare("UPDATE games SET status = 'lobby', turn_index = 0, game_data = ? WHERE id = ?")
            ->execute([$defaultData, $game['id']]);
        echo json_encode(["status" => "reset"]);
        break;
}

