<?php
// index.php — WhatsApp Cloud API bot

// ====== CONFIG ======
date_default_timezone_set('UTC');
$VERIFY_TOKEN    = getenv('VERIFY_TOKEN')    ?: 'replace-with-your-verify-token';
$WHATSAPP_TOKEN  = getenv('WHATSAPP_TOKEN')  ?: 'replace-with-a-valid-token'; // system user or temporary token
$PHONE_NUMBER_ID = getenv('PHONE_NUMBER_ID') ?: 'your_phone_number_id';       // From API Setup or your number

// Where we store minimal per-user state
$STATE_DIR = __DIR__ . '/state';
if (!is_dir($STATE_DIR)) { @mkdir($STATE_DIR, 0775, true); }

// ====== UTILITIES ======
function read_json_body(): array {
    $raw = file_get_contents('php://input');
    if ($raw === false) return [];
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function log_line(string $text): void {
    $file = __DIR__ . '/log.log';
    file_put_contents($file, $text . PHP_EOL, FILE_APPEND | LOCK_EX);
}

function send_whatsapp_text(string $to, string $body): array {
    global $WHATSAPP_TOKEN, $PHONE_NUMBER_ID;

    $url = "https://graph.facebook.com/v20.0/{$PHONE_NUMBER_ID}/messages";
    $payload = [
        "messaging_product" => "whatsapp",
        "to" => $to,
        "type" => "text",
        "text" => ["body" => $body],
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => [
            "Authorization: Bearer {$WHATSAPP_TOKEN}",
            "Content-Type: application/json",
        ],
        CURLOPT_POSTFIELDS => json_encode($payload),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
    ]);
    $resp = curl_exec($ch);
    $err  = curl_error($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $out = ["http_code"=>$code, "error"=>$err, "response"=>$resp];
    log_line("send_whatsapp_text to={$to} code={$code} err={$err}\nresp={$resp}");
    return $out;
}

function extract_message(array $body): ?array {
    if (!isset($body['entry'][0]['changes'][0]['value'])) return null;
    $value = $body['entry'][0]['changes'][0]['value'];

    if (isset($value['messages'][0])) {
        $msg = $value['messages'][0];
        $from = $msg['from'] ?? null;
        $text = null;

        if (($msg['type'] ?? '') === 'text' && isset($msg['text']['body'])) {
            $text = trim($msg['text']['body']);
        }
        return [
            "from" => $from,
            "text" => $text,
        ];
    }
    return null;
}

// Simple file-based state per user
function get_user_state(string $user): array {
    global $STATE_DIR;
    $file = $STATE_DIR . "/{$user}.json";
    if (!is_file($file)) return ["stage" => "NEW"];
    $data = json_decode(@file_get_contents($file), true);
    return is_array($data) ? $data : ["stage" => "NEW"];
}
function save_user_state(string $user, array $state): void {
    global $STATE_DIR;
    $file = $STATE_DIR . "/{$user}.json";
    @file_put_contents($file, json_encode($state, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
}

// ====== ROUTING ======
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($method === 'GET') {
    // Webhook verification
    $mode      = $_GET['hub_mode']        ?? $_GET['hub.mode']        ?? null;
    $token     = $_GET['hub_verify_token']?? $_GET['hub.verify_token']?? null;
    $challenge = $_GET['hub_challenge']   ?? $_GET['hub.challenge']   ?? null;

    if ($mode === 'subscribe' && $token !== null && hash_equals($VERIFY_TOKEN, $token)) {
        http_response_code(200);
        header('Content-Type: text/plain; charset=utf-8');
        echo $challenge;
    } else {
        http_response_code(403);
    }
    exit;
}

if ($method === 'POST') {
    $timestamp = (new DateTimeImmutable('now'))->format('Y-m-d H:i:s');
    $body = read_json_body();
    log_line("\n\nWebhook received {$timestamp}\n" . json_encode($body, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));

    $incoming = extract_message($body);
    if ($incoming && !empty($incoming['from']) && !empty($incoming['text'])) {
        $from = $incoming['from'];
        $text = strtolower(trim($incoming['text']));
        $state = get_user_state($from);

        // 1) Flow for "hi"
        if ($text === 'hi' && $state['stage'] === 'NEW') {
            send_whatsapp_text($from, "Hi! What's your name?");
            $state['stage'] = 'ASKED_NAME';
            save_user_state($from, $state);

        } elseif ($state['stage'] === 'ASKED_NAME') {
            $name = ucfirst($incoming['text']);
            $state['name'] = $name;
            $state['stage'] = 'READY';
            save_user_state($from, $state);
            send_whatsapp_text($from, "Hi {$name}!");

        // 2) Flow for World Cup question
        } elseif (
            strpos($text, 'who') !== false &&
            strpos($text, '2026') !== false &&
            strpos($text, 'world cup') !== false
        ) {
            send_whatsapp_text($from, "Of course it will be Argentina 🇦🇷");

        } elseif ($state['stage'] === 'READY') {
            $name = $state['name'] ?? 'there';
            send_whatsapp_text($from, "Hi {$name}! (say 'reset' to start over)");
        }

        // Reset option
        if ($text === 'reset') {
            $state = ["stage" => "NEW"];
            save_user_state($from, $state);
            send_whatsapp_text($from, "Reset done. Say 'hi' to start again.");
        }
    }

    http_response_code(200);
    echo 'OK';
    exit;
}

http_response_code(405);
header('Allow: GET, POST');
echo 'Method Not Allowed';

