<?php
/**
 * API Handler الموحد لنظام الكاشير - مع ملاحظات العميل
 */

// تعطيل عرض الأخطاء
error_reporting(0);
ini_set('display_errors', 0);

// بدء تشغيل المخزن المؤقت
ob_start();

require_once 'config.php';

// تنظيف أي مخرجات سابقة
ob_clean();

// تعيين header JSON
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');

// التحقق من الجلسة
if (!isset($_SESSION[CASHIER_SESSION_KEY])) {
    echo json_encode(['success' => false, 'message' => 'غير مصرح']);
    exit;
}

$action = isset($_GET['action']) ? $_GET['action'] : '';

try {
    switch($action) {
        case 'get_orders':
            getOrders();
            break;
        case 'accept_order':
            acceptOrder();
            break;
        case 'check_updates':
            checkUpdates();
            break;
        default:
            echo json_encode(['success' => false, 'message' => 'إجراء غير معروف']);
    }
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'خطأ في السيرفر: ' . $e->getMessage()]);
}

function getOrders() {
    global $conn;
    
    try {
        $status = isset($_GET['status']) ? $_GET['status'] : 'pending';
        $order_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
        
        // إذا كان طلب محدد
        if ($order_id > 0) {
            $sql = "SELECT o.*, 
                           c.name as customer_name, 
                           c.phone as customer_phone, 
                           c.address as customer_address,
                           cp.name as captain_name,
                           cp.phone as captain_phone
                    FROM orders o
                    JOIN customers c ON o.customer_id = c.id
                    LEFT JOIN captains cp ON o.captain_id = cp.id
                    WHERE o.id = ?";
            
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("i", $order_id);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows === 0) {
                echo json_encode(['success' => false, 'message' => 'الطلب غير موجود']);
                return;
            }
            
            $order = $result->fetch_assoc();
            
            // جلب عناصر الطلب
            $items_sql = "SELECT oi.*, m.name as meal_name 
                          FROM order_items oi
                          JOIN meals m ON oi.meal_id = m.id
                          WHERE oi.order_id = ?";
            $stmt = $conn->prepare($items_sql);
            $stmt->bind_param("i", $order_id);
            $stmt->execute();
            $items_result = $stmt->get_result();
            
            $order['items'] = [];
            while ($item = $items_result->fetch_assoc()) {
                $order['items'][] = $item;
            }
            
            echo json_encode(['success' => true, 'order' => $order]);
            return;
        }
        
        // فلتر الحالة
        $status_filter = "";
        $params = [];
        $types = "";
        
        if ($status !== 'all') {
            $status_filter = "AND o.status = ?";
            $params[] = $status;
            $types .= "s";
        }
        
        // تحديد عدد الطلبات
        $limit = ($status === 'pending') ? 10 : 50;
        
        // جلب الطلبات مع ملاحظات العميل (العمود notes)
        $sql = "SELECT o.*, 
                       c.name as customer_name, 
                       c.phone as customer_phone, 
                       c.address as customer_address,
                       cp.name as captain_name,
                       cp.phone as captain_phone
                FROM orders o
                JOIN customers c ON o.customer_id = c.id
                LEFT JOIN captains cp ON o.captain_id = cp.id
                WHERE 1=1 $status_filter
                ORDER BY o.created_at ASC
                LIMIT ?";
        
        $params[] = $limit;
        $types .= "i";
        
        $stmt = $conn->prepare($sql);
        
        if (!empty($params)) {
            $stmt->bind_param($types, ...$params);
        }
        
        $stmt->execute();
        $result = $stmt->get_result();
        
        $orders = [];
        
        while ($row = $result->fetch_assoc()) {
            // جلب عناصر الطلب
            $items_sql = "SELECT oi.*, m.name as meal_name 
                          FROM order_items oi
                          JOIN meals m ON oi.meal_id = m.id
                          WHERE oi.order_id = ?";
            $stmt_items = $conn->prepare($items_sql);
            $stmt_items->bind_param("i", $row['id']);
            $stmt_items->execute();
            $items_result = $stmt_items->get_result();
            
            $row['items'] = [];
            while ($item = $items_result->fetch_assoc()) {
                $row['items'][] = $item;
            }
            
            $orders[] = $row;
        }
        
        // إحصائيات اليوم
        $stats_sql = "SELECT 
                        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
                        COUNT(CASE WHEN status = 'accepted' THEN 1 END) as accepted_count,
                        COUNT(CASE WHEN status = 'on_the_way' THEN 1 END) as ontheway_count,
                        COUNT(CASE WHEN status = 'delivered' THEN 1 END) as delivered_count
                      FROM orders 
                      WHERE DATE(created_at) = CURDATE()";
        $stats_result = $conn->query($stats_sql);
        $stats = $stats_result ? $stats_result->fetch_assoc() : ['pending_count'=>0, 'accepted_count'=>0, 'ontheway_count'=>0, 'delivered_count'=>0];
        
        echo json_encode([
            'success' => true,
            'orders' => $orders,
            'stats' => $stats,
            'last_updated' => date('Y-m-d H:i:s')
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'خطأ في جلب الطلبات: ' . $e->getMessage()]);
    }
}

