<?php
// =============================================
//   إعدادات بوت تيليغرام
// =============================================

define('TELEGRAM_BOT_TOKEN', '8776553400:AAFUpkrqNPcJZLoZx32mDAm_x3VfjhAF_YY');

// أضف Chat ID لكل أدمين في هذا المصفوفة
define('TELEGRAM_ADMIN_IDS', [
    2140014900,   // Coner Mgr
    // 987654321, // أدمين 2 (أضف المزيد هنا)
]);

// =============================================
//   دالة إرسال الإشعار
// =============================================
function sendTelegramNotification($message) {
    $token    = TELEGRAM_BOT_TOKEN;
    $adminIds = TELEGRAM_ADMIN_IDS;

    $botApiHost = 'api.telegram.org';
    $path = "/bot{$token}/sendMessage";

    foreach ($adminIds as $chatId) {
        $params = http_build_query([
            'chat_id'    => $chatId,
            'text'       => $message,
            'parse_mode' => 'HTML',
        ]);

        $request  = "POST {$path} HTTP/1.1\r\n";
        $request .= "Host: {$botApiHost}\r\n";
        $request .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $request .= "Content-Length: " . strlen($params) . "\r\n";
        $request .= "Connection: close\r\n\r\n";
        $request .= $params;

        // SSL عبر fsockopen
        $sock = @fsockopen("ssl://{$botApiHost}", 443, $errno, $errstr, 10);
        if ($sock) {
            fwrite($sock, $request);
            fclose($sock);
        }
    }
}
// =============================================
//   دالة بناء رسالة الطلب
// =============================================
function buildOrderMessage($order, $items, $totalPrice, $deliveryPrice) {
    $statusEmoji = ['1' => '⏳', '2' => '🚚', '3' => '✅', '4' => '❌'];
    $emoji = $statusEmoji[$order['status_id']] ?? '📦';

    $msg  = "🛒 <b>طلب جديد وصل!</b>\n";
    $msg .= "━━━━━━━━━━━━━━━━\n";
    $msg .= "🔢 <b>رقم الطلب:</b> #" . $order['id'] . "\n";
    $msg .= "👤 <b>العميل:</b> " . htmlspecialchars($order['customer_name']) . "\n";
    $msg .= "📞 <b>الهاتف:</b> " . htmlspecialchars($order['phone']) . "\n";

    if (!empty($order['phone2'])) {
        $msg .= "📞 <b>هاتف 2:</b> " . htmlspecialchars($order['phone2']) . "\n";
    }

    $msg .= "📍 <b>الولاية:</b> " . htmlspecialchars($order['wilaya_name'] ?? '--') . "\n";

    if (!empty($order['municipality'])) {
        $msg .= "🏘️ <b>البلدية:</b> " . htmlspecialchars($order['municipality']) . "\n";
    }

    if (!empty($order['address'])) {
        $msg .= "🏠 <b>العنوان:</b> " . htmlspecialchars($order['address']) . "\n";
    }

    $msg .= "🚛 <b>التوصيل:</b> " . ($order['delivery_type'] == 'home' ? 'للمنزل' : 'للمكتب') . "\n";
    $msg .= "━━━━━━━━━━━━━━━━\n";
    $msg .= "🛍️ <b>المنتجات:</b>\n";

    foreach ($items as $item) {
        $msg .= "  • " . htmlspecialchars($item['product_name'] ?? 'منتج') . " × " . $item['quantity'] . " = " . number_format($item['quantity'] * $item['unit_price'], 2) . " دج\n";
    }

    $msg .= "━━━━━━━━━━━━━━━━\n";
    $msg .= "💰 <b>المنتجات:</b> " . number_format($totalPrice, 2) . " دج\n";
    $msg .= "🚚 <b>التوصيل:</b> " . ($deliveryPrice == 0 ? 'مجاني 🎁' : number_format($deliveryPrice, 2) . " دج") . "\n";
    $msg .= "💵 <b>الإجمالي:</b> " . number_format($totalPrice + $deliveryPrice, 2) . " دج\n";
    $msg .= "━━━━━━━━━━━━━━━━\n";
    $msg .= "🕐 " . date('Y-m-d H:i', strtotime($order['order_date'])) . "\n";

    return $msg;
}