<?php
session_start();

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

require_once '../../config/database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    // Create shipping_companies table if not exists
    $create_table = "CREATE TABLE IF NOT EXISTS shipping_companies (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        coverage ENUM('all', 'internal_only', 'gov_only') DEFAULT 'all',
        default_rate_internal DECIMAL(10, 2) DEFAULT 0,
        default_rate_gov DECIMAL(10, 2) DEFAULT 0,
        op_name VARCHAR(255),
        op_phone VARCHAR(20),
        is_active BOOLEAN DEFAULT TRUE,
        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";
    $db->exec($create_table);
    
    // Get all shipping companies
    $query = "SELECT * FROM shipping_companies ORDER BY name";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $companies = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get orders ready for shipping (pending or processing)
    $query = "SELECT COUNT(*) as count FROM orders WHERE status IN ('pending', 'processing')";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $ready_orders = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    
} catch (Exception $e) {
    $error = "خطأ: " . $e->getMessage();
    $companies = [];
    $ready_orders = 0;
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['add_company'])) {
            $name = $_POST['name'];
            $coverage = $_POST['coverage'];
            $rate_internal = $_POST['default_rate_internal'];
            $rate_gov = $_POST['default_rate_gov'];
            $op_name = $_POST['op_name'];
            $op_phone = $_POST['op_phone'];
            
            $query = "INSERT INTO shipping_companies (name, coverage, default_rate_internal, default_rate_gov, op_name, op_phone) 
                      VALUES (?, ?, ?, ?, ?, ?)";
            $stmt = $db->prepare($query);
            $stmt->execute([$name, $coverage, $rate_internal, $rate_gov, $op_name, $op_phone]);
            header("Location: index.php?added=1");
            exit;
        } elseif (isset($_POST['toggle_company'])) {
            $id = $_POST['company_id'];
            $query = "UPDATE shipping_companies SET is_active = NOT is_active WHERE id = ?";
            $stmt = $db->prepare($query);
            $stmt->execute([$id]);
            header("Location: index.php?updated=1");
            exit;
        } elseif (isset($_POST['delete_company'])) {
            $id = $_POST['company_id'];
            $query = "DELETE FROM shipping_companies WHERE id = ?";
            $stmt = $db->prepare($query);
            $stmt->execute([$id]);
            header("Location: index.php?deleted=1");
            exit;
        }
    } catch (Exception $e) {
        $message = "خطأ: " . $e->getMessage();
    }
}

