<?php
session_start();

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

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

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

$message = '';
$message_type = 'success';

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_branch'])) {
        $name = trim($_POST['name']);
        $address = trim($_POST['address']);
        $phone = trim($_POST['phone']);
        $email = trim($_POST['email']);
        $latitude = trim($_POST['latitude']);
        $longitude = trim($_POST['longitude']);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        // Working hours
        $working_hours = [
            'monday' => $_POST['monday'] ?? '',
            'tuesday' => $_POST['tuesday'] ?? '',
            'wednesday' => $_POST['wednesday'] ?? '',
            'thursday' => $_POST['thursday'] ?? '',
            'friday' => $_POST['friday'] ?? '',
            'saturday' => $_POST['saturday'] ?? '',
            'sunday' => $_POST['sunday'] ?? ''
        ];
        
        $query = "INSERT INTO branches (name, address, phone, email, working_hours, is_active, latitude, longitude, created_at) 
                  VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$name, $address, $phone, $email, json_encode($working_hours), $is_active, $latitude, $longitude])) {
            $message = 'تم إضافة الفرع بنجاح!';
            $message_type = 'success';
        } else {
            $message = 'حدث خطأ أثناء إضافة الفرع';
            $message_type = 'error';
        }
    } elseif (isset($_POST['update_branch'])) {
        $branch_id = $_POST['branch_id'];
        $name = trim($_POST['name']);
        $address = trim($_POST['address']);
        $phone = trim($_POST['phone']);
        $email = trim($_POST['email']);
        $latitude = trim($_POST['latitude']);
        $longitude = trim($_POST['longitude']);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        $working_hours = [
            'monday' => $_POST['monday'] ?? '',
            'tuesday' => $_POST['tuesday'] ?? '',
            'wednesday' => $_POST['wednesday'] ?? '',
            'thursday' => $_POST['thursday'] ?? '',
            'friday' => $_POST['friday'] ?? '',
            'saturday' => $_POST['saturday'] ?? '',
            'sunday' => $_POST['sunday'] ?? ''
        ];
        
        $query = "UPDATE branches SET name = ?, address = ?, phone = ?, email = ?, working_hours = ?, is_active = ?, latitude = ?, longitude = ? WHERE id = ?";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$name, $address, $phone, $email, json_encode($working_hours), $is_active, $latitude, $longitude, $branch_id])) {
            $message = 'تم تحديث الفرع بنجاح!';
            $message_type = 'success';
        } else {
            $message = 'حدث خطأ أثناء تحديث الفرع';
            $message_type = 'error';
        }
    } elseif (isset($_POST['delete_branch'])) {
        $branch_id = $_POST['branch_id'];
        
        $query = "DELETE FROM branches WHERE id = ?";
        $stmt = $db->prepare($query);
        
        if ($stmt->execute([$branch_id])) {
            $message = 'تم حذف الفرع بنجاح!';
            $message_type = 'success';
        } else {
            $message = 'حدث خطأ أثناء حذف الفرع';
            $message_type = 'error';
        }
    }
}

