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

// منع أي مخرجات قبل JSON
ob_clean();

require_once 'config.php';

// تعيين header JSON
header('Content-Type: application/json');

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

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

switch($action) {
    case 'get_orders':
        getOrders();
        break;
    case 'accept_order':
        acceptOrder();
        break;
    case 'check_updates':
        checkUpdates();
        break;
    default:
        echo json_encode(['success' => false, 'message' => 'إجراء غير معروف']);
}

function getOrders() {
    global $conn;
    
    $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 = $order_id";
        
        $result = $conn->query($sql);
        
        if (!$result || $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 = $order_id";
        $items_result = $conn->query($items_sql);
        
        $order['items'] = [];
        if ($items_result) {
            while ($item = $items_result->fetch_assoc()) {
                $order['items'][] = $item;
            }
        }
        
        echo json_encode(['success' => true, 'order' => $order]);
        return;
    }
    
    // فلتر الحالة
    $status_filter = $status !== 'all' ? "AND o.status = '" . $conn->real_escape_string($status) . "'" : "";
    $limit = $status === 'pending' ? 10 : 50;
    
    // جلب الطلبات
    $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 
                CASE o.status
                    WHEN 'pending' THEN 1
                    WHEN 'accepted' THEN 2
                    WHEN 'on_the_way' THEN 3
                    WHEN 'delivered' THEN 4
                    ELSE 5
                END,
                o.created_at ASC
            LIMIT $limit";
    
    $result = $conn->query($sql);
    $orders = [];
    
    if ($result) {
        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 = {$row['id']}";
            $items_result = $conn->query($items_sql);
            
            $row['items'] = [];
            if ($items_result) {
                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')
    ]);
}

function acceptOrder() {
    global $conn;
    
    // قراءة المدخلات
    $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 || !$captain_id) {
        echo json_encode(['success' => false, 'message' => 'بيانات ناقصة']);
        return;
    }
    
    // التحقق من وجود الطلب
    $check = $conn->query("SELECT id, status FROM orders WHERE id = $order_id");
    if (!$check || $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 = $captain_id,
            cashier_id = $cashier_id,
            updated_at = NOW()
            WHERE id = $order_id";
    
    if ($conn->query($sql)) {
        echo json_encode(['success' => true, 'message' => 'تم قبول الطلب بنجاح']);
    } else {
        echo json_encode(['success' => false, 'message' => 'فشل تحديث الطلب']);
    }
}

function checkUpdates() {
    global $conn;
    
    $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);
    
    $sql = "SELECT o.id, o.status, o.captain_id, o.updated_at,
                   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'
            ORDER BY o.updated_at DESC";
    
    $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')
    ]);
}
?>