<?php
require_once 'db_config.php';
require_once 'whatsapp_config.php';

// 1. Verify Webhook (GET request)
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (isset($_GET['hub_mode']) && $_GET['hub_mode'] === 'subscribe') {
        if ($_GET['hub_verify_token'] === $wa_verify_token) {
            echo $_GET['hub_challenge'];
            exit;
        } else {
            http_response_code(403);
            exit;
        }
    }
}

// 2. Handle incoming messages (POST request)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    // Validate signature (Optional but recommended)
    $headers = getallheaders();
    if (isset($headers['X-Hub-Signature-256'])) {
        $expected_signature = 'sha256=' . hash_hmac('sha256', $input, $wa_app_secret);
        if (!hash_equals($expected_signature, $headers['X-Hub-Signature-256'])) {
            http_response_code(403);
            exit;
        }
    }

    // Auto-create whatsapp_conversations table if not exists
    $db->exec("CREATE TABLE IF NOT EXISTS whatsapp_conversations (
        phone VARCHAR(20) PRIMARY KEY,
        current_step VARCHAR(50) DEFAULT 'idle',
        selected_item_id INT DEFAULT NULL,
        selected_item_name VARCHAR(255) DEFAULT '',
        selected_qty DECIMAL(10,2) DEFAULT NULL,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    )");
    
    // Ensure whatsapp_orders exists with standard ERP structure
    $db->exec("CREATE TABLE IF NOT EXISTS whatsapp_orders (id INT AUTO_INCREMENT PRIMARY KEY, data LONGTEXT NOT NULL)");

    // Process Message
    if (isset($data['entry'][0]['changes'][0]['value']['messages'][0])) {
        $message = $data['entry'][0]['changes'][0]['value']['messages'][0];
        $contact = $data['entry'][0]['changes'][0]['value']['contacts'][0];
        
        $phone = $message['from'];
        $customer_name = $contact['profile']['name'] ?? 'غير معروف';
        $message_id = $message['id'];
        
        $message_text = '';
        if ($message['type'] === 'text') {
            $message_text = $message['text']['body'];
        } elseif ($message['type'] === 'interactive') {
            if ($message['interactive']['type'] === 'list_reply') {
                $message_text = $message['interactive']['list_reply']['id']; // We will pass item ID as the list_reply ID
            }
        }
        
        if (empty($message_text)) {
            http_response_code(200);
            exit; // Ignore non-text/interactive messages for now
        }
        
        // Check if employee
        $is_employee = false;
        $emp_stmt = $db->query("SELECT data FROM employees");
        while ($emp_row = $emp_stmt->fetch(PDO::FETCH_ASSOC)) {
            $emp_data = json_decode($emp_row['data'], true);
            if (isset($emp_data['phone']) && str_replace('+', '', $emp_data['phone']) === $phone) {
                $is_employee = true;
                $customer_name = $emp_data['name'] ?? $customer_name;
                break;
            }
        }

        // Get or Create Conversation State
        $conv_stmt = $db->prepare("SELECT * FROM whatsapp_conversations WHERE phone = ?");
        $conv_stmt->execute([$phone]);
        $conversation = $conv_stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$conversation) {
            $db->prepare("INSERT INTO whatsapp_conversations (phone, current_step) VALUES (?, 'idle')")->execute([$phone]);
            $conversation = ['phone' => $phone, 'current_step' => 'idle'];
        }

        $step = $conversation['current_step'];
        
        // Helper function to send message
        function sendMessage($to, $text) {
            global $wa_api_url, $wa_token;
            $payload = [
                "messaging_product" => "whatsapp",
                "to" => $to,
                "type" => "text",
                "text" => ["body" => $text]
            ];
            $ch = curl_init($wa_api_url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $wa_token, 'Content-Type: application/json']);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_exec($ch);
            curl_close($ch);
        }
        
        // Helper to send interactive list
        function sendInteractiveList($to, $text, $items) {
            global $wa_api_url, $wa_token;
            
            $rows = [];
            foreach ($items as $item) {
                if (count($rows) < 10) { // Max 10 items per section
                    $rows[] = [
                        "id" => "ITEM_" . $item['id'],
                        "title" => substr($item['name'], 0, 24),
                        "description" => "اختر هذا الصنف"
                    ];
                }
            }
            
            $payload = [
                "messaging_product" => "whatsapp",
                "to" => $to,
                "type" => "interactive",
                "interactive" => [
                    "type" => "list",
                    "header" => ["type" => "text", "text" => "الأصناف المتاحة"],
                    "body" => ["text" => $text],
                    "footer" => ["text" => "نظام EasyERP"],
                    "action" => [
                        "button" => "عرض الأصناف",
                        "sections" => [
                            [
                                "title" => "بنود الأصناف",
                                "rows" => $rows
                            ]
                        ]
                    ]
                ]
            ];
            
            $ch = curl_init($wa_api_url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $wa_token, 'Content-Type: application/json']);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_exec($ch);
            curl_close($ch);
        }

        if ($message_text === 'إلغاء' || $message_text === 'cancel') {
            $db->prepare("UPDATE whatsapp_conversations SET current_step = 'idle' WHERE phone = ?")->execute([$phone]);
            sendMessage($phone, "تم إلغاء الطلب. يمكنك البدء من جديد بإرسال أي رسالة.");
            http_response_code(200);
            exit;
        }

        if ($step === 'idle') {
            if ($is_employee) {
                // Just log it as a general inquiry from employee for now, or allow them to order too?
                // Let's assume employees can also order if they want, but we show a welcome message.
                // Or maybe just show the menu directly.
            }
            
            // Send Interactive List of Items
            $items_stmt = $db->query("SELECT data FROM items");
            $items = [];
            while ($item_row = $items_stmt->fetch(PDO::FETCH_ASSOC)) {
                $item_data = json_decode($item_row['data'], true);
                if (isset($item_data['id']) && isset($item_data['name'])) {
                    $items[] = $item_data;
                }
            }
            
            sendInteractiveList($phone, "مرحباً بك $customer_name! \nمن فضلك اختر نوع الخرسانة المطلوب (أو اكتب 'إلغاء'):", $items);
            $db->prepare("UPDATE whatsapp_conversations SET current_step = 'awaiting_item' WHERE phone = ?")->execute([$phone]);
            
        } elseif ($step === 'awaiting_item') {
            if (strpos($message_text, 'ITEM_') === 0) {
                $item_id = str_replace('ITEM_', '', $message_text);
                
                // Find item name
                $item_name = 'غير معروف';
                $items_stmt = $db->query("SELECT data FROM items");
                while ($item_row = $items_stmt->fetch(PDO::FETCH_ASSOC)) {
                    $item_data = json_decode($item_row['data'], true);
                    if ($item_data['id'] == $item_id) {
                        $item_name = $item_data['name'];
                        break;
                    }
                }
                
                $db->prepare("UPDATE whatsapp_conversations SET current_step = 'awaiting_qty', selected_item_id = ?, selected_item_name = ? WHERE phone = ?")
                   ->execute([$item_id, $item_name, $phone]);
                   
                sendMessage($phone, "✅ اخترت: $item_name\n\nكم متر مكعب تحتاج؟ (اكتب الرقم فقط)");
            } else {
                sendMessage($phone, "يرجى اختيار الصنف من القائمة المرفقة أو كتابة 'إلغاء'.");
            }
            
        } elseif ($step === 'awaiting_qty') {
            if (is_numeric(trim($message_text))) {
                $qty = trim($message_text);
                $db->prepare("UPDATE whatsapp_conversations SET current_step = 'awaiting_location', selected_qty = ? WHERE phone = ?")
                   ->execute([$qty, $phone]);
                   
                sendMessage($phone, "📍 أين موقع التوصيل؟\n(اكتب العنوان بالتفصيل)");
            } else {
                sendMessage($phone, "يرجى كتابة رقم صحيح للكمية.");
            }
            
        } elseif ($step === 'awaiting_location') {
            $location = trim($message_text);
            
            // We have all details, save to orders
            $order_data = [
                "wa_message_id" => $message_id,
                "customer_phone" => $phone,
                "customer_name" => $customer_name,
                "sender_type" => $is_employee ? 'employee' : 'customer',
                "message_text" => "طلب جديد عبر الواتساب",
                "item_id" => $conversation['selected_item_id'],
                "item_name" => $conversation['selected_item_name'],
                "quantity" => $conversation['selected_qty'],
                "delivery_location" => $location,
                "status" => "pending",
                "created_at" => date('Y-m-d H:i:s'),
                "_last_updated" => time()
            ];
            
            $jsonStr = json_encode($order_data, JSON_UNESCAPED_UNICODE);
            $db->prepare("INSERT INTO whatsapp_orders (data) VALUES (?)")->execute([$jsonStr]);
            $newId = $db->lastInsertId();
            
            // Add ID to data and update
            $order_data['id'] = $newId;
            $db->prepare("UPDATE whatsapp_orders SET data = ? WHERE id = ?")->execute([json_encode($order_data, JSON_UNESCAPED_UNICODE), $newId]);
            
            $db->prepare("UPDATE whatsapp_conversations SET current_step = 'idle' WHERE phone = ?")->execute([$phone]);
            
            $summary = "✅ تم تسجيل طلبك بنجاح!\n\n";
            $summary .= "📋 ملخص الطلب:\n━━━━━━━━━━━━━━━\n";
            $summary .= "🔢 رقم الطلب: #WA-$newId\n";
            $summary .= "🏗️ الصنف: {$conversation['selected_item_name']}\n";
            $summary .= "📦 الكمية: {$conversation['selected_qty']} م³\n";
            $summary .= "📍 الموقع: $location\n━━━━━━━━━━━━━━━\n\n";
            $summary .= "سيتم التواصل معك قريباً لتأكيد الموعد.";
            
            sendMessage($phone, $summary);
        }
    }
    
    http_response_code(200);
}
?>
