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

class WhatsappBot {
    public function __construct() {
        add_action('wp_ajax_nopriv_dzqcod_wa_webhook', [$this, 'handle_webhook']);
        add_action('wp_ajax_dzqcod_wa_webhook', [$this, 'handle_webhook']);
        add_action('wp_ajax_dzqcod_wa_bot_save', [$this, 'save_settings']);
    }
    public function handle_webhook(): void {
        $secret = Core::opt('wa_webhook_secret','');
        if ($secret) {
            $sig = $_SERVER['HTTP_X_HUB_SIGNATURE_256'] ?? '';
            $body = file_get_contents('php://input');
            $expected = 'sha256='.hash_hmac('sha256', $body, $secret);
            if (!hash_equals($expected, $sig)) { http_response_code(401); exit; }
        }
        $payload = json_decode(file_get_contents('php://input'), true);
        if (!$payload) { http_response_code(200); exit; }
        $messages = $payload['entry'][0]['changes'][0]['value']['messages'] ?? [];
        foreach ($messages as $msg) {
            if (($msg['type'] ?? '') !== 'text') continue;
            $this->reply($msg['from'], trim($msg['text']['body'] ?? ''));
        }
        http_response_code(200); exit;
    }
    private function reply(string $phone, string $text): void {
        if ($text === '1' || mb_strpos($text,'حالة') !== false || mb_strpos($text,'طلب') !== false) {
            $local = '0' . substr($phone, 3);
            $orders = wc_get_orders(['billing_phone'=>$local,'limit'=>3,'orderby'=>'date','order'=>'DESC']);
            if (empty($orders)) { self::send($phone, Core::opt('wa_bot_no_order','لم نجد أي طلب مرتبط برقمك.')); return; }
            $msg = "طلباتك الأخيرة:\n";
            foreach ($orders as $o) {
                $st = Core::ST[str_replace('wc-','',$o->get_status())] ?? null;
                $label = $st ? $st['i'].' '.$st['l'] : $o->get_status();
                $msg .= "• #{$o->get_id()} — {$label}\n";
            }
            self::send($phone, $msg);
        } elseif ($text === '2' || mb_strpos($text,'دعم') !== false) {
            self::send($phone, Core::opt('wa_bot_agent_msg','سيتواصل معك أحد عملائنا قريباً.'));
            if (class_exists('\\DZQCOD\\TelegramBot')) TelegramBot::send("📞 طلب وكيل WA: +{$phone}");
        } else {
            self::send($phone, Core::opt('wa_bot_welcome',"مرحباً! أرسل:\n1️⃣ حالة طلبك\n2️⃣ التحدث مع وكيل"));
        }
    }
    public static function send(string $to, string $msg): void {
        $token = Core::opt('wa_meta_token',''); $pid = Core::opt('wa_meta_phone_id','');
        if (!$token || !$pid) return;
        wp_remote_post("https://graph.facebook.com/v18.0/{$pid}/messages", [
            'headers' => ['Authorization'=>'Bearer '.$token,'Content-Type'=>'application/json'],
            'body' => wp_json_encode(['messaging_product'=>'whatsapp','to'=>$to,'type'=>'text','text'=>['body'=>$msg]]),
            'timeout' => 8, 'blocking' => false,
            'sslverify' => apply_filters('dzqcod_ssl_verify', true),
        ]);
    }
    public function save_settings(): void {
        check_ajax_referer('dzqcod_admin','nonce');
        if(!current_user_can('manage_options'))wp_send_json_error();
        foreach(['wa_bot_welcome','wa_bot_no_order','wa_bot_agent_msg','wa_webhook_secret'] as $k)
            update_option('dzqcod_'.$k, sanitize_textarea_field($_POST[$k]??''), false);
        wp_send_json_success();
    }
}
