<?php

namespace App\Services;

use App\Models\Order;
use App\Models\Setting;

class WhatsAppService
{
    protected string $whatsappNumber;
    protected string $sendMethod; // 'direct' (wa.me) or 'api'
    protected ?string $apiToken;
    protected ?string $apiUrl;

    public function __construct()
    {
        $this->whatsappNumber = Setting::where('key', 'whatsapp_number')->value('value') ?? '962799999999';
        $this->sendMethod = Setting::where('key', 'whatsapp_send_method')->value('value') ?? 'direct';
        $this->apiToken = Setting::where('key', 'whatsapp_api_token')->value('value');
        $this->apiUrl = Setting::where('key', 'whatsapp_api_url')->value('value');
    }

    /**
     * Generate WhatsApp message for a new order
     */
    public function generateOrderMessage(Order $order): string
    {
        $order->load(['customer', 'items.product', 'items.productWeight.weightUnit', 'deliveryZone', 'paymentMethod']);
        
        $message = "🍯 *طلب جديد - روابي نحلة*\n";
        $message .= "━━━━━━━━━━━━━━━━━━━━━━\n\n";
        $message .= "📋 *رقم الطلب:* #{$order->order_number}\n";
        $message .= "📅 *التاريخ:* " . $order->created_at->format('Y-m-d H:i') . "\n\n";
        
        // Customer info
        $message .= "👤 *معلومات الزبون:*\n";
        $message .= "• الاسم: {$order->customer->name}\n";
        $message .= "• الهاتف: {$order->customer->phone}\n\n";
        
        // Order items
        $message .= "🛒 *المنتجات:*\n";
        $message .= "─────────────────────\n";
        foreach ($order->items as $item) {
            $message .= "• {$item->product_name}";
            if ($item->weight_label) {
                $message .= " ({$item->weight_label})";
            }
            $message .= "\n  الكمية: {$item->quantity} × " . number_format($item->unit_price, 3) . " د.ا";
            $message .= " = " . number_format($item->total_price, 3) . " د.ا\n";
            if ($item->notes) {
                $message .= "  📝 ملاحظة: {$item->notes}\n";
            }
        }
        $message .= "─────────────────────\n\n";
        
        // Totals
        $message .= "💰 *التفاصيل المالية:*\n";
        $message .= "• المجموع الفرعي: " . number_format($order->subtotal, 3) . " د.ا\n";
        if ($order->discount_amount > 0) {
            $message .= "• الخصم: -" . number_format($order->discount_amount, 3) . " د.ا";
            if ($order->coupon_code) {
                $message .= " (كوبون: {$order->coupon_code})";
            }
            $message .= "\n";
        }
        if ($order->delivery_fee > 0) {
            $message .= "• رسوم التوصيل: " . number_format($order->delivery_fee, 3) . " د.ا\n";
        }
        $message .= "• *الإجمالي: " . number_format($order->total, 3) . " د.ا*\n\n";
        
        // Delivery info
        $message .= "🚚 *التوصيل:*\n";
        if ($order->delivery_type === 'delivery') {
            $message .= "• النوع: توصيل\n";
            if ($order->deliveryZone) {
                $message .= "• المنطقة: {$order->deliveryZone->name_ar}\n";
            }
            if ($order->delivery_address) {
                $message .= "• العنوان: {$order->delivery_address}\n";
            }
            if ($order->delivery_city) {
                $message .= "• المدينة: {$order->delivery_city}\n";
            }
        } else {
            $message .= "• النوع: استلام من المتجر\n";
        }
        
        // Payment
        $message .= "\n💳 *الدفع:*\n";
        if ($order->paymentMethod) {
            $message .= "• الطريقة: {$order->paymentMethod->name_ar}\n";
        }
        $message .= "• الحالة: " . ($order->payment_status === 'paid' ? '✅ مدفوع' : '⏳ في انتظار الدفع') . "\n";
        
        // Notes
        if ($order->notes) {
            $message .= "\n📝 *ملاحظات الزبون:*\n{$order->notes}\n";
        }
        
        $message .= "\n━━━━━━━━━━━━━━━━━━━━━━\n";
        $message .= "🔗 *رابط التتبع:*\n";
        $message .= config('app.frontend_url', 'https://rnahlah.com') . "/track?order={$order->order_number}\n";
        
        return $message;
    }

    /**
     * Generate WhatsApp URL (wa.me link) for direct method
     */
    public function generateWhatsAppUrl(Order $order): string
    {
        $message = $this->generateOrderMessage($order);
        $encodedMessage = urlencode($message);
        return "https://wa.me/{$this->whatsappNumber}?text={$encodedMessage}";
    }

    /**
     * Generate tracking notification message for customer
     */
    public function generateTrackingMessage(Order $order, string $status): string
    {
        $statusLabels = [
            'pending' => '📋 تم استلام الطلب',
            'processing' => '🔄 جاري تجهيز الطلب',
            'out_for_delivery' => '🚚 الطلب في الطريق إليك',
            'delivered' => '✅ تم التسليم بنجاح',
            'cancelled' => '❌ تم إلغاء الطلب',
        ];

        $message = "🍯 *روابي نحلة - تحديث الطلب*\n\n";
        $message .= "رقم الطلب: #{$order->order_number}\n";
        $message .= "الحالة: {$statusLabels[$status]}\n\n";
        $message .= "لتتبع طلبك:\n";
        $message .= config('app.frontend_url', 'https://rnahlah.com') . "/track?order={$order->order_number}\n";

        return $message;
    }

    /**
     * Send message via WhatsApp Business API (when configured)
     */
    public function sendViaApi(string $phone, string $message): bool
    {
        if (!$this->apiToken || !$this->apiUrl) {
            return false;
        }

        try {
            $client = new \GuzzleHttp\Client();
            $response = $client->post($this->apiUrl, [
                'headers' => [
                    'Authorization' => "Bearer {$this->apiToken}",
                    'Content-Type' => 'application/json',
                ],
                'json' => [
                    'messaging_product' => 'whatsapp',
                    'to' => $phone,
                    'type' => 'text',
                    'text' => ['body' => $message],
                ],
            ]);

            return $response->getStatusCode() === 200;
        } catch (\Exception $e) {
            \Log::error('WhatsApp API Error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Send order notification
     */
    public function notifyOrderCreated(Order $order): array
    {
        $message = $this->generateOrderMessage($order);
        $whatsappUrl = $this->generateWhatsAppUrl($order);

        $result = [
            'whatsapp_url' => $whatsappUrl,
            'message' => $message,
            'api_sent' => false,
        ];

        // Try to send via API if configured
        if ($this->sendMethod === 'api') {
            $result['api_sent'] = $this->sendViaApi($this->whatsappNumber, $message);
        }

        return $result;
    }

    /**
     * Send status update to customer
     */
    public function notifyStatusUpdate(Order $order): array
    {
        $message = $this->generateTrackingMessage($order, $order->status);
        $customerPhone = $order->customer->phone;

        $result = [
            'message' => $message,
            'api_sent' => false,
        ];

        if ($this->sendMethod === 'api' && $customerPhone) {
            $result['api_sent'] = $this->sendViaApi($customerPhone, $message);
        }

        return $result;
    }
}
