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

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

// التحقق من وجود الجدول
try {
    $db->query("SELECT 1 FROM offers LIMIT 1");
} catch (Exception $e) {
    // الجدول غير موجود - إعادة توجيه للتثبيت
    header('Location: ../../setup/create_offers_system.php');
    exit;
}

$page_title = 'إدارة العروض';
$breadcrumb = [
    ['title' => 'الرئيسية', 'url' => '../dashboard.php'],
    ['title' => 'العروض']
];

// معالجة الحذف
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    $stmt = $db->prepare("DELETE FROM offers WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: index.php?success=deleted');
    exit;
}

// معالجة تغيير الحالة
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $stmt = $db->prepare("UPDATE offers SET is_active = NOT is_active WHERE id = ?");
    $stmt->execute([$id]);
    header('Location: index.php?success=toggled');
    exit;
}

// معالجة الإضافة/التعديل
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $title = $_POST['title'];
    $description = $_POST['description'];
    $discount_type = $_POST['discount_type'];
    $discount_value = $_POST['discount_value'];
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $min_purchase = $_POST['min_purchase'] ?? 0;
    $max_discount = $_POST['max_discount'] ?? null;
    $usage_limit = $_POST['usage_limit'] ?? 0;
    $priority = $_POST['priority'] ?? 0;
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    
    // معالجة رفع الصورة
    $image = null;
    if (isset($_FILES['image']) && $_FILES['image']['error'] === 0) {
        $upload_dir = '../../uploads/offers/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        $file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
        $file_name = 'offer_' . time() . '_' . rand(1000, 9999) . '.' . $file_ext;
        $file_path = $upload_dir . $file_name;
        
        if (move_uploaded_file($_FILES['image']['tmp_name'], $file_path)) {
            $image = 'uploads/offers/' . $file_name;
        }
    }
    
    if ($id) {
        // تحديث
        $sql = "UPDATE offers SET 
                title = ?, description = ?, discount_type = ?, discount_value = ?,
                start_date = ?, end_date = ?, min_purchase = ?, max_discount = ?,
                usage_limit = ?, priority = ?, is_active = ?";
        $params = [$title, $description, $discount_type, $discount_value, $start_date, $end_date, 
                   $min_purchase, $max_discount, $usage_limit, $priority, $is_active];
        
        if ($image) {
            $sql .= ", image = ?";
            $params[] = $image;
        }
        
        $sql .= " WHERE id = ?";
        $params[] = $id;
        
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
    } else {
        // إضافة جديد
        $sql = "INSERT INTO offers (title, description, discount_type, discount_value, start_date, end_date, 
                min_purchase, max_discount, usage_limit, priority, is_active, image) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $db->prepare($sql);
        $stmt->execute([$title, $description, $discount_type, $discount_value, $start_date, $end_date,
                       $min_purchase, $max_discount, $usage_limit, $priority, $is_active, $image]);
    }
    
    header('Location: index.php?success=saved');
    exit;
}

// جلب العروض
$offers = $db->query("SELECT * FROM offers ORDER BY priority ASC, created_at DESC")->fetchAll();