// Get all branches
$query = "SELECT * FROM branches ORDER BY is_active DESC, name ASC";
$stmt = $db->prepare($query);
$stmt->execute();
$branches = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Days in Arabic
$days_ar = [
    'monday' => 'الإثنين',
    'tuesday' => 'الثلاثاء',
    'wednesday' => 'الأربعاء',
    'thursday' => 'الخميس',
    'friday' => 'الجمعة',
    'saturday' => 'السبت',
    'sunday' => 'الأحد'
];
?>
<!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; }
        .branch-card { transition: all 0.3s ease; }
        .branch-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0,0,0,0.1); }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">

    <!-- Header -->
    <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>
                <div>
                    <h1 class="text-2xl font-bold text-gray-900">إدارة الفروع</h1>
                    <p class="text-sm text-gray-500">إدارة فروع المتجر ومواقعها</p>
                </div>
            </div>
            <button onclick="openAddModal()" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition">
                <i class="fas fa-plus ml-2"></i>إضافة فرع
            </button>
        </div>
    </header>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto p-6">
        
        <!-- Success/Error Message -->
        <?php if ($message): ?>
            <div class="mb-6 p-4 rounded-lg border-r-4 <?php echo $message_type === 'success' ? 'bg-green-50 border-green-400' : 'bg-red-50 border-red-400'; ?>">
                <div class="flex items-center">
                    <i class="fas <?php echo $message_type === 'success' ? 'fa-check-circle text-green-400' : 'fa-exclamation-circle text-red-400'; ?> text-xl ml-3"></i>
                    <p class="text-sm <?php echo $message_type === 'success' ? 'text-green-700' : 'text-red-700'; ?>"><?php echo $message; ?></p>
                </div>
            </div>
        <?php endif; ?>

        <!-- Statistics -->
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">إجمالي الفروع</p>
                        <p class="text-3xl font-bold text-gray-900"><?php echo count($branches); ?></p>
                    </div>
                    <div class="bg-blue-50 p-3 rounded-lg">
                        <i class="fas fa-store text-blue-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">فروع نشطة</p>
                        <p class="text-3xl font-bold text-green-600">
                            <?php echo count(array_filter($branches, fn($b) => $b['is_active'])); ?>
                        </p>
                    </div>
                    <div class="bg-green-50 p-3 rounded-lg">
                        <i class="fas fa-check-circle text-green-600 text-2xl"></i>
                    </div>
                </div>
            </div>

            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
                <div class="flex items-center justify-between">
                    <div>
                        <p class="text-sm font-medium text-gray-600">فروع معطلة</p>
                        <p class="text-3xl font-bold text-red-600">
                            <?php echo count(array_filter($branches, fn($b) => !$b['is_active'])); ?>
                        </p>
                    </div>
                    <div class="bg-red-50 p-3 rounded-lg">
                        <i class="fas fa-times-circle text-red-600 text-2xl"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Branches Grid -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php if (!empty($branches)): ?>
                <?php foreach ($branches as $branch): ?>
                    <?php $working_hours = json_decode($branch['working_hours'], true) ?? []; ?>
                    <div class="branch-card bg-white rounded-lg shadow-sm border border-gray-200 overflow-hidden">
                        <!-- Header -->
                        <div class="bg-gradient-to-r from-blue-500 to-blue-600 p-4 text-white relative">
                            <?php if ($branch['is_active']): ?>
                                <span class="absolute top-3 left-3 bg-green-500 text-white px-2 py-1 rounded-full text-xs">
                                    <i class="fas fa-check-circle ml-1"></i>نشط
                                </span>
                            <?php else: ?>
                                <span class="absolute top-3 left-3 bg-red-500 text-white px-2 py-1 rounded-full text-xs">
                                    <i class="fas fa-times-circle ml-1"></i>معطل
                                </span>
                            <?php endif; ?>
                            
                            <div class="flex items-center">
                                <div class="w-12 h-12 bg-white rounded-full flex items-center justify-center text-blue-600 font-bold text-xl">
                                    <i class="fas fa-store"></i>
                                </div>
                                <div class="mr-3">
                                    <h3 class="text-xl font-bold"><?php echo htmlspecialchars($branch['name']); ?></h3>
                                </div>
                            </div>
                        </div>

                        <!-- Content -->
                        <div class="p-6">
                            <!-- Contact Info -->
                            <div class="space-y-3 mb-4">
                                <div class="flex items-start text-sm">
                                    <i class="fas fa-map-marker-alt text-red-600 w-5 mt-1"></i>
                                    <span class="text-gray-700 mr-2"><?php echo htmlspecialchars($branch['address']); ?></span>
                                </div>
                                
                                <?php if (!empty($branch['phone'])): ?>
                                    <div class="flex items-center text-sm">
                                        <i class="fas fa-phone text-blue-600 w-5"></i>
                                        <span class="text-gray-700 mr-2"><?php echo htmlspecialchars($branch['phone']); ?></span>
                                    </div>
                                <?php endif; ?>
                                
                                <?php if (!empty($branch['email'])): ?>
                                    <div class="flex items-center text-sm">
                                        <i class="fas fa-envelope text-green-600 w-5"></i>
                                        <span class="text-gray-700 mr-2"><?php echo htmlspecialchars($branch['email']); ?></span>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Working Hours -->
                            <div class="bg-gray-50 rounded-lg p-3 mb-4">
                                <h4 class="font-semibold text-gray-900 mb-2 text-sm">
                                    <i class="fas fa-clock text-blue-600 ml-1"></i>ساعات العمل
                                </h4>
                                <div class="space-y-1 text-xs">
                                    <?php foreach ($days_ar as $day_en => $day_ar): ?>
                                        <?php if (!empty($working_hours[$day_en]) && $working_hours[$day_en] !== 'closed'): ?>
                                            <div class="flex justify-between">
                                                <span class="text-gray-600"><?php echo $day_ar; ?>:</span>
                                                <span class="text-gray-900 font-medium"><?php echo htmlspecialchars($working_hours[$day_en]); ?></span>
                                            </div>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </div>
                            </div>

                            <!-- Map Link -->
                            <?php if (!empty($branch['latitude']) && !empty($branch['longitude'])): ?>
                                <a href="https://www.google.com/maps?q=<?php echo $branch['latitude']; ?>,<?php echo $branch['longitude']; ?>" 
                                   target="_blank"
                                   class="block bg-blue-50 text-blue-600 text-center px-3 py-2 rounded-md text-sm hover:bg-blue-100 transition mb-3">
                                    <i class="fas fa-map-marked-alt ml-1"></i>عرض على الخريطة
                                </a>
                            <?php endif; ?>

                            <!-- Actions -->
                            <div class="flex items-center gap-2 pt-3 border-t">
                                <button onclick='editBranch(<?php echo json_encode($branch); ?>)' 
                                        class="flex-1 bg-green-50 text-green-600 px-3 py-2 rounded-md text-sm hover:bg-green-100 transition">
                                    <i class="fas fa-edit ml-1"></i>تعديل
                                </button>
                                <form method="POST" class="flex-1" onsubmit="return confirm('هل أنت متأكد من حذف هذا الفرع؟')">
                                    <input type="hidden" name="branch_id" value="<?php echo $branch['id']; ?>">
                                    <button type="submit" name="delete_branch"
                                            class="w-full bg-red-50 text-red-600 px-3 py-2 rounded-md text-sm hover:bg-red-100 transition">
                                        <i class="fas fa-trash ml-1"></i>حذف
                                    </button>
                                </form>
                            </div>
                        </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-gray-100 rounded-full flex items-center justify-center mx-auto mb-4">
                        <i class="fas fa-store text-4xl text-gray-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="openAddModal()" 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>

    <!-- Add/Edit Modal -->
    <div id="branchModal" class="hidden fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
        <div class="bg-white rounded-lg max-w-2xl w-full max-h-[90vh] overflow-y-auto">
            <div class="sticky top-0 bg-white border-b px-6 py-4 flex items-center justify-between">
                <h2 id="modalTitle" class="text-2xl font-bold text-gray-900">إضافة فرع جديد</h2>
                <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-2xl"></i>
                </button>
            </div>
            
            <form method="POST" class="p-6">
                <input type="hidden" name="branch_id" id="branch_id">
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">اسم الفرع *</label>
                        <input type="text" name="name" id="name" required
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">رقم الهاتف</label>
                        <input type="tel" name="phone" id="phone"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>

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

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">البريد الإلكتروني</label>
                    <input type="email" name="email" id="email"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">خط العرض (Latitude)</label>
                        <input type="text" name="latitude" id="latitude" placeholder="30.0444"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                    
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">خط الطول (Longitude)</label>
                        <input type="text" name="longitude" id="longitude" placeholder="31.2357"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>
                </div>

                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-3">ساعات العمل</label>
                    <div class="space-y-2">
                        <?php foreach ($days_ar as $day_en => $day_ar): ?>
                            <div class="flex items-center gap-3">
                                <span class="w-20 text-sm text-gray-700"><?php echo $day_ar; ?>:</span>
                                <input type="text" name="<?php echo $day_en; ?>" id="<?php echo $day_en; ?>" 
                                       placeholder="9:00-18:00 أو closed"
                                       class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="mb-6">
                    <label class="flex items-center space-x-2 space-x-reverse cursor-pointer">
                        <input type="checkbox" name="is_active" id="is_active" value="1" checked
                               class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500">
                        <span class="text-sm font-medium text-gray-700">فرع نشط</span>
                    </label>
                </div>

                <div class="flex gap-3">
                    <button type="submit" name="add_branch" id="submitBtn"
                            class="flex-1 bg-blue-600 text-white px-4 py-3 rounded-lg font-medium hover:bg-blue-700 transition">
                        <i class="fas fa-save ml-2"></i>حفظ الفرع
                    </button>
                    <button type="button" onclick="closeModal()"
                            class="px-6 py-3 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition">
                        إلغاء
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        function openAddModal() {
            document.getElementById('modalTitle').textContent = 'إضافة فرع جديد';
            document.getElementById('submitBtn').name = 'add_branch';
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save ml-2"></i>حفظ الفرع';
            document.getElementById('branchModal').classList.remove('hidden');
            document.querySelector('form').reset();
            document.getElementById('is_active').checked = true;
        }

        function editBranch(branch) {
            document.getElementById('modalTitle').textContent = 'تعديل الفرع';
            document.getElementById('submitBtn').name = 'update_branch';
            document.getElementById('submitBtn').innerHTML = '<i class="fas fa-save ml-2"></i>تحديث الفرع';
            
            document.getElementById('branch_id').value = branch.id;
            document.getElementById('name').value = branch.name;
            document.getElementById('address').value = branch.address;
            document.getElementById('phone').value = branch.phone || '';
            document.getElementById('email').value = branch.email || '';
            document.getElementById('latitude').value = branch.latitude || '';
            document.getElementById('longitude').value = branch.longitude || '';
            document.getElementById('is_active').checked = branch.is_active == 1;
            
            const workingHours = JSON.parse(branch.working_hours || '{}');
            const days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
            days.forEach(day => {
                document.getElementById(day).value = workingHours[day] || '';
            });
            
            document.getElementById('branchModal').classList.remove('hidden');
        }

        function closeModal() {
            document.getElementById('branchModal').classList.add('hidden');
        }

        // Close modal on outside click
        document.getElementById('branchModal').addEventListener('click', function(e) {
            if (e.target === this) {
                closeModal();
            }
        });
    </script>
</body>
</html>