function acceptOrder() {
    global $conn;
    
    try {
        // قراءة المدخلات
        $input = json_decode(file_get_contents('php://input'), true);
        
        if (!$input) {
            echo json_encode(['success' => false, 'message' => 'بيانات غير صالحة']);
            return;
        }
        
        $order_id = isset($input['order_id']) ? (int)$input['order_id'] : 0;
        $captain_id = isset($input['captain_id']) ? (int)$input['captain_id'] : 0;
        $cashier_id = (int)$_SESSION[CASHIER_SESSION_KEY];
        
        if (!$order_id) {
            echo json_encode(['success' => false, 'message' => 'رقم الطلب مطلوب']);
            return;
        }
        
        if (!$captain_id) {
            echo json_encode(['success' => false, 'message' => 'يرجى اختيار كابتن']);
            return;
        }
        
        // التحقق من وجود الطلب
        $check_sql = "SELECT id, status FROM orders WHERE id = ?";
        $stmt = $conn->prepare($check_sql);
        $stmt->bind_param("i", $order_id);
        $stmt->execute();
        $check = $stmt->get_result();
        
        if ($check->num_rows === 0) {
            echo json_encode(['success' => false, 'message' => 'الطلب غير موجود']);
            return;
        }
        
        $order = $check->fetch_assoc();
        if ($order['status'] !== 'pending') {
            echo json_encode(['success' => false, 'message' => 'الطلب تمت معالجته مسبقاً']);
            return;
        }
        
        // تحديث الطلب
        $sql = "UPDATE orders SET 
                status = 'accepted', 
                captain_id = ?,
                cashier_id = ?,
                accepted_at = NOW(),
                updated_at = NOW()
                WHERE id = ?";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("iii", $captain_id, $cashier_id, $order_id);
        
        if ($stmt->execute()) {
            echo json_encode(['success' => true, 'message' => 'تم قبول الطلب بنجاح']);
        } else {
            echo json_encode(['success' => false, 'message' => 'فشل تحديث الطلب: ' . $stmt->error]);
        }
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'خطأ في قبول الطلب: ' . $e->getMessage()]);
    }
}

function checkUpdates() {
    global $conn;
    
    try {
        // استخدام قيمة افتراضية إذا لم يتم إرسال last_check
        $last_check = isset($_GET['last_check']) ? $_GET['last_check'] : date('Y-m-d H:i:s', strtotime('-1 minute'));
        $last_check = $conn->real_escape_string($last_check);
        
        // استعلام مع ملاحظات العميل (العمود notes)
        $sql = "SELECT o.id, o.status, o.captain_id, o.created_at as last_update,
                       o.notes,
                       c.name as customer_name,
                       cp.name as captain_name
                FROM orders o
                JOIN customers c ON o.customer_id = c.id
                LEFT JOIN captains cp ON o.captain_id = cp.id
                WHERE o.updated_at > '$last_check'
                   OR o.created_at > DATE_SUB(NOW(), INTERVAL 5 MINUTE)
                ORDER BY o.updated_at DESC
                LIMIT 30";
        
        $result = $conn->query($sql);
        
        $updated_orders = [];
        if ($result) {
            while ($row = $result->fetch_assoc()) {
                $updated_orders[] = $row;
            }
        }
        
        echo json_encode([
            'success' => true,
            'updated_orders' => $updated_orders,
            'count' => count($updated_orders),
            'server_time' => date('Y-m-d H:i:s')
        ]);
        
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'خطأ في التحقق من التحديثات: ' . $e->getMessage()]);
    }
}

// التأكد من عدم وجود مخرجات إضافية
ob_end_flush();
?>