// جلب بيانات العرض للتعديل
$edit_offer = null;
if (isset($_GET['edit'])) {
    $edit_id = (int)$_GET['edit'];
    $stmt = $db->prepare("SELECT * FROM offers WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_offer = $stmt->fetch();
}

include '../includes/header.php';
?>

<div class="animate-fade-in">
    <?php if (isset($_GET['success'])): ?>
        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
            <?php
            $messages = [
                'saved' => 'تم حفظ العرض بنجاح',
                'deleted' => 'تم حذف العرض بنجاح',
                'toggled' => 'تم تغيير حالة العرض'
            ];
            echo $messages[$_GET['success']] ?? 'تمت العملية بنجاح';
            ?>
        </div>
    <?php endif; ?>

    <!-- نموذج الإضافة/التعديل -->
    <div class="bg-white rounded-lg shadow-md p-6 mb-6">
        <h2 class="text-xl font-bold mb-4 text-gray-800">
            <?php echo $edit_offer ? 'تعديل العرض' : 'إضافة عرض جديد'; ?>
        </h2>
        
        <form method="POST" enctype="multipart/form-data" class="space-y-4">
            <?php if ($edit_offer): ?>
                <input type="hidden" name="id" value="<?php echo $edit_offer['id']; ?>">
            <?php endif; ?>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">عنوان العرض *</label>
                    <input type="text" name="title" required
                           value="<?php echo $edit_offer['title'] ?? ''; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">صورة العرض</label>
                    <input type="file" name="image" accept="image/*"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg">
                    <?php if ($edit_offer && $edit_offer['image']): ?>
                        <img src="../../<?php echo $edit_offer['image']; ?>" class="mt-2 h-20 rounded">
                    <?php endif; ?>
                </div>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">وصف العرض</label>
                <textarea name="description" rows="3"
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500"><?php echo $edit_offer['description'] ?? ''; ?></textarea>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">نوع الخصم *</label>
                    <select name="discount_type" required
                            class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                        <option value="percentage" <?php echo ($edit_offer['discount_type'] ?? '') === 'percentage' ? 'selected' : ''; ?>>نسبة مئوية %</option>
                        <option value="fixed" <?php echo ($edit_offer['discount_type'] ?? '') === 'fixed' ? 'selected' : ''; ?>>مبلغ ثابت</option>
                    </select>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">قيمة الخصم *</label>
                    <input type="number" name="discount_value" step="0.01" required
                           value="<?php echo $edit_offer['discount_value'] ?? ''; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">الحد الأقصى للخصم</label>
                    <input type="number" name="max_discount" step="0.01"
                           value="<?php echo $edit_offer['max_discount'] ?? ''; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">تاريخ البداية *</label>
                    <input type="datetime-local" name="start_date" required
                           value="<?php echo isset($edit_offer['start_date']) ? date('Y-m-d/TH:i', strtotime($edit_offer['start_date'])) : ''; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">تاريخ النهاية *</label>
                    <input type="datetime-local" name="end_date" required
                           value="<?php echo isset($edit_offer['end_date']) ? date('Y-m-d/TH:i', strtotime($edit_offer['end_date'])) : ''; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">الحد الأدنى للشراء</label>
                    <input type="number" name="min_purchase" step="0.01"
                           value="<?php echo $edit_offer['min_purchase'] ?? 0; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">عدد مرات الاستخدام (0 = غير محدود)</label>
                    <input type="number" name="usage_limit"
                           value="<?php echo $edit_offer['usage_limit'] ?? 0; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">الأولوية</label>
                    <input type="number" name="priority"
                           value="<?php echo $edit_offer['priority'] ?? 0; ?>"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500">
                </div>
            </div>
            
            <div class="flex items-center">
                <input type="checkbox" name="is_active" id="is_active" value="1"
                       <?php echo ($edit_offer['is_active'] ?? 1) ? 'checked' : ''; ?>
                       class="w-4 h-4 text-blue-600 rounded">
                <label for="is_active" class="mr-2 text-sm text-gray-700">تفعيل العرض</label>
            </div>
            
            <div class="flex gap-2">
                <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                    <i class="fas fa-save ml-2"></i>
                    <?php echo $edit_offer ? 'تحديث' : 'إضافة'; ?>
                </button>
                <?php if ($edit_offer): ?>
                    <a href="index.php" class="px-6 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600">
                        إلغاء
                    </a>
                <?php endif; ?>
            </div>
        </form>
    </div>

    <!-- قائمة العروض -->
    <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <div class="p-6 border-b">
            <h2 class="text-xl font-bold text-gray-800">العروض الحالية</h2>
        </div>
        
        <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>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    <?php foreach ($offers as $offer): ?>
                        <?php
                        $now = time();
                        $start = strtotime($offer['start_date']);
                        $end = strtotime($offer['end_date']);
                        $is_expired = $now > $end;
                        $is_upcoming = $now < $start;
                        $is_running = $now >= $start && $now <= $end && $offer['is_active'];
                        ?>
                        <tr class="hover:bg-gray-50">
                            <td class="px-6 py-4">
                                <div class="flex items-center gap-3">
                                    <?php if ($offer['image']): ?>
                                        <img src="../../<?php echo $offer['image']; ?>" class="w-16 h-16 object-cover rounded">
                                    <?php else: ?>
                                        <div class="w-16 h-16 bg-gradient-to-br from-pink-400 to-purple-500 rounded flex items-center justify-center">
                                            <i class="fas fa-tag text-white text-2xl"></i>
                                        </div>
                                    <?php endif; ?>
                                    <div>
                                        <div class="font-medium text-gray-900"><?php echo htmlspecialchars($offer['title']); ?></div>
                                        <div class="text-sm text-gray-500"><?php echo htmlspecialchars(substr($offer['description'], 0, 50)); ?>...</div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4">
                                <span class="text-lg font-bold text-pink-600">
                                    <?php echo $offer['discount_value']; ?>
                                    <?php echo $offer['discount_type'] === 'percentage' ? '%' : 'ج.م'; ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 text-sm">
                                <div><?php echo date('Y-m-d', strtotime($offer['start_date'])); ?></div>
                                <div class="text-gray-500">إلى <?php echo date('Y-m-d', strtotime($offer['end_date'])); ?></div>
                            </td>
                            <td class="px-6 py-4 text-sm">
                                <?php if ($offer['usage_limit'] > 0): ?>
                                    <?php echo $offer['used_count']; ?> / <?php echo $offer['usage_limit']; ?>
                                <?php else: ?>
                                    <span class="text-gray-500">غير محدود</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4">
                                <?php if ($is_expired): ?>
                                    <span class="px-2 py-1 text-xs rounded-full bg-gray-200 text-gray-700">منتهي</span>
                                <?php elseif ($is_upcoming): ?>
                                    <span class="px-2 py-1 text-xs rounded-full bg-blue-100 text-blue-700">قادم</span>
                                <?php elseif ($is_running): ?>
                                    <span class="px-2 py-1 text-xs rounded-full bg-green-100 text-green-700">نشط</span>
                                <?php else: ?>
                                    <span class="px-2 py-1 text-xs rounded-full bg-gray-200 text-gray-700">متوقف</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4">
                                <div class="flex gap-2">
                                    <a href="?edit=<?php echo $offer['id']; ?>" 
                                       class="text-blue-600 hover:text-blue-800" title="تعديل">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="?toggle=<?php echo $offer['id']; ?>" 
                                       class="text-yellow-600 hover:text-yellow-800" title="تغيير الحالة">
                                        <i class="fas fa-toggle-<?php echo $offer['is_active'] ? 'on' : 'off'; ?>"></i>
                                    </a>
                                    <a href="?delete=<?php echo $offer['id']; ?>" 
                                       onclick="return confirm('هل أنت متأكد من حذف هذا العرض؟')"
                                       class="text-red-600 hover:text-red-800" title="حذف">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php include '../includes/footer.php'; ?>
