<?php

include __DIR__ . '/db.php'; // Include your database connection

$curl = curl_init();

// Fetch the last update ID to use as offset for the next request
$last_update_id = 0; // Initialize with zero or last known update ID if stored

// Get the last known update_id from the database (optional)
$stmt = $conn->prepare("SELECT update_id FROM telegram_users ORDER BY update_id DESC LIMIT 1");
$stmt->execute();
$stmt->bind_result($last_update_id);
$stmt->fetch();
$stmt->close();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.telegram.org/bot7927313221:AAE-n7PHKv6iBC_pLXzoRZK9r8GiiSj8Mm0/getUpdates?offset=$last_update_id",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => '',
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => 'GET',
));

$response = curl_exec($curl);
$response_data = json_decode($response, true);
curl_close($curl);

// Check if response has data
if (isset($response_data['result']) && count($response_data['result']) > 0) {
    // Process each update individually
    foreach ($response_data['result'] as $update) {
        $firstName = isset($update['message']['from']['first_name']) ? $update['message']['from']['first_name'] : 'N/A';
        $lastName = isset($update['message']['from']['last_name']) ? $update['message']['from']['last_name'] : 'N/A';
        $chatId = isset($update['message']['chat']['id']) ? $update['message']['chat']['id'] : 'N/A';
        $messageText = isset($update['message']['text']) ? $update['message']['text'] : '';
        $updateId = isset($update['update_id']) ? $update['update_id'] : '';

        // Check if the message is a /start command
        if (strtolower($messageText) == "/start") {
            // Check if this user already exists in the database
            $stmt = $conn->prepare("SELECT COUNT(*), update_id, status FROM telegram_users WHERE chat_id = ?");
            $stmt->bind_param("s", $chatId);
            $stmt->execute();
            $stmt->bind_result($count, $stored_update_id, $status);
            $stmt->fetch();
            $stmt->close();

            if ($count > 0) {
                // If the user exists, check if the update_id is new
                if ($updateId > $stored_update_id) {
                    // Send the welcome message with options
                    $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'],
                            ]
                        ]
                    ];

                    // Call sendMessage function to send the message
                    sendMessage($chatId, $message, $keyboard);

                    // After sending the message, update the status to 1 (message sent) and update the update_id
                    $stmt = $conn->prepare("UPDATE telegram_users SET update_id = ?, status = 1 WHERE chat_id = ?");
                    $stmt->bind_param("ss", $updateId, $chatId);
                    
                    if ($stmt->execute()) {
                        echo "Message sent and status updated for Chat ID: $chatId\n";
                    } else {
                        echo "Error updating status: " . $stmt->error . "\n";
                    }
                    $stmt->close();
                } else {
                    // If the update_id is the same or smaller, don't resend the message
                    echo "No new message to send for Chat ID: $chatId\n";
                }
            } else {
                // If the user doesn't exist, insert a new record with update_id, status as 0, and store chat_id
                $stmt = $conn->prepare("INSERT INTO telegram_users (first_name, last_name, chat_id, update_id, status) VALUES (?, ?, ?, ?, ?)");
                $status = 0; // Set status to 0 for new users
                $stmt->bind_param("sssss", $firstName, $lastName, $chatId, $updateId, $status);
        
                if ($stmt->execute()) {
                    // Send the welcome message with options
                    $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'],
                            ]
                        ]
                    ];

                    // Send the message to the user
                    sendMessage($chatId, $message, $keyboard);

                    echo "New user added and message sent to Chat ID: $chatId\n";
                } else {
                    echo "Error inserting data: " . $stmt->error . "\n";
                }
                $stmt->close();
            }
        }
        // Update the offset with the latest processed message ID for the next request
        $last_update_id = $updateId + 1; // Move the offset to the next update
    }
} else {
    echo "No new messages found.\n";
}

// Close database connection
$conn->close();

// Function to send message
function sendMessage($chatId, $message, $keyboard = null) {
    $botToken = "7927313221:AAE-n7PHKv6iBC_pLXzoRZK9r8GiiSj8Mm0"; // Replace with your bot's token
    $url = "https://api.telegram.org/bot$botToken/sendMessage";

    // Prepare the data
    $data = [
        'chat_id' => $chatId,
        'text' => $message
    ];

    // If a keyboard is passed, add it to the message
    if ($keyboard) {
        $data['reply_markup'] = json_encode($keyboard);
    }

    // Use cURL to send the request
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // URL encode the data
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);

    // Log the response for debugging
    if ($response === false) {
        $error = curl_error($ch);
        echo "Error: $error";
        curl_close($ch);
        return false;
    }

    curl_close($ch);
    
    // Log the response to see what Telegram returns
    $response_data = json_decode($response, true);
    if (isset($response_data['ok']) && $response_data['ok'] === true) {
        echo "Message sent successfully!\n";
    } else {
        echo "Failed to send message. Response: " . print_r($response_data, true) . "\n";
    }

    return true;
}