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

$host = "localhost";
$dbname = "joshuakitoka_danso";
$username = "joshuakitoka_danso";
$password = "mmicrea2025";

try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(["error" => $e->getMessage()]);
    exit();
}

/* ============================================================
   LOGIQUE PFC
============================================================ */
function combatResultat($attacker, $defender) {

    if ($attacker == $defender) return "egalite";

    if (
        ($attacker == "pierre"  && $defender == "ciseau") ||
        ($attacker == "ciseau"  && $defender == "feuille") ||
        ($attacker == "feuille" && $defender == "pierre")
    ) return "attaquant_gagne";

    return "defenseur_gagne";
}

$action = $_POST["base"] ?? "";

/* ============================================================
   GET STATE
============================================================ */
if ($action === "get") {
    $stmt = $conn->prepare("SELECT * FROM game WHERE id = 1");
    $stmt->execute();
    $g = $stmt->fetch(PDO::FETCH_ASSOC);

    // V�rifie victoire
    $winner = 0;

    if ($g["vaisseau1"] <= 0) {
        $winner = 2;
    }
    if ($g["vaisseau2"] <= 0) {
        $winner = 1;
    }

    // Ajoute winner dans le JSON
    $g["winner"] = $winner;

    echo json_encode($g);
    exit();
}


