<?php

// Set your bot token
$botToken = '1206454586:AAHP37-65ffVZdTJr6zGZj11MBtz3WcytbM';

// Check if message and chatId are provided
if (!isset($_POST['message']) || !isset($_POST['chatId'])) {
    echo "Error: Message or chatId parameter is missing.";
    exit();
}

// Get the message and chat ID from the POST data
$message = $_POST['message'];
$chatId = $_POST['chatId'];

// Check if message or chatId is empty
if (empty($message) || empty($chatId)) {
    echo "Error: Message or chatId parameter is empty.";
    exit();
}

// Prepare the message data
$data = array(
    'chat_id' => $chatId,
    'text' => $message
);

// Initialize cURL
$ch = curl_init('https://api.telegram.org/bot' . $botToken . '/sendMessage');

// Set cURL options
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

// Execute the cURL request
$response = curl_exec($ch);

// Check for cURL errors
if (curl_errno($ch)) {
    $error = curl_error($ch);
    // Handle cURL error
    echo "Error: " . $error;
} else {
    // Check the response from Telegram API
    $responseData = json_decode($response, true);
    if (isset($responseData['ok']) && $responseData['ok'] == false) {
        // Handle Telegram API error
        echo "Telegram API Error: " . $responseData['description'];
    } else {
        // Message sent successfully
        echo "Message sent successfully!";
        recordChat($chatId, $message, 2);
    }
}

// Close cURL session
curl_close($ch);

//update db

function recordChat($chatID, $text, $type){
    $conn = mysqli_connect("localhost", "dzvisual_admin", "Farhan@123456", "dzvisual_homestay");
	mysqli_query($conn,"INSERT INTO chats (tg_chat_id, content, receive_send) VALUES ('$chatID', '$text', $type)");
}