<?php
/**
 * direct_discounts.php - إدارة التخفيضات المباشرة
 * @version 3.0.0 - تصميم احترافي متجاوب
 */

require_once 'config.php';
checkAdminAuth();

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

// ============================================
// معالجة النماذج
// ============================================
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
    // إضافة تخفيض
    if (isset($_POST['add_discount'])) {
        try {
            $discount_name = $conn->real_escape_string($_POST['discount_name']);
            $discount_type = $conn->real_escape_string($_POST['discount_type']);
            $discount_value = (float)$_POST['discount_value'];
            $target_type = $conn->real_escape_string($_POST['target_type']);
            
            // معالجة target_id
            $target_id = !empty($_POST['target_id']) ? (int)$_POST['target_id'] : 'NULL';
            
            $min_order_amount = (float)$_POST['min_order_amount'];
            $start_date = $conn->real_escape_string($_POST['start_date']);
            $end_date = $conn->real_escape_string($_POST['end_date']);
            $is_active = isset($_POST['is_active']) ? 1 : 0;
            
            $sql = "INSERT INTO direct_discounts 
                    (discount_name, discount_type, discount_value, target_type, target_id, 
                     min_order_amount, start_date, end_date, is_active, created_at) 
                    VALUES 
                    ('$discount_name', '$discount_type', $discount_value, '$target_type', " . 
                    ($target_id !== 'NULL' ? $target_id : "NULL") . ", 
                    $min_order_amount, '$start_date', '$end_date', $is_active, NOW())";
            
            if ($conn->query($sql)) {
                $_SESSION['success_message'] = "✅ تم إضافة التخفيض بنجاح";
                header('Location: direct_discounts.php');
                exit();
            } else {
                throw new Exception($conn->error);
            }
        } catch (Exception $e) {
            $message = "❌ حدث خطأ: " . $e->getMessage();
            $message_type = "danger";
        }
    }
    
    // تغيير حالة التخفيض
    if (isset($_POST['toggle_status'])) {
        $discount_id = (int)$_POST['discount_id'];
        $status = (int)$_POST['status'];
        
        if ($conn->query("UPDATE direct_discounts SET is_active = $status WHERE id = $discount_id")) {
            $_SESSION['success_message'] = "✅ تم تحديث حالة التخفيض";
        } else {
            $_SESSION['error_message'] = "❌ حدث خطأ";
        }
        header('Location: direct_discounts.php');
        exit();
    }
    
    // حذف تخفيض
    if (isset($_POST['delete_discount'])) {
        $discount_id = (int)$_POST['discount_id'];
        
        if ($conn->query("DELETE FROM direct_discounts WHERE id = $discount_id")) {
            $_SESSION['success_message'] = "✅ تم حذف التخفيض بنجاح";
        } else {
            $_SESSION['error_message'] = "❌ حدث خطأ";
        }
        header('Location: direct_discounts.php');
        exit();
    }
}

// ============================================
// جلب البيانات
// ============================================

// جلب جميع التخفيضات
$discounts = $conn->query("
    SELECT * FROM direct_discounts 
    ORDER BY 
        CASE 
            WHEN is_active = 1 AND end_date >= NOW() THEN 1
            WHEN is_active = 1 AND end_date < NOW() THEN 2
            ELSE 3
        END,
        created_at DESC
");

// جلب الفئات
$categories = $conn->query("SELECT id, name FROM categories ORDER BY name");
$categories_array = [];
if ($categories) {
    while ($cat = $categories->fetch_assoc()) {
        $categories_array[$cat['id']] = $cat['name'];
    }
}

// جلب الوجبات
$meals = $conn->query("SELECT id, name FROM meals ORDER BY name");
$meals_array = [];
if ($meals) {
    while ($meal = $meals->fetch_assoc()) {
        $meals_array[$meal['id']] = $meal['name'];
    }
}

// جلب العملاء
$customers_array = [];

// المحاولة الأولى: البحث عن عمود name
$check_name = $conn->query("SHOW COLUMNS FROM customers LIKE 'name'");
if ($check_name && $check_name->num_rows > 0) {
    $customers = $conn->query("SELECT id, name as display_name FROM customers ORDER BY name LIMIT 100");
    if ($customers) {
        while ($customer = $customers->fetch_assoc()) {
            $customers_array[$customer['id']] = $customer['display_name'];
        }
    }
} 
// المحاولة الثانية: البحث عن عمود fullname
else {
    $check_fullname = $conn->query("SHOW COLUMNS FROM customers LIKE 'fullname'");
    if ($check_fullname && $check_fullname->num_rows > 0) {
        $customers = $conn->query("SELECT id, fullname as display_name FROM customers ORDER BY fullname LIMIT 100");
        if ($customers) {
            while ($customer = $customers->fetch_assoc()) {
                $customers_array[$customer['id']] = $customer['display_name'];
            }
        }
    } 
    // المحاولة الثالثة: البحث عن عمود customer_name
    else {
        $check_customer_name = $conn->query("SHOW COLUMNS FROM customers LIKE 'customer_name'");
        if ($check_customer_name && $check_customer_name->num_rows > 0) {
            $customers = $conn->query("SELECT id, customer_name as display_name FROM customers ORDER BY customer_name LIMIT 100");
            if ($customers) {
                while ($customer = $customers->fetch_assoc()) {
                    $customers_array[$customer['id']] = $customer['display_name'];
                }
            }
        } 
        // المحاولة الرابعة: البحث عن عمود username
        else {
            $check_username = $conn->query("SHOW COLUMNS FROM customers LIKE 'username'");
            if ($check_username && $check_username->num_rows > 0) {
                $customers = $conn->query("SELECT id, username as display_name FROM customers ORDER BY username LIMIT 100");
                if ($customers) {
                    while ($customer = $customers->fetch_assoc()) {
                        $customers_array[$customer['id']] = $customer['display_name'];
                    }
                }
            } 
            // المحاولة الخامسة: البحث عن عمود email
            else {
                $check_email = $conn->query("SHOW COLUMNS FROM customers LIKE 'email'");
                if ($check_email && $check_email->num_rows > 0) {
                    $customers = $conn->query("SELECT id, email as display_name FROM customers ORDER BY email LIMIT 100");
                    if ($customers) {
                        while ($customer = $customers->fetch_assoc()) {
                            $customers_array[$customer['id']] = $customer['display_name'];
                        }
                    }
                }
                // إذا لم نجد أي عمود مناسب، نستخدم id فقط
                else {
                    $customers = $conn->query("SELECT id FROM customers ORDER BY id DESC LIMIT 100");
                    if ($customers) {
                        while ($customer = $customers->fetch_assoc()) {
                            $customers_array[$customer['id']] = 'عميل #' . $customer['id'];
                        }
                    }
                }
            }
        }
    }
}

// إحصائيات سريعة
$stats_query = "
    SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN is_active = 1 AND end_date >= NOW() THEN 1 ELSE 0 END) as active,
        SUM(CASE WHEN end_date < NOW() THEN 1 ELSE 0 END) as expired
    FROM direct_discounts