/* ============================================================
   START GAME
============================================================ */
if ($action === "start") {

    $stmt = $conn->prepare("
        UPDATE game SET
            joueur = 1,
            phase = 'attente',

            vaisseau1 = 5,
            vaisseau2 = 5,

            pierre1 = 3, feuille1 = 3, ciseau1 = 3,
            pierre2 = 3, feuille2 = 3, ciseau2 = 3,

            attaque_joueur = NULL,
            attaque_drone = NULL,
            attaque_cible = NULL,
            defense_drone = NULL,

            joker1 = 2,
            joker2 = 2,

            bluff_annonce = NULL,
            bluff_reel = NULL,
            bluff_joueur = NULL,
            phase_bluff = NULL

        WHERE id = 1
    ");
    $stmt->execute();

    echo json_encode(["status" => "started"]);
    exit();
}

/* ============================================================
   RESET GAME
============================================================ */
if ($action === "reset") {

    $stmt = $conn->prepare("
        UPDATE game SET
            joueur = 1,
            phase = 'attente',

            vaisseau1 = 5,
            vaisseau2 = 5,

            pierre1 = 3, feuille1 = 3, ciseau1 = 3,
            pierre2 = 3, feuille2 = 3, ciseau2 = 3,

            attaque_joueur = NULL,
            attaque_drone = NULL,
            attaque_cible = NULL,
            defense_drone = NULL,

            joker1 = 2,
            joker2 = 2,

            bluff_annonce = NULL,
            bluff_reel = NULL,
            bluff_joueur = NULL,
            phase_bluff = NULL
        WHERE id = 1
    ");
    $stmt->execute();

    echo json_encode(["status" => "reset_done"]);
    exit();
}

/* ============================================================
   ATTAQUE
============================================================ */
if ($action === "attack") {

    $joueur = intval($_POST["joueur"]);
    $drone  = $_POST["drone"];
    $cible  = $_POST["cible"];

    $stmt = $conn->prepare("SELECT * FROM game WHERE id = 1");
    $stmt->execute();
    $g = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($g["joueur"] != $joueur) exit(json_encode(["error" => "not_your_turn"]));
    if ($g["phase"] !== "attente") exit(json_encode(["error" => "bad_phase"]));

    $col = $drone . $joueur;
    if ($g[$col] <= 0) exit(json_encode(["error" => "drone_dead"]));

    $stmt = $conn->prepare("
        UPDATE game SET
            attaque_joueur = :j,
            attaque_drone  = :d,
            attaque_cible  = :c,
            phase = 'defense'
        WHERE id = 1
    ");

    $stmt->execute([
        ":j" => $joueur,
        ":d" => $drone,
        ":c" => $cible
    ]);

    echo json_encode(["status" => "attack_recorded"]);
    exit();
}

/* ============================================================
   DEFENSE
============================================================ */
if ($action === "defend") {

    $def_joueur = intval($_POST["joueur"]);
    $def_drone  = $_POST["drone"];

    $stmt = $conn->prepare("SELECT * FROM game WHERE id = 1");
    $stmt->execute();
    $g = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($g["phase"] !== "defense") exit(json_encode(["error" => "bad_phase"]));

    $atk_joueur = intval($g["attaque_joueur"]);
    $atk_drone  = $g["attaque_drone"];
    $atk_cible  = $g["attaque_cible"];

    if ($def_joueur == $atk_joueur) exit(json_encode(["error" => "not_defender"]));

    $colDef = $def_drone . $def_joueur;
    if ($g[$colDef] <= 0) exit(json_encode(["error" => "defender_dead"]));

    $result = combatResultat($atk_drone, $def_drone);

    if ($result !== "attaquant_gagne") {

        $stmt = $conn->prepare("
            UPDATE game SET
                attaque_joueur = NULL,
                attaque_drone  = NULL,
                attaque_cible  = NULL,
                phase = 'attente',
                joueur = :next
            WHERE id = 1
        ");

        $stmt->execute([":next" => $def_joueur]);

        echo json_encode(["resultat" => "bonne_defense"]);
        exit();
    }

    $victime = ($atk_joueur == 1) ? 2 : 1;

    $hpCol = ($atk_cible === "vaisseau")
        ? "vaisseau" . $victime
        : $atk_cible . $victime;

    $newHP = max(0, $g[$hpCol] - 1);

    $stmt = $conn->prepare("
        UPDATE game SET
            $hpCol = :hp,
            attaque_joueur = NULL,
            attaque_drone  = NULL,
            attaque_cible  = NULL,
            phase = 'attente',
            joueur = :next
        WHERE id = 1
    ");

    $stmt->execute([
        ":hp" => $newHP,
        ":next" => $def_joueur
    ]);

    echo json_encode(["resultat" => "mauvaise_defense"]);
    exit();
}

/* ============================================================
   REPARATION
============================================================ */
if ($action === "repair") {

    $joueur = intval($_POST["joueur"]);
    $drone  = $_POST["drone"];

    $stmt = $conn->prepare("SELECT * FROM game WHERE id = 1");
    $stmt->execute();
    $g = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($g["joueur"] != $joueur) exit(json_encode(["error" => "not_your_turn"]));

    $col = $drone . $joueur;
    $jokerCol = "joker" . $joueur;

    if ($g[$jokerCol] <= 0) exit(json_encode(["error" => "no_joker"]));
    if ($g[$col] >= 3) exit(json_encode(["error" => "drone_full_hp"]));

    $newHP = min(3, $g[$col] + 2);

    $stmt = $conn->prepare("
        UPDATE game SET
            $col = :hp,
            $jokerCol = :jk,
            joueur = :next
        WHERE id = 1
    ");

    $stmt->execute([
        ":hp" => $newHP,
        ":jk" => $g[$jokerCol] - 1,
        ":next" => ($joueur == 1 ? 2 : 1)
    ]);

    echo json_encode(["status" => "repaired"]);
    exit();
}

/* ============================================================
   BLUFF — JOUEUR ANNONCE (CONSOMME 1 JOKER ICI)
============================================================ */
if ($action === "bluff") {

    $j = intval($_POST["joueur"]);
    $left = $_POST["left"];
    $right = $_POST["right"];

    $stmt = $conn->prepare("SELECT * FROM game WHERE id = 1");
    $stmt->execute();
    $g = $stmt->fetch(PDO::FETCH_ASSOC);

    $jokerCol = "joker".$j;

    /* 📌 CONSOMME 1 JOKER ICI */
    $newJokers = max(0, $g[$jokerCol] - 1);

    $stmt = $conn->prepare("
        UPDATE game SET
            bluff_annonce = :a,
            bluff_reel = :r,
            bluff_joueur = :j,
            phase_bluff = 'attente_verif',
            joueur = :next,
            $jokerCol = :jk
        WHERE id = 1
    ");

    $stmt->execute([
        ":a" => $left,
        ":r" => $right,
        ":j" => $j,
        ":next" => ($j == 1 ? 2 : 1),
        ":jk" => $newJokers
    ]);

    echo json_encode(["status" => "bluff_sent"]);
    exit();
}

/* ============================================================
   BLUFF : VERIFICATION (NE CHANGE RIEN AUX JOKERS)
============================================================ */
if ($action === "verif_bluff") {

    $verif = $_POST["verif"]; 

    $stmt = $conn->prepare("SELECT * FROM game WHERE id = 1");
    $stmt->execute();
    $g = $stmt->fetch(PDO::FETCH_ASSOC);

    $annonce = $g["bluff_annonce"];
    $reel = $g["bluff_reel"];
    $bluffeur = intval($g["bluff_joueur"]);
    $adversaire = ($bluffeur == 1 ? 2 : 1);

    $pvBluffeur = "vaisseau".$bluffeur;
    $pvAdv = "vaisseau".$adversaire;

    $degatsBluffeur = 0;
    $degatsAdversaire = 0;

    $annonceVraie = ($annonce === $reel);

    if ($verif === "true") {
        if ($annonceVraie) $degatsBluffeur = 2;
        else $degatsAdversaire = 2;
    }

    if ($verif === "false") {
        if ($annonceVraie) $degatsAdversaire = 2;
        else $degatsBluffeur = 2;
    }

    $newPvBluffeur = max(0, $g[$pvBluffeur] - $degatsBluffeur);
    $newPvAdv = max(0, $g[$pvAdv] - $degatsAdversaire);

    $stmt = $conn->prepare("
        UPDATE game SET
            $pvBluffeur = :pvb,
            $pvAdv = :pva,
            bluff_annonce = NULL,
            bluff_reel = NULL,
            bluff_joueur = NULL,
            phase_bluff = NULL,
            phase = 'attente'
        WHERE id = 1
    ");

    $stmt->execute([
        ":pvb" => $newPvBluffeur,
        ":pva" => $newPvAdv
    ]);

    echo json_encode([
        "status" => "bluff_checked",
        "verif" => $verif,
        "degats_bluffeur" => $degatsBluffeur,
        "degats_adversaire" => $degatsAdversaire
    ]);

    exit();
}

/* ============================================================
   ACTION INCONNUE
============================================================ */

echo json_encode(["error" => "unknown_action"]);
exit();

?>
