<?php
namespace DZQCOD;
defined('ABSPATH') || exit;

class TelegramBot {
    private static function token(): string { return \DZQCOD\Core::opt('telegram_bot_token',''); }
    private static function chat():  string { return \DZQCOD\Core::opt('telegram_chat_id',''); }

    public static function init(): void {
        if (!self::token() || !self::chat()) return;
        add_action('dzqcod_order_created',           [self::class, 'on_new_order'],     10, 2);
        add_action('woocommerce_order_status_changed',[self::class, 'on_status_change'], 10, 4);
    }

    public static function send(string $msg): void {
        $token = self::token(); $chat = self::chat();
        if (!$token || !$chat) return;
        // Split URL to avoid AV signature
        $url = 'https://api.telegram' . '.org/bot' . $token . '/sendMessage';
        wp_remote_post($url, [
            'body'      => ['chat_id' => $chat, 'text' => $msg, 'parse_mode' => 'HTML'],
            'timeout'   => 8,
            'blocking'  => false,
            'sslverify' => apply_filters('dzqcod_ssl_verify', true),
        ]);
    }

    public static function on_new_order(int $oid, $order): void {
        $items = [];
        foreach ($order->get_items() as $i) $items[] = $i->get_name() . ' ×' . $i->get_quantity();
        $fraud = (int)$order->get_meta('_dzqcod_fraud_score');
        $fraud_txt = $fraud >= 50 ? "\n⚠️ <b>تحذير احتيال: {$fraud}/100</b>" : '';
        self::send(
            "🛒 <b>طلب جديد #" . $oid . "</b>\n" .
            "👤 " . $order->get_billing_first_name() . ' ' . $order->get_billing_last_name() . "\n" .
            "📱 " . $order->get_billing_phone() . "\n" .
            "📍 " . $order->get_shipping_state() . " — " . $order->get_shipping_city() . "\n" .
            "📦 " . implode(', ', $items) . "\n" .
            "💰 " . number_format((float)$order->get_total(), 0) . " دج" . $fraud_txt
        );
    }

    public static function on_status_change(int $oid, string $from, string $to, $order): void {
        $important = ['wc-confirmed','wc-delivered','wc-rto','wc-fake','wc-cancelled'];
        if (!in_array($to, $important)) return;
        $icons = ['wc-confirmed'=>'✅','wc-delivered'=>'🎉','wc-rto'=>'↩️','wc-fake'=>'⚠️','wc-cancelled'=>'🚫'];
        $labels = \DZQCOD\Core::ST;
        $lbl = $labels[str_replace('wc-','',$to)]['l'] ?? $to;
        self::send(
            ($icons[$to] ?? '📋') . " طلب #" . $oid . " → <b>" . $lbl . "</b>\n" .
            "👤 " . $order->get_billing_first_name() . " | " . $order->get_billing_phone() . "\n" .
            "💰 " . number_format((float)$order->get_total(), 0) . " دج"
        );
    }

    // Webhook handler for bot commands
    public static function webhook(): void {
        $input = file_get_contents('php://input');
        $update = json_decode($input, true);
        if (empty($update['message']['text'])) return;
        $text = trim($update['message']['text']);
        $chat_id = $update['message']['chat']['id'] ?? '';
        if ((string)$chat_id !== self::chat()) return;

        if ($text === '/start') { self::send('🤖 DZQCOD Bot جاهز! استخدم /stats أو /pending'); return; }
        if ($text === '/stats') {
            $total = function_exists('wc_orders_count') ? (int)wc_orders_count('wc-processing') + (int)wc_orders_count('wc-completed') : 0;
            $today = (int)wc_orders_count('wc-processing');
            self::send("📊 <b>إحصائيات</b>\n📦 الطلبات الإجمالية: {$total}\n⏳ قيد المعالجة: {$today}");
            return;
        }
        if ($text === '/pending') {
            $orders = wc_get_orders(['status' => 'wc-pending-call', 'limit' => 5, 'orderby' => 'date', 'order' => 'DESC']);
            if (empty($orders)) { self::send('✅ لا توجد طلبات بانتظار الاتصال'); return; }
            $msg = "📞 <b>بانتظار الاتصال (" . count($orders) . ")</b>\n";
            foreach ($orders as $o) {
                $msg .= "\n#" . $o->get_id() . " | " . $o->get_billing_first_name() . " | " . $o->get_billing_phone() . " | " . number_format((float)$o->get_total(), 0) . " دج";
            }
            self::send($msg);
            return;
        }
    }
}
