<?php

include "../classes/db.class.php";

// $db = new db();
// to set a webhook https://api.telegram.org/bot7778679262:AAGY7qcQl_JkgPFctc0glaXm7Map_LtnlAw/setWebhook?url=muell.elegantwork.co.za/api/telegram.php
// Get the incoming JSON payload from Telegram
$update = file_get_contents('php://input');
$update = json_decode($update, true);
$token = "7778679262:AAGY7qcQl_JkgPFctc0glaXm7Map_LtnlAw";
$state = "";

// Check if a message exists in the payload
if (isset($update['message'])) {
    $chat_id = $update['message']['chat']['id']; // Extract the chat ID
    $text = $update['message']['text'];

    // Start the account linking process
    if (stripos($text, '/start') !== false) {
        $response = [
            'chat_id' => $chat_id,
            'text' => "TO Link your muell estates account please send the following command: /linkaccount u:yourusername p:yourpassword",
        ];
        file_get_contents("https://api.telegram.org/bot$token/sendMessage?" . http_build_query($response));
    }

    // Link the account

    if (stripos($text, '/linkaccount') !== false) {
        // Extract username and password from the command
        preg_match('/u:(.*?)\s?p:/', $text, $userMatches);
        preg_match('/p:(\S+)/', $text, $passMatches);

        if (!empty($userMatches) && !empty($passMatches)) {
            $username = $userMatches[1];
            $password = $passMatches[1];

            // Now you can use $username and $password for further processing
            // For example, linking the account

            $db = new db();
            $res = $db->exec_query("users", ['*'], "", '', '', '', "username = '$username' AND password = '$password'");
            if ($res->num_rows > 0) {
                $user = $res->fetch_assoc();
                $db->Update('users', ['telegram_chat_id'], [$chat_id], "record_id = {$user['record_id']}");
                $response = [
                    "chat_id" => $chat_id,
                    "text" => "Your account has been linked successfully!",
                ];
                file_get_contents("https://api.telegram.org/bot$token/sendMessage?" . http_build_query($response));

            } else {
                $response = [
                    'chat_id' => $chat_id,
                    'text' => "Invalid username or password. Please try again. U:$username P:$password",
                ];
                file_get_contents("https://api.telegram.org/bot$token/sendMessage?" . http_build_query($response));
            }
        } else {
            $response = [
                'chat_id' => $chat_id,
                'text' => "Invalid format. Please use: /linkaccount u:yourusername p:yourpassword",
            ];
            file_get_contents("https://api.telegram.org/bot$token/sendMessage?" . http_build_query($response));
        }
    }
}
?>