<?php
session_start();
require_once '../../config/database.php';

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

// تحديث وقت آخر نشاط
$_SESSION['last_activity'] = time();

$database = new Database();
$conn = $database->getConnection();

$message = '';

// إضافة/تعديل مورد
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_supplier'])) {
    $id = $_POST['supplier_id'] ?? null;
    $name = $_POST['name'];
    $contact_person = $_POST['contact_person'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $address = $_POST['address'];
    $notes = $_POST['notes'];
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    try {
        if ($id) {
            $stmt = $conn->prepare("UPDATE suppliers SET name=?, contact_person=?, phone=?, email=?, address=?, notes=?, is_active=? WHERE id=?");
            $stmt->execute([$name, $contact_person, $phone, $email, $address, $notes, $is_active, $id]);
            $message = 'تم تحديث المورد بنجاح';
        } else {
            $stmt = $conn->prepare("INSERT INTO suppliers (name, contact_person, phone, email, address, notes, is_active) VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$name, $contact_person, $phone, $email, $address, $notes, $is_active]);
            $message = 'تم إضافة المورد بنجاح';
        }
    } catch (Exception $e) {
        $message = 'حدث خطأ: ' . $e->getMessage();
    }
}

// حذف مورد
if (isset($_GET['delete'])) {
    try {
        $stmt = $conn->prepare("DELETE FROM suppliers WHERE id = ?");
        $stmt->execute([$_GET['delete']]);
        $message = 'تم حذف المورد بنجاح';
    } catch (Exception $e) {
        $message = 'حدث خطأ: ' . $e->getMessage();
    }
}

// الحصول على الموردين
$stmt = $conn->query("SELECT * FROM suppliers ORDER BY name ASC");
$suppliers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// إحصائيات
$stmt = $conn->query("SELECT COUNT(*) FROM suppliers WHERE is_active = 1");
$active_suppliers = $stmt->fetchColumn();

$stmt = $conn->query("SELECT COUNT(*) FROM suppliers");
$total_suppliers = $stmt->fetchColumn();
?>
<!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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
</head>
<body class="bg-gray-50">
    <div class="min-h-screen">
        <div class="bg-gradient-to-r from-indigo-600 to-indigo-800 text-white p-6 shadow-lg">
            <div class="max-w-7xl mx-auto">
                <div class="flex items-center justify-between">
                    <div>
                        <h1 class="text-3xl font-bold mb-2">🏭 إدارة الموردين</h1>
                        <p class="text-indigo-100">إدارة معلومات الموردين والتواصل معهم</p>
                    </div>
                    <div class="flex gap-3">
                        <button onclick="openSupplierModal()" class="bg-white text-indigo-600 px-6 py-2 rounded-lg hover:bg-indigo-50">
                            <i class="fas fa-plus ml-2"></i> مورد جديد
                        </button>
                        <a href="index.php" class="bg-indigo-700 text-white px-6 py-2 rounded-lg hover:bg-indigo-600">
                            <i class="fas fa-arrow-right ml-2"></i> المخزون
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <div class="max-w-7xl mx-auto p-6">
            <!-- إحصائيات -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">إجمالي الموردين</p>
                            <p class="text-3xl font-bold text-gray-800"><?php echo $total_suppliers; ?></p>
                        </div>
                        <div class="bg-indigo-100 p-4 rounded-full">
                            <i class="fas fa-truck text-indigo-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">موردين نشطين</p>
                            <p class="text-3xl font-bold text-green-600"><?php echo $active_suppliers; ?></p>
                        </div>
                        <div class="bg-green-100 p-4 rounded-full">
                            <i class="fas fa-check-circle text-green-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-lg shadow-md p-6">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-gray-500 text-sm">موردين غير نشطين</p>
                            <p class="text-3xl font-bold text-gray-600"><?php echo $total_suppliers - $active_suppliers; ?></p>
                        </div>
                        <div class="bg-gray-100 p-4 rounded-full">
                            <i class="fas fa-pause-circle text-gray-600 text-2xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- جدول الموردين -->
            <div class="bg-white rounded-lg shadow-md overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">اسم المورد</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">جهة الاتصال</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الهاتف</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">البريد</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">العنوان</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الحالة</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">إجراءات</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php foreach ($suppliers as $supplier): ?>
                            <tr class="hover:bg-gray-50">
                                <td class="px-6 py-4 font-medium"><?php echo htmlspecialchars($supplier['name']); ?></td>
                                <td class="px-6 py-4 text-sm"><?php echo htmlspecialchars($supplier['contact_person'] ?? '-'); ?></td>
                                <td class="px-6 py-4 text-sm">
                                    <?php if ($supplier['phone']): ?>
                                        <a href="https://wa.me/<?php echo preg_replace('/[^0-9]/', '', $supplier['phone']); ?>" 
                                           target="_blank" class="text-green-600 hover:text-green-700">
                                            <i class="fab fa-whatsapp ml-1"></i>
                                            <?php echo htmlspecialchars($supplier['phone']); ?>
                                        </a>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-sm">
                                    <?php if ($supplier['email']): ?>
                                        <a href="mailto:<?php echo htmlspecialchars($supplier['email']); ?>" 
                                           class="text-blue-600 hover:text-blue-700">
                                            <?php echo htmlspecialchars($supplier['email']); ?>
                                        </a>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4 text-sm"><?php echo htmlspecialchars($supplier['address'] ?? '-'); ?></td>
                                <td class="px-6 py-4">
                                    <?php if ($supplier['is_active']): ?>
                                        <span class="px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800">نشط</span>
                                    <?php else: ?>
                                        <span class="px-3 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800">غير نشط</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="flex gap-2">
                                        <button onclick='editSupplier(<?php echo json_encode($supplier); ?>)' 
                                                class="bg-blue-600 text-white px-3 py-1 rounded hover:bg-blue-700 text-sm">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button onclick="deleteSupplier(<?php echo $supplier['id']; ?>)" 
                                                class="bg-red-600 text-white px-3 py-1 rounded hover:bg-red-700 text-sm">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal المورد -->
    <div id="supplierModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
        <div class="bg-white rounded-lg p-8 max-w-2xl w-full mx-4 max-h-[90vh] overflow-y-auto">
            <h3 class="text-2xl font-bold mb-6" id="modalTitle">إضافة مورد جديد</h3>
            <form method="POST">
                <input type="hidden" name="supplier_id" id="supplier_id">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">اسم المورد *</label>
                        <input type="text" name="name" id="name" required 
                               class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">جهة الاتصال</label>
                        <input type="text" name="contact_person" id="contact_person" 
                               class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">رقم الهاتف</label>
                        <input type="text" name="phone" id="phone" 
                               class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                    </div>
                    <div>
                        <label class="block text-gray-700 font-medium mb-2">البريد الإلكتروني</label>
                        <input type="email" name="email" id="email" 
                               class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500">
                    </div>
                </div>

                <div class="mb-4">
                    <label class="block text-gray-700 font-medium mb-2">العنوان</label>
                    <textarea name="address" id="address" rows="2" 
                              class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500"></textarea>
                </div>

                <div class="mb-4">
                    <label class="block text-gray-700 font-medium mb-2">ملاحظات</label>
                    <textarea name="notes" id="notes" rows="3" 
                              class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500"></textarea>
                </div>

                <div class="mb-6">
                    <label class="flex items-center">
                        <input type="checkbox" name="is_active" id="is_active" checked 
                               class="ml-2 w-5 h-5 text-indigo-600">
                        <span class="text-gray-700 font-medium">مورد نشط</span>
                    </label>
                </div>

                <div class="flex gap-4">
                    <button type="submit" name="save_supplier" 
                            class="flex-1 bg-indigo-600 text-white px-6 py-3 rounded-lg hover:bg-indigo-700 font-medium">
                        <i class="fas fa-save ml-2"></i> حفظ
                    </button>
                    <button type="button" onclick="closeSupplierModal()" 
                            class="flex-1 bg-gray-300 text-gray-700 px-6 py-3 rounded-lg hover:bg-gray-400 font-medium">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openSupplierModal() {
            document.getElementById('modalTitle').textContent = 'إضافة مورد جديد';
            document.getElementById('supplier_id').value = '';
            document.getElementById('name').value = '';
            document.getElementById('contact_person').value = '';
            document.getElementById('phone').value = '';
            document.getElementById('email').value = '';
            document.getElementById('address').value = '';
            document.getElementById('notes').value = '';
            document.getElementById('is_active').checked = true;
            document.getElementById('supplierModal').classList.remove('hidden');
        }

        function editSupplier(supplier) {
            document.getElementById('modalTitle').textContent = 'تعديل المورد';
            document.getElementById('supplier_id').value = supplier.id;
            document.getElementById('name').value = supplier.name;
            document.getElementById('contact_person').value = supplier.contact_person || '';
            document.getElementById('phone').value = supplier.phone || '';
            document.getElementById('email').value = supplier.email || '';
            document.getElementById('address').value = supplier.address || '';
            document.getElementById('notes').value = supplier.notes || '';
            document.getElementById('is_active').checked = supplier.is_active == 1;
            document.getElementById('supplierModal').classList.remove('hidden');
        }

        function closeSupplierModal() {
            document.getElementById('supplierModal').classList.add('hidden');
        }

        function deleteSupplier(id) {
            Swal.fire({
                title: 'هل أنت متأكد؟',
                text: 'سيتم حذف المورد نهائياً',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'نعم، احذف',
                cancelButtonText: 'إلغاء'
            }).then((result) => {
                if (result.isConfirmed) {
                    window.location.href = '?delete=' + id;
                }
            });
        }

        <?php if ($message): ?>
        Swal.fire({
            icon: 'success',
            title: 'نجح!',
            text: '<?php echo $message; ?>',
            timer: 2000,
            showConfirmButton: false
        });
        <?php endif; ?>
    </script>
</body>
</html>
