<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

date_default_timezone_set("Asia/Tashkent");

$config = include 'config.php';
$botToken = $config['bot_token'];
$apiUrl = "https://api.telegram.org/bot" . $botToken;

$mysqli = new mysqli($config['db_host'], $config['db_user'], $config['db_password'], $config['db_name']);
if ($mysqli->connect_error) {
    die("MySQL ulanishida xato: " . $mysqli->connect_error);
}

function sendMessage($chatId, $message) {
    global $apiUrl;

    $data = array(
        'chat_id' => $chatId,
        'text' => $message
    );

    $options = array(
        'http' => array(
            'header'  => "Content-Type: application/json\r\n",
            'method'  => 'POST',
            'content' => json_encode($data)
        )
    );

    $context = stream_context_create($options);
    file_get_contents($apiUrl . "/sendMessage", false, $context);
}

$content = file_get_contents("php://input");
if ($content === false) {
    error_log("Kirish ma'lumotini olishda xato.");
    die("Kirish ma'lumotini olishda xato.");
}

$update = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
    error_log("JSONni o'qishda xato: " . json_last_error_msg());
    die("Yaroqsiz JSON ma'lumot.");
}

if (isset($update['message'])) {
    $message = $update['message'];
    $chatId = $message['chat']['id'];
    $text = isset($message['text']) ? $message['text'] : '';
    $userId = $message['from']['id'];
    $firstName = isset($message['from']['first_name']) ? $message['from']['first_name'] : 'Noma';

    if ($text == "/elon") {
        $query = "SELECT first_name, title, content, created_at FROM elon ORDER BY created_at DESC LIMIT 1";
        $result = $mysqli->query($query);
        
        if ($result && $result->num_rows > 0) {
            $row = $result->fetch_assoc();
            $elon = "📢 *Oxirgi e'lon:*\n";
            $elon .= "📌 *" . $row['title'] . "*\n";
            $elon .= "👤 " . $row['first_name'] . "\n";
            $elon .= "📝 " . $row['content'] . "\n";
            $elon .= "🕒 " . $row['created_at'] . "\n";
            sendMessage($chatId, $elon);
        } else {
            sendMessage($chatId, "📭 Hozircha e'lonlar mavjud emas.");
        }
    } elseif ($text == "/elonlar") {
        $query = "SELECT first_name, title, content, created_at FROM elon ORDER BY created_at DESC";
        $result = $mysqli->query($query);
        
        if ($result && $result->num_rows > 0) {
            $elonlar = "📢 *Barcha e'lonlar:*\n";
            while ($row = $result->fetch_assoc()) {
                $elonlar .= "\n📌 *" . $row['title'] . "*\n";
                $elonlar .= "👤 " . $row['first_name'] . "\n";
                $elonlar .= "📝 " . $row['content'] . "\n";
                $elonlar .= "🕒 " . $row['created_at'] . "\n";
            }
            sendMessage($chatId, $elonlar);
        } else {
            sendMessage($chatId, "📭 Hozircha e'lonlar mavjud emas.");
        }
    } elseif (strpos($text, "/add_elon") === 0) {
        $elon_data = trim(str_replace("/add_elon", "", $text));
        $parts = explode("|", $elon_data);
        
        if (count($parts) < 2) {
            sendMessage($chatId, "❌ Iltimos, e'lonni quyidagi formatda yuboring:\n`/add_elon Nomi | Mazmuni`");
            return;
        }

        $title = trim($parts[0]);
        $content = trim($parts[1]);

        $stmt = $mysqli->prepare("INSERT INTO elon (user_id, first_name, title, content) VALUES (?, ?, ?, ?)");
        if (!$stmt) {
            error_log("❌ MySQL INSERT xatosi: " . $mysqli->error);
            sendMessage($chatId, "❌ E'lon qo'shishda xato yuz berdi.");
            return;
        }

        $stmt->bind_param("isss", $userId, $firstName, $title, $content);
        if ($stmt->execute()) {
            sendMessage($chatId, "✅ E'loningiz muvaffaqiyatli qo'shildi!\n📌 *Nomi:* $title\n📝 *Mazmuni:* $content");
        } else {
            sendMessage($chatId, "❌ E'lon qo'shishda xato yuz berdi.");
        }
        $stmt->close();
    }
}

$mysqli->close();
?>