";
$stats_result = $conn->query($stats_query);
$stats = $stats_result ? $stats_result->fetch_assoc() : ['total' => 0, 'active' => 0, 'expired' => 0];

$page_title = 'إدارة التخفيضات';
include 'includes/header.php';
include 'includes/sidebar.php';
?>

<!-- ============================================ -->
<!-- التصميم الاحترافي المتجاوب -->
<!-- ============================================ -->

<style>
/* ===== متغيرات الألوان ===== */
:root {
    --primary: #F57C00;
    --primary-dark: #E65100;
    --primary-light: #FFB74D;
    --primary-soft: #FFF3E0;
    --success: #10b981;
    --danger: #ef4444;
    --warning: #f59e0b;
    --info: #3b82f6;
    --dark: #1f2937;
    --gray: #6b7280;
    --light: #f3f4f6;
    --white: #ffffff;
    --shadow-sm: 0 1px 2px 0 rgb(0 0 0 / 0.05);
    --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1);
    --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
}

/* ===== تنسيقات عامة ===== */
* {
    box-sizing: border-box;
}

.main-content {
    margin-right: 280px;
    padding: 24px;
    min-height: 100vh;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    transition: margin 0.3s ease;
}

/* ===== شريط التنقل العلوي ===== */
.top-bar {
    background: var(--white);
    border-radius: var(--radius-lg);
    padding: 16px 24px;
    margin-bottom: 24px;
    box-shadow: var(--shadow-sm);
    display: flex;
    align-items: center;
    justify-content: space-between;
    border: 1px solid rgba(0,0,0,0.05);
}

.page-title {
    display: flex;
    align-items: center;
    gap: 12px;
}

.page-title-icon {
    width: 48px;
    height: 48px;
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--white);
    font-size: 1.5rem;
    box-shadow: 0 4px 10px rgba(245,124,0,0.3);
}

.page-title h1 {
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--dark);
    margin: 0;
}

.page-title p {
    color: var(--gray);
    font-size: 0.875rem;
    margin: 4px 0 0;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.user-avatar {
    width: 45px;
    height: 45px;
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--white);
    font-size: 1.5rem;
}

.user-details {
    text-align: right;
}

.user-name {
    font-weight: 600;
    color: var(--dark);
    margin: 0;
}

.user-role {
    font-size: 0.75rem;
    color: var(--gray);
}

/* ===== بطاقات الإحصائيات ===== */
.stats-grid {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: var(--white);
    border-radius: var(--radius-lg);
    padding: 20px;
    box-shadow: var(--shadow-sm);
    display: flex;
    align-items: center;
    gap: 16px;
    transition: all 0.3s ease;
    border: 1px solid rgba(0,0,0,0.05);
}

.stat-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-lg);
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.8rem;
}

