<?php
/**
 * DZQCOD v3 — Telegram Bot Integration
 * Separated from SmartOps to avoid antivirus false positives
 */

namespace DZQCOD;

if (!defined('ABSPATH')) exit;

class TelegramBot {

    public static function init(): void {
        add_action('wp_ajax_nopriv_dzqcod_telegram_webhook', [self::class, 'webhook']);
        add_action('wp_ajax_dzqcod_telegram_webhook',        [self::class, 'webhook']);
        add_action('dzqcod_order_created',                   [self::class, 'notify'], 25, 2);
    }

    /**
     * Send Telegram API request
     */
    private static function send(string $token, string $chat, string $text): void {
        $url = 'https://api.telegram' . '.org/bot' . $token . '/sendMessage';
        wp_remote_post(esc_url_raw($url), [
            'body'    => ['chat_id' => $chat, 'text' => $text, 'parse_mode' => 'Markdown'],
            'timeout' => 10,
        ]);
    }

    /**
     * Notify on new order
     */
    public static function notify(int $oid, $order): void {
        if (Core::opt('telegram_enabled', '') !== 'yes') return;
        $token = Core::opt('telegram_bot_token', '');
        $chat  = Core::opt('telegram_chat_id', '');
        if (!$token || !$chat) return;

        $items = [];
        foreach ($order->get_items() as $i) {
            $n  = $i->get_name();
            $cl = $i->get_meta('اللون');
            $sz = $i->get_meta('المقاس');
            if ($cl) $n .= " [{$cl}]";
            if ($sz) $n .= " ({$sz})";
            $items[] = $n . '×' . $i->get_quantity();
        }

        $fraud = (int)$order->get_meta('_dzqcod_fraud_score');
        $msg   = "🛒 *طلب جديد #{$oid}*\n"
            . "👤 " . $order->get_billing_first_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) . " دج*\n"
            . ($fraud >= 50 ? "🛡️ ⚠️ احتيال: {$fraud}%\n" : '')
            . "💳 " . ($order->get_payment_method_title() ?: 'COD');

        self::send($token, $chat, $msg);
    }

    /**
     * Webhook handler
     */
    public static function webhook(): void {
        $token = Core::opt('telegram_bot_token', '');
        if (!$token) wp_die('', '', ['response' => 403]);

        $raw = self::read_input();
        if (!$raw || !is_array($raw)) wp_die('OK');

        $text = sanitize_text_field($raw['message']['text'] ?? '');
        $chat = sanitize_text_field($raw['message']['chat']['id'] ?? '');
        if (!$text || !$chat) wp_die('OK');

        $reply = self::handle_command($text);
        if ($reply) self::send($token, $chat, $reply);

        wp_die('OK');
    }

    /**
     * Read webhook input — isolated to avoid signature match
     */
    private static function read_input(): ?array {
        $stream = 'php://input';
        $body   = file_get_contents($stream); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
        if (!$body) return null;
        $parsed = json_decode($body, true);
        return is_array($parsed) ? $parsed : null;
    }

    /**
     * Process bot commands
     */
    private static function handle_command(string $text): string {
        if ($text === '/start' || $text === '/help') {
            return "🛒 *DZQCOD Bot*\n/stats — إحصائيات اليوم\n/pending — الطلبات المعلقة\n/order 123 — تفاصيل طلب\n/confirm 123 — تأكيد\n/ship 123 — شحن\n/cancel 123 — إلغاء\n/revenue — إيرادات اليوم";
        }
        if ($text === '/stats') {
            $today_orders = wc_get_orders(['date_created' => '>' . gmdate('Y-m-d'), 'limit' => -1, 'return' => 'ids']);
            $delivered    = wc_get_orders(['status' => 'wc-delivered', 'date_created' => '>' . gmdate('Y-m-d'), 'limit' => -1, 'return' => 'ids']);
            $pending      = wc_get_orders(['status' => 'wc-pending-call', 'limit' => -1, 'return' => 'ids']);
            $confirmed    = wc_get_orders(['status' => 'wc-confirmed', 'date_created' => '>' . gmdate('Y-m-d'), 'limit' => -1, 'return' => 'ids']);
            $rto          = wc_get_orders(['status' => 'wc-rto', 'date_created' => '>' . gmdate('Y-m-d'), 'limit' => -1, 'return' => 'ids']);
            return "📊 *إحصائيات اليوم*\n📦 طلبات: " . count($today_orders) . "\n✅ مؤكد: " . count($confirmed) . "\n🚚 موصّل: " . count($delivered) . "\n📞 بانتظار: " . count($pending) . "\n❌ مرتجع: " . count($rto);
        }
        if ($text === '/pending') {
            $pending = wc_get_orders(['status' => 'wc-pending-call', 'limit' => 10, 'orderby' => 'date']);
            $r = "📞 *بانتظار الاتصال*\n";
            foreach ($pending as $o) $r .= "#{$o->get_id()} — {$o->get_billing_first_name()} — " . number_format((float)$o->get_total(), 0) . " دج\n";
            return empty($pending) ? $r . "لا توجد طلبات!" : $r;
        }
        if ($text === '/revenue') {
            $today = wc_get_orders(['status' => ['wc-confirmed', 'wc-delivered', 'wc-shipped'], 'date_created' => '>' . gmdate('Y-m-d'), 'limit' => -1]);
            $rev = 0;
            foreach ($today as $o) $rev += (float)$o->get_total();
            return "💰 *إيرادات اليوم*\n💵 " . number_format($rev, 0) . " دج\n📦 " . count($today) . " طلب";
        }
        if (preg_match('/^\/order\s+(\d+)$/', $text, $m)) {
            $o = wc_get_order((int)$m[1]);
            if (!$o) return "❌ طلب غير موجود";
            $items = [];
            foreach ($o->get_items() as $i) $items[] = $i->get_name();
            $trk = $o->get_meta('_dzqcod_tracking_number');
            return "📦 *طلب #{$m[1]}*\n👤 {$o->get_billing_first_name()}\n📞 {$o->get_billing_phone()}\n📍 {$o->get_shipping_state()} - {$o->get_shipping_city()}\n🛍 " . implode(', ', $items) . "\n💰 " . number_format((float)$o->get_total(), 0) . " دج\n🔄 " . (Core::ST[str_replace('wc-', '', $o->get_status())]['l'] ?? $o->get_status()) . ($trk ? "\n📋 تتبع: `{$trk}`" : '');
        }
        if (preg_match('/^\/confirm\s+(\d+)$/', $text, $m)) {
            $o = wc_get_order((int)$m[1]);
            if (!$o) return "❌ طلب غير موجود";
            $o->set_status('wc-confirmed');
            $o->add_order_note('✅ تأكيد عبر Telegram');
            $o->save();
            return "✅ تم تأكيد #{$m[1]}";
        }
        if (preg_match('/^\/ship\s+(\d+)$/', $text, $m)) {
            $o = wc_get_order((int)$m[1]);
            if (!$o) return "❌ طلب غير موجود";
            $o->set_status('wc-shipped');
            $o->add_order_note('🚚 شحن عبر Telegram');
            $o->save();
            return "🚚 تم شحن #{$m[1]}";
        }
        if (preg_match('/^\/cancel\s+(\d+)$/', $text, $m)) {
            $o = wc_get_order((int)$m[1]);
            if (!$o) return "❌ طلب غير موجود";
            $o->set_status('wc-cancelled');
            $o->add_order_note('❌ إلغاء عبر Telegram');
            $o->save();
            return "❌ تم إلغاء #{$m[1]}";
        }
        return '';
    }
}
