<?php
// =============================
// Telegram Bot Configuration
// =============================
define('BOT_TOKEN', '7266394475:AAEXZvhKhZkfw0jwAmU1mgf5Jt8YjuToVoY');
define('API_URL', 'https://api.telegram.org/bot' . BOT_TOKEN . '/');


// =============================
// Helper: Send Request
// =============================
function tgRequest($method, $data = [])
{
    $ch = curl_init(API_URL . $method);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => ['Content-Type: application/json']
    ]);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

// =============================
// Catalog (Same as Python)
// =============================
$catalog = [
    "Gemetric toric" => [
        "T3" => [
            "19" => ["available" => true],
            "19.5" => ["available" => true],
            "20" => ["available" => true],
            "20.5" => ["available" => true],
            "21" => ["available" => true],
            "21.5" => ["available" => true],
            "22" => ["available" => false],
            "22.5" => ["available" => false],
            "23" => ["available" => true],
            "23.5" => ["available" => true],
            "24" => ["available" => false],
            "24.5" => ["available" => false],
        ],
        "T4" => [
            "19" => ["available" => false],
            "19.5" => ["available" => true],
            "20" => ["available" => true],
            "20.5" => ["available" => true],
            "21" => ["available" => true],
            "21.5" => ["available" => true],
            "22" => ["available" => true],
            "22.5" => ["available" => true],
            "23" => ["available" => true],
            "23.5" => ["available" => true],
            "24" => ["available" => true],
            "24.5" => ["available" => true],
        ]
    ],
    "TORIC" => [
        "T3" => [
            "18" => ["available" => true],
            "18.5" => ["available" => true],
            "19" => ["available" => true],
            "19.5" => ["available" => true],
            "20" => ["available" => false],
            "20.5" => ["available" => true],
        ]
    ]
];

// =============================
// Build Nodes (Tree)
// =============================
$nodes = [];
$nextId = 1;

function traverse($title, $subtree, $parentId)
{
    global $nodes, $nextId;

    $id = $nextId++;
    $nodes[$id] = [
        'id' => $id,
        'title' => $title,
        'children' => [],
        'available' => null,
        'parent' => $parentId
    ];

    if (is_array($subtree) && isset($subtree['available']) && count($subtree) === 1) {
        $nodes[$id]['available'] = (bool)$subtree['available'];
    } else {
        foreach ($subtree as $childTitle => $childSub) {
            $childId = traverse($childTitle, $childSub, $id);
            $nodes[$id]['children'][] = $childId;
        }
    }
    return $id;
}

// Root
$nodes[0] = [
    'id' => 0,
    'title' => ' ',
    'children' => [],
    'available' => null,
    'parent' => null
];

foreach ($catalog as $title => $sub) {
    $cid = traverse($title, $sub, 0);
    $nodes[0]['children'][] = $cid;
}

// =============================
// UI Helpers
// =============================
function keyboardForNode($nodeId)
{
    global $nodes;
    $buttons = [];

    foreach ($nodes[$nodeId]['children'] as $cid) {
        $buttons[] = [[
            'text' => $nodes[$cid]['title'],
            'callback_data' => "NODE:$cid"
        ]];
    }

    $footer = [];
    if ($nodeId != 0) {
        $footer[] = [
            'text' => '🔙 بازگشت',
            'callback_data' => "BACK:$nodeId"
        ];
    }
    $footer[] = [
        'text' => '🏠 منوی اصلی',
        'callback_data' => 'HOME'
    ];

    $buttons[] = $footer;

    return ['inline_keyboard' => $buttons];
}

function breadcrumb($nodeId)
{
    global $nodes;
    $parts = [];
    while ($nodeId !== null && isset($nodes[$nodeId])) {
        $parts[] = $nodes[$nodeId]['title'];
        $nodeId = $nodes[$nodeId]['parent'];
    }
    return implode(' > ', array_reverse($parts));
}

// =============================
// Handle Update
// =============================
$update = json_decode(file_get_contents('php://input'), true);

if (isset($update['message']['text']) && $update['message']['text'] === '/start') {
    tgRequest('sendMessage', [
        'chat_id' => $update['message']['chat']['id'],
        'text' => "سلام 👋\nخوش آمدید.\nلطفاً دسته‌ی مورد نظرت رو انتخاب کن:",
        'reply_markup' => keyboardForNode(0)
    ]);
}

if (isset($update['callback_query'])) {
    $q = $update['callback_query'];
    $data = $q['data'];
    $chatId = $q['message']['chat']['id'];
    $msgId = $q['message']['message_id'];

    tgRequest('answerCallbackQuery', [
        'callback_query_id' => $q['id']
    ]);

    if (strpos($data, 'NODE:') === 0) {
        $id = intval(substr($data, 5));
        $node = $nodes[$id] ?? null;

        if (!$node) return;

        if ($node['available'] !== null) {
            $status = $node['available'] ? "✅ موجود است" : "❌ موجود نیست";
            $text = breadcrumb($id) . "\n\n{$node['title']}: $status";

            tgRequest('editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $msgId,
                'text' => $text,
                'reply_markup' => [
                    'inline_keyboard' => [
                        [[ 'text' => '🔙 بازگشت', 'callback_data' => "BACK:$id" ]],
                        [[ 'text' => '🏠 منوی اصلی', 'callback_data' => 'HOME' ]]
                    ]
                ]
            ]);
        } else {
            tgRequest('editMessageText', [
                'chat_id' => $chatId,
                'message_id' => $msgId,
                'text' => breadcrumb($id) . "\n\nلطفاً انتخاب کنید:",
                'reply_markup' => keyboardForNode($id)
            ]);
        }
    }

    elseif (strpos($data, 'BACK:') === 0) {
        $id = intval(substr($data, 5));
        $parent = $nodes[$nodes[$id]['parent']] ?? $nodes[0];

        tgRequest('editMessageText', [
            'chat_id' => $chatId,
            'message_id' => $msgId,
            'text' => breadcrumb($parent['id']) . "\n\nلطفاً انتخاب کنید:",
            'reply_markup' => keyboardForNode($parent['id'])
        ]);
    }

    elseif ($data === 'HOME') {
        tgRequest('editMessageText', [
            'chat_id' => $chatId,
            'message_id' => $msgId,
            'text' => "🏠 بازگشت به منوی اصلی:",
            'reply_markup' => keyboardForNode(0)
        ]);
    }
}