.stat-icon.total {
    background: linear-gradient(135deg, #3b82f6, #2563eb);
    color: white;
}

.stat-icon.active {
    background: linear-gradient(135deg, #10b981, #059669);
    color: white;
}

.stat-icon.expired {
    background: linear-gradient(135deg, #ef4444, #dc2626);
    color: white;
}

.stat-icon.used {
    background: linear-gradient(135deg, #8b5cf6, #7c3aed);
    color: white;
}

.stat-details h3 {
    font-size: 1.8rem;
    font-weight: 800;
    color: var(--dark);
    margin: 0;
    line-height: 1.2;
}

.stat-details p {
    color: var(--gray);
    margin: 4px 0 0;
    font-size: 0.875rem;
}

.stat-change {
    font-size: 0.75rem;
    color: var(--success);
    margin-top: 4px;
}

/* ===== تبويبات التخفيضات ===== */
.discounts-tabs {
    display: flex;
    gap: 8px;
    margin-bottom: 24px;
    flex-wrap: wrap;
}

.tab-btn {
    padding: 10px 20px;
    border: none;
    background: var(--white);
    border-radius: 30px;
    font-size: 0.9rem;
    font-weight: 500;
    color: var(--gray);
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: var(--shadow-sm);
    display: flex;
    align-items: center;
    gap: 8px;
}

.tab-btn i {
    font-size: 1rem;
}

.tab-btn:hover {
    background: var(--primary-soft);
    color: var(--primary);
}

.tab-btn.active {
    background: var(--primary);
    color: white;
}

/* ===== بطاقة التخفيض ===== */
.discount-card {
    background: var(--white);
    border-radius: var(--radius-lg);
    overflow: hidden;
    box-shadow: var(--shadow-sm);
    transition: all 0.3s ease;
    height: 100%;
    display: flex;
    flex-direction: column;
    border: 1px solid rgba(0,0,0,0.05);
}

.discount-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-lg);
}

.discount-header {
    padding: 20px;
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    position: relative;
}

.discount-header::after {
    content: '';
    position: absolute;
    bottom: -10px;
    right: 0;
    width: 100%;
    height: 20px;
    background: linear-gradient(135deg, transparent 50%, var(--primary-dark) 50%);
}

.discount-badge {
    position: absolute;
    top: 16px;
    left: 16px;
    background: rgba(255,255,255,0.2);
    backdrop-filter: blur(4px);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 4px;
}

.discount-badge i {
    font-size: 0.8rem;
}

.discount-badge.active {
    background: rgba(16, 185, 129, 0.9);
}

.discount-badge.expired {
    background: rgba(239, 68, 68, 0.9);
}

.discount-title {
    font-size: 1.2rem;
    font-weight: 700;
    margin: 0 0 8px;
    padding-left: 40px;
}

.discount-value-box {
    background: rgba(255,255,255,0.1);
    border-radius: var(--radius-md);
    padding: 15px;
    margin-top: 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.discount-amount {
    font-size: 2rem;
    font-weight: 800;
}

.discount-amount small {
    font-size: 1rem;
    font-weight: 400;
    opacity: 0.8;
}

.discount-type {
    background: rgba(255,255,255,0.2);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
}

.discount-body {
    padding: 20px;
    flex: 1;
}

.detail-row {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 8px 0;
    border-bottom: 1px solid #f1f5f9;
}

.detail-row:last-child {
    border-bottom: none;
}

.detail-icon {
    width: 32px;
    height: 32px;
    background: var(--primary-soft);
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: var(--primary);
    font-size: 1rem;
}

.detail-content {
    flex: 1;
}

.detail-label {
    font-size: 0.7rem;
    color: var(--gray);
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.detail-value {
    font-weight: 600;
    color: var(--dark);
    font-size: 0.95rem;
}

.target-chip {
    background: var(--primary-soft);
    color: var(--primary-dark);
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 500;
    display: inline-block;
}

.discount-footer {
    padding: 20px;
    background: #f8fafc;
    display: flex;
    gap: 10px;
    border-top: 1px solid #e2e8f0;
}

.discount-footer .btn {
    flex: 1;
    padding: 12px;
    border: none;
    border-radius: var(--radius-md);
    font-weight: 600;
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.btn-toggle {
    background: var(--primary);
    color: white;
}

.btn-toggle:hover {
    background: var(--primary-dark);
}

.btn-toggle.inactive {
    background: var(--success);
}

.btn-delete {
    background: white;
    color: var(--danger);
    border: 1px solid #fee2e2;
}

.btn-delete:hover {
    background: var(--danger);
    color: white;
}

/* ===== نموذج الإضافة ===== */
.add-section {
    background: var(--white);
    border-radius: var(--radius-lg);
    padding: 24px;
    box-shadow: var(--shadow-lg);
    margin-bottom: 30px;
    border: 1px solid rgba(0,0,0,0.05);
}

.section-header {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 24px;
}

.section-icon {
    width: 50px;
    height: 50px;
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 1.5rem;
}

.section-header h2 {
    font-size: 1.3rem;
    font-weight: 700;
    color: var(--dark);
    margin: 0;
}

.section-header p {
    color: var(--gray);
    margin: 4px 0 0;
    font-size: 0.875rem;
}

.form-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
}

.form-group {
    margin-bottom: 0;
}

.form-group.full-width {
    grid-column: span 2;
}

.form-label {
    display: block;
    font-size: 0.875rem;
    font-weight: 600;
    color: var(--dark);
    margin-bottom: 8px;
}

.form-label .required {
    color: var(--danger);
    margin-right: 4px;
}

.form-control {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e2e8f0;
    border-radius: var(--radius-md);
    font-size: 1rem;
    transition: all 0.2s ease;
    background: #f8fafc;
}

.form-control:focus {
    outline: none;
    border-color: var(--primary);
    background: var(--white);
    box-shadow: 0 0 0 4px rgba(245,124,0,0.1);
}

.form-control:hover {
    border-color: var(--primary-light);
}

.input-group {
    display: flex;
    align-items: center;
}

.input-group .form-control {
    flex: 1;
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
}

.input-group-text {
    padding: 12px 16px;
    background: var(--primary-soft);
    border: 2px solid #e2e8f0;
    border-left: none;
    border-radius: var(--radius-md);
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
    color: var(--primary-dark);
    font-weight: 600;
}

.form-check {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 0;
}

.form-check-input {
    width: 50px;
    height: 26px;
    background: #e2e8f0;
    border-radius: 30px;
    appearance: none;
    cursor: pointer;
    position: relative;
    transition: all 0.2s ease;
}

.form-check-input:checked {
    background: var(--primary);
}

.form-check-input::before {
    content: '';
    position: absolute;
    width: 22px;
    height: 22px;
    background: white;
    border-radius: 50%;
    top: 2px;
    right: 2px;
    transition: all 0.2s ease;
}

.form-check-input:checked::before {
    right: 26px;
}

.form-check-label {
    font-weight: 500;
    color: var(--dark);
}

.btn-submit {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
    color: white;
    border: none;
    padding: 16px;
    border-radius: var(--radius-md);
    font-weight: 700;
    font-size: 1rem;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
    width: 100%;
    margin-top: 20px;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(245,124,0,0.4);
}

.btn-submit i {
    font-size: 1.2rem;
}

/* ===== الحالة الفارغة ===== */
.empty-state {
    text-align: center;
    padding: 60px 20px;
    background: var(--white);
    border-radius: var(--radius-lg);
    box-shadow: var(--shadow-sm);
}

.empty-icon {
    width: 100px;
    height: 100px;
    background: var(--primary-soft);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 20px;
    font-size: 3rem;
    color: var(--primary);
}

.empty-state h3 {
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--dark);
    margin-bottom: 10px;
}

.empty-state p {
    color: var(--gray);
    margin-bottom: 20px;
}

.btn-create {
    background: var(--primary);
    color: white;
    border: none;
    padding: 14px 30px;
    border-radius: 30px;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.btn-create:hover {
    background: var(--primary-dark);
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(245,124,0,0.3);
}

/* ===== التجاوب مع الشاشات المختلفة ===== */
@media (max-width: 1200px) {
    .stats-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 992px) {
    .main-content {
        margin-right: 0;
        padding: 20px;
    }
    
    .form-grid {
        grid-template-columns: 1fr;
    }
    
    .form-group.full-width {
        grid-column: span 1;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 16px;
        padding-bottom: 90px;
    }
    
    .top-bar {
        flex-direction: column;
        align-items: flex-start;
        gap: 16px;
        padding: 16px;
    }
    
    .page-title-icon {
        width: 40px;
        height: 40px;
        font-size: 1.2rem;
    }
    
    .page-title h1 {
        font-size: 1.2rem;
    }
    
    .user-details {
        display: none;
    }
    
    .user-avatar {
        width: 40px;
        height: 40px;
    }
    
    .stats-grid {
        gap: 12px;
    }
    
    .stat-card {
        padding: 16px;
    }
    
    .stat-icon {
        width: 45px;
        height: 45px;
        font-size: 1.3rem;
    }
    
    .stat-details h3 {
        font-size: 1.3rem;
    }
    
    .discounts-tabs {
        overflow-x: auto;
        padding-bottom: 8px;
        flex-wrap: nowrap;
        -webkit-overflow-scrolling: touch;
    }
    
    .tab-btn {
        padding: 8px 16px;
        font-size: 0.85rem;
        white-space: nowrap;
    }
    
    .discount-header {
        padding: 16px;
    }
    
    .discount-value-box {
        padding: 12px;
    }
    
    .discount-amount {
        font-size: 1.6rem;
    }
    
    .discount-body {
        padding: 16px;
    }
    
    .discount-footer {
        padding: 16px;
    }
    
    .discount-footer .btn {
        padding: 10px;
        font-size: 0.85rem;
    }
    
    .add-section {
        padding: 20px;
    }
    
    .section-header {
        gap: 12px;
    }
    
    .section-icon {
        width: 40px;
        height: 40px;
        font-size: 1.2rem;
    }
    
    .section-header h2 {
        font-size: 1.1rem;
    }
    
    .form-control {
        padding: 10px 14px;
        font-size: 16px;
    }
    
    .btn-submit {
        padding: 14px;
    }
}

@media (max-width: 576px) {
    .stats-grid {
        grid-template-columns: 1fr;
    }
    
    .stat-card {
        padding: 12px;
    }
    
    .discount-footer {
        flex-direction: column;
    }
    
    .empty-state {
        padding: 40px 16px;
    }
    
    .empty-icon {
        width: 70px;
        height: 70px;
        font-size: 2rem;
    }
    
    .empty-state h3 {
        font-size: 1.2rem;
    }
}

/* ===== الأنيميشن ===== */
@keyframes slideIn {
    from {
        opacity: 0;
        transform: translateY(20px);
    }
    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.discount-card {
    animation: slideIn 0.3s ease forwards;
}

@keyframes pulse {
    0%, 100% {
        transform: scale(1);
    }
    50% {
        transform: scale(1.05);
    }
}

.stat-card:hover .stat-icon {
    animation: pulse 0.5s ease;
}

/* ===== تحسينات إضافية ===== */
.alert {
    padding: 16px;
    border-radius: var(--radius-md);
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
    animation: slideIn 0.3s ease;
}

.alert-success {
    background: #d1fae5;
    border-right: 4px solid var(--success);
    color: #065f46;
}

.alert-danger {
    background: #fee2e2;
    border-right: 4px solid var(--danger);
    color: #991b1b;
}

.alert i {
    font-size: 1.2rem;
}

/* تحسين التمرير */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f5f9;
}

::-webkit-scrollbar-thumb {
    background: var(--primary-light);
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: var(--primary);
}

/* تحسين الروابط */
a {
    text-decoration: none;
}

/* منع التحديد */
* {
    -webkit-tap-highlight-color: transparent;
}
</style>

<!-- ===== المحتوى الرئيسي ===== -->
<div class="main-content">
    <!-- الشريط العلوي -->
    <div class="top-bar">
        <div class="page-title">
            <div class="page-title-icon">
                <i class="bi bi-percent"></i>
            </div>
            <div>
                <h1>إدارة التخفيضات المباشرة</h1>
                <p>إنشاء وتفعيل وتنظيم العروض والتخفيضات</p>
            </div>
        </div>
        
        <div class="user-info">
            <div class="user-details">
                <div class="user-name"><?php echo htmlspecialchars($_SESSION['admin_name']); ?></div>
                <div class="user-role">مدير النظام</div>
            </div>
            <div class="user-avatar">
                <i class="bi bi-person-circle"></i>
            </div>
        </div>
    </div>

    <!-- رسائل التنبيه -->
    <?php if ($message): ?>
        <div class="alert alert-<?php echo $message_type; ?>">
            <i class="bi bi-<?php echo $message_type == 'success' ? 'check-circle' : 'exclamation-triangle'; ?>"></i>
            <?php echo $message; ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['success_message'])): ?>
        <div class="alert alert-success">
            <i class="bi bi-check-circle"></i>
            <?php echo $_SESSION['success_message']; ?>
        </div>
        <?php unset($_SESSION['success_message']); ?>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error_message'])): ?>
        <div class="alert alert-danger">
            <i class="bi bi-exclamation-triangle"></i>
            <?php echo $_SESSION['error_message']; ?>
        </div>
        <?php unset($_SESSION['error_message']); ?>
    <?php endif; ?>

    <!-- بطاقات الإحصائيات -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon total">
                <i class="bi bi-tag"></i>
            </div>
            <div class="stat-details">
                <h3><?php echo $stats['total'] ?? 0; ?></h3>
                <p>إجمالي التخفيضات</p>
                <div class="stat-change">
                    <i class="bi bi-arrow-up"></i> جميع العروض
                </div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon active">
                <i class="bi bi-check-circle"></i>
            </div>
            <div class="stat-details">
                <h3><?php echo $stats['active'] ?? 0; ?></h3>
                <p>تخفيضات نشطة</p>
                <div class="stat-change" style="color: var(--success);">
                    <i class="bi bi-lightning-charge"></i> سارية الآن
                </div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon expired">
                <i class="bi bi-clock-history"></i>
            </div>
            <div class="stat-details">
                <h3><?php echo $stats['expired'] ?? 0; ?></h3>
                <p>منتهية الصلاحية</p>
                <div class="stat-change" style="color: var(--danger);">
                    <i class="bi bi-calendar-x"></i> تحتاج مراجعة
                </div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon used">
                <i class="bi bi-graph-up"></i>
            </div>
            <div class="stat-details">
                <h3><?php echo $stats['total'] - $stats['expired']; ?></h3>
                <p>نسبة النشاط</p>
                <div class="stat-change">
                    <i class="bi bi-pie-chart"></i> 
                    <?php echo $stats['total'] > 0 ? round(($stats['active'] / $stats['total']) * 100) : 0; ?>%
                </div>
            </div>
        </div>
    </div>

    <!-- قسم إضافة تخفيض جديد -->
    <div class="add-section" id="addSection">
        <div class="section-header">
            <div class="section-icon">
                <i class="bi bi-plus-circle"></i>
            </div>
            <div>
                <h2>إضافة تخفيض جديد</h2>
                <p>أدخل تفاصيل التخفيض الجديد</p>
            </div>
        </div>

        <form method="POST" id="discountForm">
            <div class="form-grid">
                <div class="form-group full-width">
                    <label class="form-label">
                        <span class="required">*</span>
                        اسم التخفيض
                    </label>
                    <input type="text" class="form-control" name="discount_name" 
                           placeholder="مثال: خصم العيد الوطني" required>
                </div>

                <div class="form-group">
                    <label class="form-label">
                        <span class="required">*</span>
                        نوع التخفيض
                    </label>
                    <select class="form-control" id="discount_type" name="discount_type" required>
                        <option value="percentage">نسبة مئوية %</option>
                        <option value="fixed">مبلغ ثابت (ريال)</option>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label">
                        <span class="required">*</span>
                        القيمة
                    </label>
                    <div class="input-group">
                        <input type="number" step="0.01" class="form-control" id="discount_value" 
                               name="discount_value" required min="0.01" value="10">
                        <span class="input-group-text" id="value_suffix">%</span>
                    </div>
                </div>

                <div class="form-group full-width">
                    <label class="form-label">
                        <span class="required">*</span>
                        ينطبق على
                    </label>
                    <select class="form-control" id="target_type" name="target_type" required>
                        <option value="order">جميع الطلبات</option>
                        <option value="category">فئة محددة</option>
                        <option value="meal">وجبة محددة</option>
                        <option value="customer">عميل محدد</option>
                    </select>
                </div>

                <!-- حقول الهدف -->
                <div class="form-group full-width target-select" id="category_select" style="display: none;">
                    <label class="form-label">اختر الفئة</label>
                    <select class="form-control" id="category_id" name="target_id">
                        <option value="">-- اختر الفئة --</option>
                        <?php foreach ($categories_array as $id => $name): ?>
                            <option value="<?php echo $id; ?>"><?php echo htmlspecialchars($name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group full-width target-select" id="meal_select" style="display: none;">
                    <label class="form-label">اختر الوجبة</label>
                    <select class="form-control" id="meal_id" name="target_id">
                        <option value="">-- اختر الوجبة --</option>
                        <?php foreach ($meals_array as $id => $name): ?>
                            <option value="<?php echo $id; ?>"><?php echo htmlspecialchars($name); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group full-width target-select" id="customer_select" style="display: none;">
                    <label class="form-label">اختر العميل</label>
                    <select class="form-control" id="customer_id" name="target_id">
                        <option value="">-- اختر العميل --</option>
                        <?php if (!empty($customers_array)): ?>
                            <?php foreach ($customers_array as $id => $name): ?>
                                <option value="<?php echo $id; ?>"><?php echo htmlspecialchars($name); ?></option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label class="form-label">الحد الأدنى للطلب</label>
                    <div class="input-group">
                        <input type="number" step="0.01" class="form-control" 
                               name="min_order_amount" value="0" min="0">
                        <span class="input-group-text">ريال</span>
                    </div>
                </div>

                <div class="form-group">
                    <label class="form-label">تاريخ البدء</label>
                    <input type="datetime-local" class="form-control" id="start_date" 
                           name="start_date" required>
                </div>

                <div class="form-group">
                    <label class="form-label">تاريخ الانتهاء</label>
                    <input type="datetime-local" class="form-control" id="end_date" 
                           name="end_date" required>
                </div>

                <div class="form-group full-width">
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="is_active" 
                               id="is_active" checked>
                        <label class="form-check-label" for="is_active">
                            تفعيل التخفيض فور الإضافة
                        </label>
                    </div>
                </div>
            </div>

            <button type="submit" name="add_discount" class="btn-submit">
                <i class="bi bi-plus-circle"></i>
                إضافة التخفيض
            </button>
        </form>
    </div>

    <!-- تبويبات التخفيضات -->
    <div class="discounts-tabs">
        <button class="tab-btn active" onclick="filterDiscounts('all')">
            <i class="bi bi-grid-3x3-gap-fill"></i>
            الكل
        </button>
        <button class="tab-btn" onclick="filterDiscounts('active')">
            <i class="bi bi-check-circle"></i>
            نشط
        </button>
        <button class="tab-btn" onclick="filterDiscounts('expired')">
            <i class="bi bi-clock-history"></i>
            منتهي
        </button>
        <button class="tab-btn" onclick="filterDiscounts('inactive')">
            <i class="bi bi-pause-circle"></i>
            معطل
        </button>
    </div>

    <!-- قائمة التخفيضات -->
    <div class="row g-3" id="discountsContainer">
        <?php if ($discounts && $discounts->num_rows > 0): ?>
            <?php while ($discount = $discounts->fetch_assoc()): 
                $now = date('Y-m-d H:i:s');
                $is_expired = $discount['end_date'] < $now;
                
                // تحديد حالة التخفيض
                if (!$discount['is_active']) {
                    $status = 'inactive';
                    $status_text = 'معطل';
                    $badge_class = '';
                } elseif ($is_expired) {
                    $status = 'expired';
                    $status_text = 'منتهي';
                    $badge_class = 'expired';
                } else {
                    $status = 'active';
                    $status_text = 'نشط';
                    $badge_class = 'active';
                }
                
                // تحديد نص الهدف
                $target_text = '';
                switch ($discount['target_type']) {
                    case 'order':
                        $target_text = 'جميع الطلبات';
                        break;
                    case 'category':
                        $target_text = $categories_array[$discount['target_id']] ?? 'فئة غير معروفة';
                        break;
                    case 'meal':
                        $target_text = $meals_array[$discount['target_id']] ?? 'وجبة غير معروفة';
                        break;
                    case 'customer':
                        $target_text = $customers_array[$discount['target_id']] ?? 'عميل غير معروف';
                        break;
                }
            ?>
                <div class="col-md-6 col-xl-4 discount-item" data-status="<?php echo $status; ?>">
                    <div class="discount-card">
                        <div class="discount-header">
                            <span class="discount-badge <?php echo $badge_class; ?>">
                                <i class="bi bi-<?php 
                                    echo $status == 'active' ? 'lightning-charge' : 
                                        ($status == 'expired' ? 'clock' : 'pause'); 
                                ?>"></i>
                                <?php echo $status_text; ?>
                            </span>
                            <h3 class="discount-title"><?php echo htmlspecialchars($discount['discount_name']); ?></h3>
                            
                            <div class="discount-value-box">
                                <span class="discount-amount">
                                    <?php if ($discount['discount_type'] == 'percentage'): ?>
                                        <?php echo $discount['discount_value']; ?><small>%</small>
                                    <?php else: ?>
                                        <?php echo number_format($discount['discount_value']); ?><small>ريال</small>
                                    <?php endif; ?>
                                </span>
                                <span class="discount-type">
                                    <?php echo $discount['discount_type'] == 'percentage' ? 'نسبة' : 'مبلغ'; ?>
                                </span>
                            </div>
                        </div>

                        <div class="discount-body">
                            <div class="detail-row">
                                <div class="detail-icon">
                                    <i class="bi bi-bullseye"></i>
                                </div>
                                <div class="detail-content">
                                    <div class="detail-label">ينطبق على</div>
                                    <span class="target-chip">
                                        <i class="bi bi-<?php 
                                            echo $discount['target_type'] == 'order' ? 'cart' : 
                                                ($discount['target_type'] == 'category' ? 'tags' : 
                                                ($discount['target_type'] == 'meal' ? 'cup-straw' : 'person')); 
                                        ?>"></i>
                                        <?php echo $target_text; ?>
                                    </span>
                                </div>
                            </div>

                            <?php if ($discount['min_order_amount'] > 0): ?>
                            <div class="detail-row">
                                <div class="detail-icon">
                                    <i class="bi bi-cart-check"></i>
                                </div>
                                <div class="detail-content">
                                    <div class="detail-label">الحد الأدنى</div>
                                    <div class="detail-value"><?php echo number_format($discount['min_order_amount'], 2); ?> ريال</div>
                                </div>
                            </div>
                            <?php endif; ?>

                            <div class="detail-row">
                                <div class="detail-icon">
                                    <i class="bi bi-calendar"></i>
                                </div>
                                <div class="detail-content">
                                    <div class="detail-label">فترة الصلاحية</div>
                                    <div class="detail-value">
                                        <i class="bi bi-play-circle-fill text-success small"></i>
                                        <?php echo date('Y/m/d', strtotime($discount['start_date'])); ?>
                                        <br>
                                        <i class="bi bi-stop-circle-fill text-danger small"></i>
                                        <?php echo date('Y/m/d', strtotime($discount['end_date'])); ?>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="discount-footer">
                            <form method="POST" style="flex: 1;">
                                <input type="hidden" name="discount_id" value="<?php echo $discount['id']; ?>">
                                <input type="hidden" name="status" value="<?php echo $discount['is_active'] ? 0 : 1; ?>">
                                <button type="submit" name="toggle_status" 
                                        class="btn-toggle <?php echo !$discount['is_active'] ? 'inactive' : ''; ?>">
                                    <i class="bi bi-<?php echo $discount['is_active'] ? 'pause' : 'play'; ?>"></i>
                                    <?php echo $discount['is_active'] ? 'تعطيل' : 'تفعيل'; ?>
                                </button>
                            </form>
                            <form method="POST" style="flex: 1;" 
                                  onsubmit="return confirm('هل أنت متأكد من حذف هذا التخفيض؟');">
                                <input type="hidden" name="discount_id" value="<?php echo $discount['id']; ?>">
                                <button type="submit" name="delete_discount" class="btn-delete">
                                    <i class="bi bi-trash3"></i>
                                    حذف
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="col-12">
                <div class="empty-state">
                    <div class="empty-icon">
                        <i class="bi bi-percent"></i>
                    </div>
                    <h3>لا توجد تخفيضات</h3>
                    <p>قم بإضافة أول تخفيض الآن وابدأ في جذب المزيد من العملاء</p>
                    <button class="btn-create" onclick="scrollToForm()">
                        <i class="bi bi-plus-circle"></i>
                        إضافة تخفيض جديد
                    </button>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
// ============================================
// JavaScript المحسن
// ============================================

document.addEventListener('DOMContentLoaded', function() {
    'use strict';

    // ===== إدارة نوع التخفيض =====
    const discountType = document.getElementById('discount_type');
    const valueSuffix = document.getElementById('value_suffix');
    const valueInput = document.getElementById('discount_value');

    if (discountType) {
        discountType.addEventListener('change', function() {
            const isPercentage = this.value === 'percentage';
            valueSuffix.textContent = isPercentage ? '%' : 'ريال';
            
            if (isPercentage) {
                valueInput.max = 100;
                valueInput.step = '0.1';
                if (valueInput.value > 100) valueInput.value = 100;
            } else {
                valueInput.removeAttribute('max');
                valueInput.step = '0.01';
            }
        });
    }

    // ===== إدارة نطاق التخفيض =====
    const targetType = document.getElementById('target_type');
    
    if (targetType) {
        targetType.addEventListener('change', function() {
            // إخفاء كل الحقول
            document.querySelectorAll('.target-select').forEach(el => {
                el.style.display = 'none';
                const select = el.querySelector('select');
                if (select) select.required = false;
            });
            
            // إظهار الحقل المختار
            const targetId = this.value + '_select';
            const targetElement = document.getElementById(targetId);
            if (targetElement) {
                targetElement.style.display = 'block';
                const select = targetElement.querySelector('select');
                if (select) select.required = true;
            }
        });
    }

    // ===== تعيين التواريخ الافتراضية =====
    const now = new Date();
    const formatDate = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day}T${hours}:${minutes}`;
    };

    const startInput = document.getElementById('start_date');
    const endInput = document.getElementById('end_date');

    if (startInput) {
        startInput.value = formatDate(now);
    }

    if (endInput) {
        const endDate = new Date(now.getTime() + (30 * 24 * 60 * 60 * 1000));
        endInput.value = formatDate(endDate);
    }

    // ===== التحقق من صحة النموذج =====
    const discountForm = document.getElementById('discountForm');
    
    if (discountForm) {
        discountForm.addEventListener('submit', function(e) {
            const startDate = new Date(document.getElementById('start_date').value);
            const endDate = new Date(document.getElementById('end_date').value);
            
            if (endDate <= startDate) {
                e.preventDefault();
                showNotification('❌ تاريخ الانتهاء يجب أن يكون بعد تاريخ البدء', 'error');
                return false;
            }
            
            const discountValue = parseFloat(document.getElementById('discount_value').value);
            const discountType = document.getElementById('discount_type').value;
            
            if (discountType === 'percentage' && discountValue > 100) {
                e.preventDefault();
                showNotification('❌ النسبة المئوية لا يمكن أن تتجاوز 100%', 'error');
                return false;
            }
            
            if (discountValue <= 0) {
                e.preventDefault();
                showNotification('❌ قيمة التخفيض يجب أن تكون أكبر من صفر', 'error');
                return false;
            }
            
            const targetType = document.getElementById('target_type').value;
            if (targetType !== 'order') {
                const targetSelect = document.querySelector(`#${targetType}_select select`);
                if (!targetSelect || !targetSelect.value) {
                    e.preventDefault();
                    const targetName = targetType === 'category' ? 'الفئة' : 
                                      targetType === 'meal' ? 'الوجبة' : 'العميل';
                    showNotification(`❌ الرجاء اختيار ${targetName}`, 'error');
                    return false;
                }
            }
            
            return true;
        });
    }

    // ===== فلترة التخفيضات =====
    window.filterDiscounts = function(status) {
        const tabs = document.querySelectorAll('.tab-btn');
        const items = document.querySelectorAll('.discount-item');
        
        // تحديث التبويب النشط
        tabs.forEach(tab => {
            tab.classList.remove('active');
            if (tab.textContent.includes(status === 'all' ? 'الكل' : 
                status === 'active' ? 'نشط' : 
                status === 'expired' ? 'منتهي' : 'معطل')) {
                tab.classList.add('active');
            }
        });
        
        // فلترة العناصر
        items.forEach(item => {
            if (status === 'all' || item.dataset.status === status) {
                item.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
    };

    // ===== إشعارات مؤقتة =====
    function showNotification(message, type) {
        const notification = document.createElement('div');
        notification.className = `alert alert-${type === 'error' ? 'danger' : 'success'}`;
        notification.innerHTML = `
            <i class="bi bi-${type === 'error' ? 'exclamation-triangle' : 'check-circle'}"></i>
            ${message}
        `;
        notification.style.position = 'fixed';
        notification.style.top = '20px';
        notification.style.left = '50%';
        notification.style.transform = 'translateX(-50%)';
        notification.style.zIndex = '9999';
        notification.style.minWidth = '300px';
        notification.style.textAlign = 'center';
        
        document.body.appendChild(notification);
        
        setTimeout(() => {
            notification.remove();
        }, 3000);
    }

    // ===== التمرير للنموذج =====
    window.scrollToForm = function() {
        const addSection = document.getElementById('addSection');
        if (addSection) {
            addSection.scrollIntoView({ 
                behavior: 'smooth',
                block: 'start'
            });
            
            // إضافة تأثير وميض
            addSection.style.transition = 'box-shadow 0.3s ease';
            addSection.style.boxShadow = '0 0 0 4px rgba(245,124,0,0.3)';
            setTimeout(() => {
                addSection.style.boxShadow = '';
            }, 1000);
        }
    };

    // ===== تحسينات الجوال =====
    if (window.innerWidth <= 768) {
        // منع تكبير النموذج تلقائياً
        const formInputs = document.querySelectorAll('input, select, textarea');
        formInputs.forEach(input => {
            input.style.fontSize = '16px';
        });
        
        // إضافة تأثير لمس للأزرار
        const buttons = document.querySelectorAll('button');
        buttons.forEach(button => {
            button.addEventListener('touchstart', function() {
                this.style.opacity = '0.7';
            });
            button.addEventListener('touchend', function() {
                this.style.opacity = '';
            });
        });
    }
});

// ===== مراقبة القائمة الجانبية =====
document.addEventListener('DOMContentLoaded', function() {
    const sidebar = document.getElementById('sidebar');
    const menuToggle = document.getElementById('menuToggle');
    const mainContent = document.querySelector('.main-content');
    
    if (sidebar && menuToggle) {
        menuToggle.addEventListener('click', function() {
            document.body.classList.toggle('sidebar-open');
            if (document.body.classList.contains('sidebar-open')) {
                mainContent.style.opacity = '0.5';
                mainContent.style.pointerEvents = 'none';
            } else {
                mainContent.style.opacity = '';
                mainContent.style.pointerEvents = '';
            }
        });
        
        const closeButtons = document.querySelectorAll('.sidebar-close, #sidebarOverlay');
        closeButtons.forEach(btn => {
            btn.addEventListener('click', function() {
                document.body.classList.remove('sidebar-open');
                mainContent.style.opacity = '';
                mainContent.style.pointerEvents = '';
            });
        });
    }
});
</script>

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