<?php

error_reporting(E_ALL);

ini_set('display_errors', 1);

date_default_timezone_set("Asia/Baku");

// Database configuration
$db_host = "localhost";
$db_user = "panelzon_smm2";
$db_pass = "El5208262";
$db_name = "panelzon_smm2";

// Create connection
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Define Telegram Bot token and API URL
define("BOT_TOKEN", "7007403703:AAHYAP4-hWYkFzNGr9rRVfmbSZgG184_9ug"); // Your TOKEN here
define("API_URL", "https://api.telegram.org/bot" . BOT_TOKEN . "/");

// Define admin and inbox IDs
$UID = 6182576695; // ID of admin
$inbox_id = 6182576695; // ID where all messages will be forwarded
// Get incoming message
$content = file_get_contents("php://input");
$update = json_decode($content, true);

if (!$update || !isset($update['message'])) {
    exit;
}

// Handle the incoming message
$chat_id = $update['message']['chat']['id'];
$message_text = $update['message']['text'];
$message_id = $update['message']['message_id'];
$caption = isset($update['message']['caption']) ? $update['message']['caption'] : "";
$userid = $update['message']['from']['id'];
$chat_type = $update['message']['chat']['type'];

// Store user data in the database if not admin
if ($userid != $UID && $chat_type == "private") {
    $firstname = $update['message']['from']['first_name'];
    $lastname = isset($update['message']['from']['last_name']) ? $update['message']['from']['last_name'] : "";
    $username = isset($update['message']['from']['username']) ? $update['message']['from']['username'] : "";

    // Escape variables to prevent SQL injection
    $userid_safe = $conn->real_escape_string($userid);
    $firstname_safe = $conn->real_escape_string($firstname);
    $lastname_safe = $conn->real_escape_string($lastname);
    $username_safe = $conn->real_escape_string($username);

    // Check if user exists in database
    $query = "SELECT * FROM users WHERE user_id = '$userid_safe'";
    $result = $conn->query($query);
    
    if ($result && $result->num_rows == 0) {
        // User does not exist, insert data into database
        $insert_query = "INSERT INTO users (user_id, first_name, last_name, username) 
                        VALUES ('$userid_safe', '$firstname_safe', '$lastname_safe', '$username_safe')";
        
        if ($conn->query($insert_query) !== TRUE) {
            error_log("Error: " . $insert_query . " - " . $conn->error);
        }
    }
}

// Handle /start command
if ($message_text == "/start" && $userid != $UID && $chat_type == "private") {
    sendTelegramMessage($chat_id, "Hello Sir, How Can I help You?");
} elseif ($message_text == "/start" && $userid == $UID && $chat_type == "private") {
    sendTelegramMessage($chat_id, "Hi I will forward all messages to the group or channel you give me.");
}

// Handle broadcast command
if (strpos($message_text, "/broadcast") === 0 && $userid == $UID) {
    // Remove the command part
    $message = trim(str_replace("/broadcast", "", $message_text));
    
    // Split the message into parts
    $parts = explode("|", $message);

    // Default button values
    $button_name = "Click Here";
    $button_url = "https://example.com";

    // Validate and assign values
    if (count($parts) >= 1) {
        $message = trim($parts[0]);
    }
    if (count($parts) >= 2) {
        $button_name = trim($parts[1]);
    }
    if (count($parts) >= 3) {
        $button_url = trim($parts[2]);
    }

    if (empty($message)) {
        sendTelegramMessage($chat_id, "Message cannot be empty. Usage: /broadcast Your message here | Button Name | Button URL");
    } else {
        // Fetch all user IDs from the database
        $query = "SELECT user_id FROM users";
        $result = $conn->query($query);

        if ($result->num_rows > 0) {
            $error = false;
            while ($row = $result->fetch_assoc()) {
                $user_id = $row["user_id"];

                // Send message to each user ID with button
                if (!sendTelegramMessageWithButton($user_id, $message, $button_name, $button_url)) {
                    $error = true;
                }
            }
            if ($error) {
                sendTelegramMessage($chat_id, "Failed to send message to one or more users");
            } else {
                sendTelegramMessage($chat_id, "Message broadcasted successfully");
            }
        } else {
            sendTelegramMessage($chat_id, "No users found to send message to");
        }
    }
}

// Forward messages to inbox ID
if ($userid != $UID && $chat_type == "private") {
    $data = [
        "chat_id" => $inbox_id,
        "from_chat_id" => $userid,
        "message_id" => $message_id,
    ];
    $json_data = json_encode($data, JSON_NUMERIC_CHECK);
    makeTelegramRequest("forwardMessage", $json_data);
} elseif ($userid == $UID) {
    handleAdminMessages($update);
}

