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

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

// التحقق من وجود جدول الطلبات
function checkOrdersTable() {
    global $conn;
    
    try {
        $stmt = $conn->query("SHOW TABLES LIKE 'orders'");
        return $stmt->rowCount() > 0;
    } catch (PDOException $e) {
        return false;
    }
}

// إنشاء جدول الطلبات إذا لم يكن موجودًا
function createOrdersTable() {
    global $conn;
    
    try {
        $conn->exec("
            CREATE TABLE IF NOT EXISTS orders (
                id INT AUTO_INCREMENT PRIMARY KEY,
                order_number VARCHAR(20) NOT NULL,
                client_name VARCHAR(100) NOT NULL,
                service_type VARCHAR(50),
                branch_id INT,
                departure_area VARCHAR(100),
                second_destination VARCHAR(100),
                delivery_area VARCHAR(100),
                goods_name VARCHAR(100),
                goods_type VARCHAR(50),
                country_of_origin VARCHAR(50),
                weight DECIMAL(10,2),
                quantity INT,
                unit VARCHAR(20),
                service_fees DECIMAL(10,2),
                currency VARCHAR(20),
                payment_type VARCHAR(50),
                delivery_duration VARCHAR(50),
                amount_paid DECIMAL(10,2),
                remaining_amount DECIMAL(10,2),
                order_upload_date DATE,
                scheduled_delivery_date DATE,
                recipient_name VARCHAR(100),
                phone_number VARCHAR(20),
                delivery_company VARCHAR(100),
                employee_name VARCHAR(100),
                notes TEXT,
                amount_agreed_with_customer DECIMAL(10,2),
                amount_agreed_with_agent DECIMAL(10,2),
                other_expenses DECIMAL(10,2),
                profit DECIMAL(10,2),
                payment_status VARCHAR(20) DEFAULT 'غير مدفوع',
                status VARCHAR(20) DEFAULT 'قيد المعالجة',
                archived TINYINT(1) DEFAULT 0,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
        ");
        
        return true;
    } catch (PDOException $e) {
        echo "خطأ في إنشاء جدول الطلبات: " . $e->getMessage();
        return false;
    }
}

// إضافة طلب جديد
function addOrder($orderData) {
    global $conn;
    
    try {
        // إعداد استعلام الإدراج
        $sql = "INSERT INTO orders (
            order_number, client_name, service_type, 
            departure_area, second_destination, delivery_area, goods_name, goods_type, 
            country_of_origin, weight, quantity, unit, service_fees, 
            currency, payment_type, delivery_duration, amount_paid, remaining_amount, 
            order_upload_date, scheduled_delivery_date, recipient_name, phone_number, 
            notes, amount_agreed_with_customer, amount_agreed_with_agent, other_expenses, 
            profit, payment_status, status
        ) VALUES (
            :order_number, :client_name, :service_type, 
            :departure_area, :second_destination, :delivery_area, :goods_name, :goods_type, 
            :country_of_origin, :weight, :quantity, :unit, :service_fees, 
            :currency, :payment_type, :delivery_duration, :amount_paid, :remaining_amount, 
            :order_upload_date, :scheduled_delivery_date, :recipient_name, :phone_number, 
            :notes, :amount_agreed_with_customer, :amount_agreed_with_agent, :other_expenses, 
            :profit, :payment_status, :status
        )";
        
        $stmt = $conn->prepare($sql);
        $stmt->execute($orderData);
        
        return [
            'status' => 'success',
            'message' => 'تم إضافة الطلب بنجاح',
            'orderId' => $conn->lastInsertId()
        ];
    } catch (PDOException $e) {
        return [
            'status' => 'error',
            'message' => 'فشل في إضافة الطلب: ' . $e->getMessage()
        ];
    }
}

// التحقق من وجود جدول الطلبات وإنشائه إذا لم يكن موجودًا
if (!checkOrdersTable()) {
    createOrdersTable();
}

// بيانات الطلبات التجريبية
$testOrders = [
    [
        'order_number' => 'ADN23-01',
        'client_name' => 'محمد علي',
        'service_type' => 'شحن بحري',
        'departure_area' => 'عدن',
        'second_destination' => '',
        'delivery_area' => 'صنعاء',
        'goods_name' => 'أجهزة كهربائية',
        'goods_type' => 'إلكترونيات',
        'country_of_origin' => 'الصين',
        'weight' => 150.00,
        'quantity' => 10,
        'unit' => 'كرتون',
        'service_fees' => 1000.00,
        'currency' => 'دولار',
        'payment_type' => 'كاش',
        'delivery_duration' => '3-5 أيام',
        'amount_paid' => 500.00,
        'remaining_amount' => 500.00,
        'order_upload_date' => date('Y-m-d'),
        'scheduled_delivery_date' => date('Y-m-d', strtotime('+5 days')),
        'recipient_name' => 'أحمد محمد',
        'phone_number' => '777123456',
        'notes' => 'يرجى الاتصال قبل التسليم',
        'amount_agreed_with_customer' => 1200.00,
        'amount_agreed_with_agent' => 800.00,
        'other_expenses' => 100.00,
        'profit' => 300.00,
        'payment_status' => 'جزئي',
        'status' => 'قيد المعالجة'
    ],
    [
        'order_number' => 'SNA23-01',
        'client_name' => 'علي محمد',
        'service_type' => 'شحن جوي',
        'departure_area' => 'صنعاء',
        'second_destination' => 'دبي',
        'delivery_area' => 'المكلا',
        'goods_name' => 'ملابس',
        'goods_type' => 'نسيج',
        'country_of_origin' => 'تركيا',
        'weight' => 100.00,
        'quantity' => 5,
        'unit' => 'كيس',
        'service_fees' => 800.00,
        'currency' => 'دولار',
        'payment_type' => 'تحويل بنكي',
        'delivery_duration' => '1-2 أيام',
        'amount_paid' => 800.00,
        'remaining_amount' => 0.00,
        'order_upload_date' => date('Y-m-d'),
        'scheduled_delivery_date' => date('Y-m-d', strtotime('+2 days')),
        'recipient_name' => 'سعيد عمر',
        'phone_number' => '777654321',
        'notes' => 'بضاعة قابلة للكسر',
        'amount_agreed_with_customer' => 1000.00,
        'amount_agreed_with_agent' => 600.00,
        'other_expenses' => 50.00,
        'profit' => 350.00,
        'payment_status' => 'مدفوع',
        'status' => 'في الطريق'
    ],
    [
        'order_number' => 'ADN23-02',
        'client_name' => 'حسن علي',
        'service_type' => 'شحن بري',
        'departure_area' => 'عدن',
        'second_destination' => '',
        'delivery_area' => 'المكلا',
        'goods_name' => 'أثاث منزلي',
        'goods_type' => 'أثاث',
        'country_of_origin' => 'الصين',
        'weight' => 150.00,
        'quantity' => 10,
        'unit' => 'قطعة',
        'service_fees' => 1000.00,
        'currency' => 'دولار',
        'payment_type' => 'كاش',
        'delivery_duration' => '5-7 أيام',
        'amount_paid' => 1000.00,
        'remaining_amount' => 0.00,
        'order_upload_date' => date('Y-m-d'),
        'scheduled_delivery_date' => date('Y-m-d', strtotime('+7 days')),
        'recipient_name' => 'عبدالله سالم',
        'phone_number' => '777987654',
        'notes' => 'توصيل إلى باب المنزل',
        'amount_agreed_with_customer' => 1200.00,
        'amount_agreed_with_agent' => 700.00,
        'other_expenses' => 150.00,
        'profit' => 350.00,
        'payment_status' => 'مدفوع',
        'status' => 'قيد المعالجة'
    ]
];

// إضافة الطلبات
$results = [];
foreach ($testOrders as $orderData) {
    $results[] = addOrder($orderData);
}

// عرض النتائج
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إضافة طلبات تجريبية</title>
    <style>
        body {
            font-family: 'Tajawal', sans-serif;
            background-color: #f8f9fa;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #4f46e5;
            text-align: center;
            margin-bottom: 30px;
        }
        .result {
            margin-bottom: 15px;
            padding: 15px;
            border-radius: 5px;
        }
        .success {
            background-color: #d1fae5;
            border: 1px solid #10b981;
            color: #047857;
        }
        .error {
            background-color: #fee2e2;
            border: 1px solid #ef4444;
            color: #b91c1c;
        }
        .btn {
            display: inline-block;
            padding: 10px 20px;
            background-color: #4f46e5;
            color: #fff;
            text-decoration: none;
            border-radius: 5px;
            margin-top: 20px;
            text-align: center;
        }
        .btn:hover {
            background-color: #4338ca;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>إضافة طلبات تجريبية</h1>
        
        <?php foreach ($results as $result): ?>
            <div class="result <?php echo $result['status'] === 'success' ? 'success' : 'error'; ?>">
                <strong><?php echo $result['message']; ?></strong>
                <?php if (isset($result['orderId'])): ?>
                    <p>معرف الطلب: <?php echo $result['orderId']; ?></p>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
        
        <a href="orders.php" class="btn">العودة إلى صفحة الطلبات</a>
    </div>
</body>
</html>
