<?php
// تفعيل عرض الأخطاء للتصحيح
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// تضمين ملف الاتصال بقاعدة البيانات
require_once '../config/db_connection.php';

// التحقق من أن الطلب هو طلب GET
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'يجب استخدام طريقة GET']);
    exit;
}

// بدء الجلسة إذا لم تكن قد بدأت بالفعل
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

try {
    // الحصول على معلمات التصفية
    $status = isset($_GET['status']) ? $_GET['status'] : null;
    $branch = isset($_GET['branch']) ? $_GET['branch'] : null;
    $search = isset($_GET['search']) ? $_GET['search'] : null;
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    $offset = ($page - 1) * $limit;

    // التحقق من دور المستخدم وتحديد ما إذا كان يجب تقييد الطلبات
    $userRole = isset($_SESSION['role']) ? $_SESSION['role'] : 'user';
    $userId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;

    // بناء استعلام SQL
    $sql = "
        SELECT
            o.id, o.order_number, o.client_name, b.name as branch,
            o.departure_area, o.second_destination, o.delivery_area,
            o.goods_name, o.goods_type, o.country_of_origin,
            o.weight, o.quantity, o.unit, o.service_fees,
            o.currency, o.payment_type, o.delivery_duration,
            o.amount_paid, o.remaining_amount, o.order_upload_date,
            o.scheduled_delivery_date, o.recipient_name, o.phone_number,
            o.delivery_company, o.employee_name, o.notes,
            o.amount_agreed_with_customer, o.amount_agreed_with_agent,
            o.other_expenses, o.profit, o.payment_status, o.status,
            o.created_at, o.updated_at
        FROM orders o
        LEFT JOIN branches b ON o.branch_id = b.id
        WHERE o.archived = 0
    ";

    // إضافة شروط التصفية
    $params = [];

    // تقييد الطلبات للمستخدمين العاديين (غير المديرين)
    if ($userRole !== 'admin' && $userRole !== 'manager' && $userId) {
        // المستخدم العادي يرى فقط الطلبات الخاصة به
        $sql .= " AND o.user_id = ?";
        $params[] = $userId;
    }

    if ($status) {
        $sql .= " AND o.status = ?";
        $params[] = $status;
    }

    if ($branch) {
        $sql .= " AND b.name = ?";
        $params[] = $branch;
    }

    if ($search) {
        $sql .= " AND (o.order_number LIKE ? OR o.client_name LIKE ? OR o.service_type LIKE ? OR o.goods_name LIKE ? OR o.goods_type LIKE ? OR o.country_of_origin LIKE ? OR o.departure_area LIKE ? OR o.second_destination LIKE ? OR o.delivery_area LIKE ? OR o.recipient_name LIKE ? OR o.phone_number LIKE ? OR o.notes LIKE ?)";
        $searchParam = "%$search%";
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
        $params[] = $searchParam;
    }

    // استعلام لحساب إجمالي عدد النتائج
    $countSql = str_replace("SELECT
            o.id, o.order_number, o.client_name, b.name as branch,
            o.departure_area, o.second_destination, o.delivery_area,
            o.goods_name, o.goods_type, o.country_of_origin,
            o.weight, o.quantity, o.unit, o.service_fees,
            o.currency, o.payment_type, o.delivery_duration,
            o.amount_paid, o.remaining_amount, o.order_upload_date,
            o.scheduled_delivery_date, o.recipient_name, o.phone_number,
            o.delivery_company, o.employee_name, o.notes,
            o.amount_agreed_with_customer, o.amount_agreed_with_agent,
            o.other_expenses, o.profit, o.payment_status, o.status,
            o.created_at, o.updated_at", "SELECT COUNT(*) as total", $sql);

    // تنفيذ استعلام العدد
    $countStmt = $conn->prepare($countSql);
    $countStmt->execute($params);
    $totalResult = $countStmt->fetch();
    $total = $totalResult['total'];

    // إضافة ترتيب وحدود للاستعلام الرئيسي
    $sql .= " ORDER BY o.created_at DESC LIMIT $limit OFFSET $offset";

    // تنفيذ الاستعلام الرئيسي
    $stmt = $conn->prepare($sql);
    $stmt->execute($params);
    $orders = $stmt->fetchAll();

    // تحويل البيانات إلى التنسيق المطلوب للعرض في الواجهة
    $formattedOrders = [];
    foreach ($orders as $order) {
        // تنسيق التواريخ
        $uploadDate = $order['order_upload_date'] ? date('Y-m-d', strtotime($order['order_upload_date'])) : null;
        $deliveryDate = $order['scheduled_delivery_date'] ? date('Y-m-d', strtotime($order['scheduled_delivery_date'])) : null;
        $createdAt = $order['created_at'] ? date('Y-m-d H:i:s', strtotime($order['created_at'])) : null;

        // إضافة الطلب المنسق
        $formattedOrders[] = [
            'id' => $order['id'],
            'orderNumber' => $order['order_number'],
            'clientName' => $order['client_name'],
            'branch' => $order['branch'],
            'departureArea' => $order['departure_area'],
            'secondDestination' => $order['second_destination'],
            'deliveryArea' => $order['delivery_area'],
            'goodsName' => $order['goods_name'],
            'goodsType' => $order['goods_type'],
            'countryOfOrigin' => $order['country_of_origin'],
            'weight' => $order['weight'],
            'quantity' => $order['quantity'],
            'unit' => $order['unit'],
            'serviceFees' => $order['service_fees'],
            'currency' => $order['currency'],
            'paymentType' => $order['payment_type'],
            'deliveryDuration' => $order['delivery_duration'],
            'amountPaid' => $order['amount_paid'],
            'remainingAmount' => $order['remaining_amount'],
            'uploadDate' => $uploadDate,
            'deliveryDate' => $deliveryDate,
            'recipientName' => $order['recipient_name'],
            'phoneNumber' => $order['phone_number'],
            'deliveryCompany' => $order['delivery_company'],
            'employeeName' => $order['employee_name'],
            'notes' => $order['notes'],
            'amountAgreedWithCustomer' => $order['amount_agreed_with_customer'],
            'amountAgreedWithAgent' => $order['amount_agreed_with_agent'],
            'otherExpenses' => $order['other_expenses'],
            'profit' => $order['profit'],
            'paymentStatus' => $order['payment_status'],
            'status' => $order['status'],
            'createdAt' => $createdAt
        ];
    }

    // إرجاع البيانات
    header('Content-Type: application/json');
    echo json_encode([
        'status' => 'success',
        'total' => $total,
        'page' => $page,
        'limit' => $limit,
        'totalPages' => ceil($total / $limit),
        'orders' => $formattedOrders
    ]);

} catch (PDOException $e) {
    // إرجاع رسالة الخطأ
    header('Content-Type: application/json');
    echo json_encode(['status' => 'error', 'message' => 'فشل جلب الطلبات: ' . $e->getMessage()]);
}
?>