function sendTelegramMessage($chat_id, $message)
{
    $data = [
        "text" => $message,
        "chat_id" => $chat_id,
    ];
    $json_data = json_encode($data);

    $response = makeTelegramRequest("sendMessage", $json_data);

    return $response !== false;
}

function sendTelegramMessageWithButton($chat_id, $message, $button_name, $button_url)
{
    $data = [
        "chat_id" => $chat_id,
        "text" => $message,
        "reply_markup" => [
            "inline_keyboard" => [
                [
                    ["text" => $button_name, "url" => $button_url]
                ]
            ]
        ]
    ];
    $json_data = json_encode($data);

    $response = makeTelegramRequest("sendMessage", $json_data);

    return $response !== false;
}

function handleAdminMessages($update)
{
    $message = $update['message'];
    $reply_to_message = isset($message['reply_to_message']) ? $message['reply_to_message'] : null;

    if ($reply_to_message && isset($reply_to_message['forward_from'])) {
        $reply_id = $reply_to_message['forward_from']['id'];

        $data = [
            "chat_id" => $reply_id,
        ];

        if (isset($message['text'])) {
            $data["text"] = $message['text'];
        } elseif (isset($message['animation'])) {
            $data["animation"] = $message['animation']['file_id'];
        } elseif (isset($message['audio'])) {
            $data["audio"] = $message['audio']['file_id'];
            $data["caption"] = $message['caption'] ?? "";
        } elseif (isset($message['contact'])) {
            $data["phone_number"] = $message['contact']['phone_number'];
            $data["first_name"] = $message['contact']['first_name'];
            $data["last_name"] = $message['contact']['last_name'] ?? "";
            $data["vcard"] = $message['contact']['vcard'];
        } elseif (isset($message['dice'])) {
            $data["emoji"] = $message['dice']['emoji'];
        } elseif (isset($message['document'])) {
            $data["document"] = $message['document']['file_id'];
            $data["caption"] = $message['caption'] ?? "";
        } elseif (isset($message['location'])) {
            $data["longitude"] = $message['location']['longitude'] ?? 0;
            $data["latitude"] = $message['location']['latitude'] ?? 0;
            $data["horizontal_accuracy"] = $message['location']['horizontal_accuracy'] ?? 0;
            $data["live_period"] = $message['location']['live_period'] ?? 0;
            $data["heading"] = $message['location']['heading'] ?? 0;
            $data["proximity_alert_radius"] = $message['location']['proximity_alert_radius'] ?? 0;
        } elseif (isset($message['photo'])) {
            $photo_id = $message['photo'][count($message['photo']) - 1]['file_id'];
            $data["photo"] = $photo_id;
            $data["caption"] = $message['caption'] ?? "";
        } elseif (isset($message['sticker'])) {
            $data["sticker"] = $message['sticker']['file_id'];
        } elseif (isset($message['video'])) {
            $data["video"] = $message['video']['file_id'];
            $data["caption"] = $message['caption'] ?? "";
        } elseif (isset($message['voice'])) {
            $data["voice"] = $message['voice']['file_id'];
            $data["caption"] = $message['caption'] ?? "";
        } elseif (isset($message['video_note'])) {
            $data["video_note"] = $message['video_note']['file_id'];
            $data["caption"] = $message['caption'] ?? "";
        } elseif (isset($message['venue'])) {
            $data["latitude"] = $message['venue']['location']['latitude'] ?? 0;
            $data["longitude"] = $message['venue']['location']['longitude'] ?? 0;
            $data["title"] = $message['venue']['title'] ?? "";
            $data["address"] = $message['venue']['address'] ?? "";
            $data["foursquare_id"] = $message['venue']['foursquare_id'] ?? "";
            $data["foursquare_type"] = $message['venue']['foursquare_type'] ?? "";
            $data["google_place_id"] = $message['venue']['google_place_id'] ?? "";
            $data["google_place_type"] = $message['venue']['google_place_type'] ?? "";
        }

        if (!empty($data)) {
            $json_data = json_encode($data, JSON_NUMERIC_CHECK);
            makeTelegramRequest("sendMessage", $json_data);
        }
    }
}

function makeTelegramRequest($method, $json_data)
{
    $url = API_URL . $method;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    $response = curl_exec($ch);

    if ($response === false) {
        error_log('Curl error: ' . curl_error($ch));
        return false;
    }

    curl_close($ch);

    return json_decode($response, true);
}
?>
