<?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 coupons table if not exists
    $create_table = "CREATE TABLE IF NOT EXISTS coupons (
        id INT AUTO_INCREMENT PRIMARY KEY,
        code VARCHAR(50) UNIQUE NOT NULL,
        discount_type ENUM('percentage', 'fixed') DEFAULT 'percentage',
        discount_value DECIMAL(10, 2) NOT NULL,
        usage_limit INT DEFAULT NULL,
        usage_count INT DEFAULT 0,
        expiry_date DATE DEFAULT NULL,
        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 coupons
    $query = "SELECT * FROM coupons ORDER BY created_at DESC";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $coupons = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    $error = "خطأ: " . $e->getMessage();
    $coupons = [];
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['add_coupon'])) {
            $code = strtoupper($_POST['code']);
            $type = $_POST['discount_type'];
            $value = $_POST['discount_value'];
            $limit = !empty($_POST['usage_limit']) ? $_POST['usage_limit'] : NULL;
            $expiry = !empty($_POST['expiry_date']) ? $_POST['expiry_date'] : NULL;
            
            $query = "INSERT INTO coupons (code, discount_type, discount_value, usage_limit, expiry_date) 
                      VALUES (?, ?, ?, ?, ?)";
            $stmt = $db->prepare($query);
            $stmt->execute([$code, $type, $value, $limit, $expiry]);
            header("Location: index.php?added=1");
            exit;
        } elseif (isset($_POST['toggle_coupon'])) {
            $id = $_POST['coupon_id'];
            $query = "UPDATE coupons 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_coupon'])) {
            $id = $_POST['coupon_id'];
            $query = "DELETE FROM coupons 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>
                <button onclick="showAddModal()" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
                    <i class="fas fa-plus ml-2"></i>إضافة كوبون
                </button>
            </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($coupons, fn($c) => $c['is_active']));
                $expired_count = count(array_filter($coupons, fn($c) => !empty($c['expiry_date']) && strtotime($c['expiry_date']) < time()));
            ?>
            <div class="grid grid-cols-1 md:grid-cols-4 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($coupons); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-ticket-alt text-purple-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">
                        <div>
                            <p class="text-sm text-gray-600">منتهية</p>
                            <p class="text-2xl font-bold text-red-600"><?php echo $expired_count; ?></p>
                        </div>
                        <div class="w-12 h-12 bg-red-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-times-circle text-red-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-blue-600"><?php echo array_sum(array_column($coupons, 'usage_count')); ?></p>
                        </div>
                        <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
                            <i class="fas fa-chart-line text-blue-600 text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Coupons Grid -->
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                <?php if (!empty($coupons)): ?>
                    <?php foreach ($coupons as $coupon): ?>
                        <?php
                            $is_expired = !empty($coupon['expiry_date']) && strtotime($coupon['expiry_date']) < time();
                            $is_limit_reached = !empty($coupon['usage_limit']) && $coupon['usage_count'] >= $coupon['usage_limit'];
                        ?>
                        <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6 <?php echo (!$coupon['is_active'] || $is_expired || $is_limit_reached) ? 'opacity-60' : ''; ?>">
                            <div class="flex items-center justify-between mb-4">
                                <div class="bg-gradient-to-r from-purple-500 to-pink-500 text-white px-4 py-2 rounded-lg font-bold text-lg">
                                    <?php echo htmlspecialchars($coupon['code']); ?>
                                </div>
                                <?php if ($coupon['is_active'] && !$is_expired && !$is_limit_reached): ?>
                                    <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">
                                        <?php echo $is_expired ? 'منتهي' : ($is_limit_reached ? 'مكتمل' : 'معطل'); ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                            
                            <div class="space-y-3 mb-4">
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-600">الخصم:</span>
                                    <span class="font-bold text-purple-600">
                                        <?php echo $coupon['discount_type'] === 'percentage' ? $coupon['discount_value'] . '%' : 'EGP ' . number_format($coupon['discount_value'], 0); ?>
                                    </span>
                                </div>
                                <div class="flex items-center justify-between">
                                    <span class="text-gray-600">الاستخدام:</span>
                                    <span class="font-bold">
                                        <?php echo $coupon['usage_count']; ?> / <?php echo $coupon['usage_limit'] ?? '∞'; ?>
                                    </span>
                                </div>
                                <?php if (!empty($coupon['expiry_date'])): ?>
                                    <div class="flex items-center justify-between">
                                        <span class="text-gray-600">ينتهي:</span>
                                        <span class="font-bold <?php echo $is_expired ? 'text-red-600' : ''; ?>">
                                            <?php echo date('Y-m-d', strtotime($coupon['expiry_date'])); ?>
                                        </span>
                                    </div>
                                <?php endif; ?>
                            </div>
                            
                            <div class="flex gap-2">
                                <form method="POST" class="flex-1">
                                    <input type="hidden" name="coupon_id" value="<?php echo $coupon['id']; ?>">
                                    <button type="submit" name="toggle_coupon" 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 $coupon['is_active'] ? 'تعطيل' : 'تفعيل'; ?>
                                    </button>
                                </form>
                                <form method="POST" onsubmit="return confirm('هل أنت متأكد من حذف هذا الكوبون؟');">
                                    <input type="hidden" name="coupon_id" value="<?php echo $coupon['id']; ?>">
                                    <button type="submit" name="delete_coupon" 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-purple-100 rounded-full flex items-center justify-center mx-auto mb-4">
                            <i class="fas fa-ticket-alt text-4xl text-purple-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-purple-600 text-white px-6 py-3 rounded-lg hover:bg-purple-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">
            <div class="flex items-center justify-between p-4 border-b border-gray-200">
                <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="code" required class="w-full border border-gray-300 rounded-lg px-3 py-2 uppercase" 
                           placeholder="SUMMER2025">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">نوع الخصم</label>
                    <select name="discount_type" class="w-full border border-gray-300 rounded-lg px-3 py-2">
                        <option value="percentage">نسبة مئوية (%)</option>
                        <option value="fixed">مبلغ ثابت (EGP)</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">قيمة الخصم</label>
                    <input type="number" name="discount_value" required 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="usage_limit" class="w-full border border-gray-300 rounded-lg px-3 py-2" 
                           placeholder="اتركه فارغاً للاستخدام غير المحدود">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">تاريخ الانتهاء (اختياري)</label>
                    <input type="date" name="expiry_date" 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_coupon" class="flex-1 bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-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>
