<?php
include __DIR__ . '/db.php';

$input = file_get_contents("php://input");
$update = json_decode($input, true);
$telgram_data = json_encode($input, true);
if (isset($update['message'])) {
    $chatId = $update['message']['chat']['id'];
    $text = $update['message']['text'];
    $updateId = $update['update_id'];
    $firstName = $update['message']['chat']['first_name'] ?? '';
    $lastName = $update['message']['chat']['last_name'] ?? '';
    $username = $update['message']['chat']['username'] ?? '';

    if (strtolower($text) === "/start") {
        // Check if the user already exists
        $stmt = $conn->prepare("SELECT update_id FROM telegram_users WHERE chat_id = ?");
        $stmt->bind_param("s", $chatId);
        $stmt->execute();
        $stmt->bind_result($stored_update_id);
        $userExists = $stmt->fetch();
        $stmt->close();

        if ($userExists) {
            // If the user exists, check if the update_id has changed
            if ($updateId > $stored_update_id) {
                // Update the update_id if it's a new update
                $stmt = $conn->prepare("UPDATE telegram_users SET update_id = ? WHERE chat_id = ?");
                $stmt->bind_param("ss", $updateId, $chatId);
                $stmt->execute();
                $stmt->close();
            }
        } else {
            // If the user doesn't exist, insert a new record
            $stmt = $conn->prepare("INSERT INTO telegram_users (first_name, last_name, chat_id,username,telegram_hut, update_id) VALUES (?, ?, ?, ? ,?,?)");
            $stmt->bind_param("ssssss", $firstName, $lastName, $chatId , $username,$telgram_data, $updateId);
            $stmt->execute();
            $stmt->close();
        }

        // // Send the welcome message
        // $message = "Welcome to our loan service! Please choose an option:";
        // $keyboard = [
        //     'inline_keyboard' => [
        //         [['text' => '📚 Borrow a Loan', 'callback_data' => 'borrow']],
        //         [['text' => '💸 Repay the Loan', 'callback_data' => 'repay']],
        //         [['text' => '📑 View History (Remaining)', 'callback_data' => 'history']]
        //     ]
        // ];
        // sendMessage($chatId, $message, $keyboard);
    }
}

// function sendMessage($chatId, $message, $keyboard) {
    
//     $botToken = "7927313221:AAE-n7PHKv6iBC_pLXzoRZK9r8GiiSj8Mm0";
//     $url = "https://api.telegram.org/bot$botToken/sendMessage";

//     $data = [
//         'chat_id' => $chatId,
//         'text' => $message,
//         'reply_markup' => json_encode($keyboard)
//     ];

//     $ch = curl_init();
//     curl_setopt($ch, CURLOPT_URL, $url);
//     curl_setopt($ch, CURLOPT_POST, 1);
//     curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
//     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//     curl_exec($ch);
//     curl_close($ch);
// }

header("Content-Type: application/json");
echo json_encode(["status" => "ok"]);