if (isset($_GET['added'])) {
    $message = 'تم إضافة شركة الشحن بنجاح!';
} elseif (isset($_GET['updated'])) {
    $message = 'تم تحديث شركة الشحن بنجاح!';
} elseif (isset($_GET['deleted'])) {
    $message = 'تم حذف شركة الشحن بنجاح!';
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>إدارة الشحن - Roz Skin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
    </style>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <header class="bg-white shadow-sm border-b border-gray-200 sticky top-0 z-20">
            <div class="flex items-center justify-between px-6 py-4">
                <div class="flex items-center space-x-4 space-x-reverse">
                    <a href="../dashboard.php" class="text-gray-600 hover:text-gray-900">
                        <i class="fas fa-arrow-right text-xl"></i>
                    </a>
                    <h1 class="text-2xl font-bold text-gray-900">إدارة الشحن</h1>
                </div>
                <div class="flex gap-3">
                    <a href="update-status.php" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 flex items-center gap-2">
                        <i class="fas fa-exchange-alt"></i>
                        تحديث الحالة
                    </a>
                    <a href="list-manifests.php" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700 flex items-center gap-2">
                        <i class="fas fa-list"></i>
                        المانيفستات
                    </a>
                    <button onclick="showAddModal()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-plus ml-2"></i>إضافة شركة شحن
                    </button>
                </div>
            </div>
        </header>

        <div class="p-6">
            <?php if (isset($error)): ?>
                <div class="bg-red-50 border-r-4 border-red-400 p-4 mb-6">
                    <p class="text-sm text-red-700"><?php echo $error; ?></p>
                </div>
            <?php endif; ?>

            <?php if ($message): ?>
                <div class="bg-green-50 border-r-4 border-green-400 p-4 mb-6">
                    <p class="text-sm text-green-700"><?php echo $message; ?></p>
                </div>
            <?php endif; ?>

            <!-- Statistics -->
            <?php
                $active_count = count(array_filter($companies, fn($c) => $c['is_active']));
            ?>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">شركات الشحن</p>
                            <p class="text-2xl font-bold text-gray-900"><?php echo count($companies); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-truck text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-sm text-gray-600">الشركات النشطة</p>
                            <p class="text-2xl font-bold text-green-600"><?php echo $active_count; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-check-circle text-green-600 text-xl"></i>
                        </div>
                    </div>
                </div>
                <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4">
                    <div class="flex items-center justify-between mb-3">
                        <div>
                            <p class="text-sm text-gray-600">طلبات جاهزة للشحن</p>
                            <p class="text-2xl font-bold text-orange-600"><?php echo $ready_orders; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-orange-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-box text-orange-600 text-xl"></i>
                        </div>
                    </div>
                    <?php if ($ready_orders > 0): ?>
                        <a href="create-manifest.php" class="block w-full text-center bg-orange-600 text-white px-4 py-2 rounded-lg hover:bg-orange-700 text-sm font-bold">
                            <i class="fas fa-file-invoice"></i>
                            إنشاء مانيفست
                        </a>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Companies Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php if (!empty($companies)): ?>
                    <?php foreach ($companies as $company): ?>
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                            <div class="flex items-center justify-between mb-4">
                                <h3 class="text-xl font-bold text-gray-900"><?php echo htmlspecialchars($company['name']); ?></h3>
                                <?php if ($company['is_active']): ?>
                                    <span class="bg-green-100 text-green-800 px-3 py-1 rounded-full text-xs font-bold">نشط</span>
                                <?php else: ?>
                                    <span class="bg-red-100 text-red-800 px-3 py-1 rounded-full text-xs font-bold">معطل</span>
                                <?php endif; ?>
                            </div>
                            
                            <div class="space-y-3 mb-4">
                                <div class="flex items-center justify-between text-sm">
                                    <span class="text-gray-600">التغطية:</span>
                                    <span class="font-bold">
                                        <?php 
                                            echo $company['coverage'] === 'all' ? 'كل المحافظات' : 
                                                ($company['coverage'] === 'internal_only' ? 'داخلي فقط' : 'محافظات فقط');
                                        ?>
                                    </span>
                                </div>
                                <div class="flex items-center justify-between text-sm">
                                    <span class="text-gray-600">شحن داخلي:</span>
                                    <span class="font-bold text-blue-600">EGP <?php echo number_format($company['default_rate_internal'], 0); ?></span>
                                </div>
                                <div class="flex items-center justify-between text-sm">
                                    <span class="text-gray-600">شحن محافظات:</span>
                                    <span class="font-bold text-blue-600">EGP <?php echo number_format($company['default_rate_gov'], 0); ?></span>
                                </div>
                                <?php if (!empty($company['op_name'])): ?>
                                    <div class="pt-3 border-t">
                                        <p class="text-xs text-gray-600 mb-1">مدير العمليات:</p>
                                        <p class="font-semibold"><?php echo htmlspecialchars($company['op_name']); ?></p>
                                        <?php if (!empty($company['op_phone'])): ?>
                                            <a href="tel:<?php echo $company['op_phone']; ?>" class="text-sm text-blue-600">
                                                <i class="fas fa-phone ml-1"></i><?php echo htmlspecialchars($company['op_phone']); ?>
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="flex gap-2">
                                <form method="POST" class="flex-1">
                                    <input type="hidden" name="company_id" value="<?php echo $company['id']; ?>">
                                    <button type="submit" name="toggle_company" class="w-full bg-yellow-50 text-yellow-600 px-3 py-2 rounded-lg text-sm hover:bg-yellow-100">
                                        <i class="fas fa-toggle-on ml-1"></i><?php echo $company['is_active'] ? 'تعطيل' : 'تفعيل'; ?>
                                    </button>
                                </form>
                                <form method="POST" onsubmit="return confirm('هل أنت متأكد من حذف هذه الشركة؟');">
                                    <input type="hidden" name="company_id" value="<?php echo $company['id']; ?>">
                                    <button type="submit" name="delete_company" class="bg-red-50 text-red-600 px-3 py-2 rounded-lg text-sm hover:bg-red-100">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="col-span-3 bg-white rounded-lg shadow-sm border border-gray-200 p-12 text-center">
                        <div class="w-24 h-24 bg-blue-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-truck text-4xl text-blue-400"></i>
                        </div>
                        <h3 class="text-xl font-semibold text-gray-700 mb-2">لا توجد شركات شحن</h3>
                        <p class="text-gray-500 mb-6">ابدأ بإضافة شركات الشحن التي تتعامل معها</p>
                        <button onclick="showAddModal()" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700">
                            <i class="fas fa-plus ml-2"></i>إضافة شركة شحن
                        </button>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Add Modal -->
    <div id="addModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
        <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 max-h-[90vh] overflow-y-auto">
            <div class="flex items-center justify-between p-4 border-b border-gray-200 sticky top-0 bg-white">
                <h3 class="text-lg font-semibold text-gray-900">إضافة شركة شحن</h3>
                <button onclick="closeAddModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <form method="POST" class="p-4 space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">اسم الشركة</label>
                    <input type="text" name="name" required class="w-full border border-gray-300 rounded-lg px-3 py-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">نوع التغطية</label>
                    <select name="coverage" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                        <option value="all">كل المحافظات</option>
                        <option value="internal_only">داخلي فقط</option>
                        <option value="gov_only">محافظات فقط</option>
                    </select>
                </div>
                <div class="grid grid-cols-2 gap-3">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">سعر الشحن الداخلي</label>
                        <input type="number" name="default_rate_internal" value="0" step="0.01" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">سعر شحن المحافظات</label>
                        <input type="number" name="default_rate_gov" value="0" step="0.01" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                    </div>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">اسم مدير العمليات</label>
                    <input type="text" name="op_name" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">هاتف مدير العمليات</label>
                    <input type="text" name="op_phone" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                </div>
                <div class="flex gap-2 pt-2">
                    <button type="submit" name="add_company" class="flex-1 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                        <i class="fas fa-plus ml-1"></i>إضافة
                    </button>
                    <button type="button" onclick="closeAddModal()" class="flex-1 bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function showAddModal() {
            document.getElementById('addModal').classList.remove('hidden');
        }
        function closeAddModal() {
            document.getElementById('addModal').classList.add('hidden');
        }
    </script>
</body>
</html>
