<?php
/**
 * صفحة تفاصيل الخدمة - Roz Skin
 */

session_start();
require_once '../includes/product-card.php';
require_once '../config/database.php';

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

// جلب ID الخدمة
$service_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($service_id <= 0) {
    header('Location: services.php');
    exit;
}

// جلب تفاصيل الخدمة
try {
    $stmt = $db->prepare("
        SELECT * FROM beauty_services 
        WHERE id = ? AND is_active = 1
    ");
    $stmt->execute([$service_id]);
    $service = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$service) {
        header('Location: services.php');
        exit;
    }
} catch (PDOException $e) {
    header('Location: services.php');
    exit;
}

// جلب إعدادات الموقع
try {
    $query = "SELECT setting_key, setting_value FROM settings 
              WHERE setting_key IN ('site_name', 'logo_text', 'default_currency')";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    $site_name = $settings['site_name'] ?? 'Roz Skin';
    $logo_text = $settings['logo_text'] ?? 'Roz Skin';
    $currency = $settings['default_currency'] ?? 'EGP';
} catch (PDOException $e) {
    $site_name = 'Roz Skin';
    $logo_text = 'Roz Skin';
    $currency = 'EGP';
}

$currency_symbols = ['EGP' => 'ج.م', 'USD' => '$', 'EUR' => '€', 'AED' => 'د.إ'];
$currency_symbol = $currency_symbols[$currency] ?? 'ج.م';

$serviceImage = !empty($service['image']) && file_exists('../uploads/services/' . $service['image']) 
    ? '../uploads/services/' . htmlspecialchars($service['image']) 
    : 'https://images.unsplash.com/photo-1540555700478-4be289fbecef?w=1200&h=600&fit=crop';
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($service['name']); ?> - <?php echo htmlspecialchars($site_name); ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/css/pinterest-style.css">
    
    <style>
        .service-hero {
            position: relative;
            height: 400px;
            background: linear-gradient(135deg, rgba(229, 115, 147, 0.9) 0%, rgba(209, 83, 122, 0.9) 100%),
                        url('<?php echo $serviceImage; ?>') center/cover;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            text-align: center;
            margin-top: 80px;
        }
        
        .service-content {
            max-width: 900px;
            margin: -80px auto 0;
            position: relative;
            z-index: 2;
            padding: 0 var(--space-md);
        }
        
        .service-card {
            background: white;
            border-radius: var(--radius-xl);
            box-shadow: var(--shadow-lg);
            padding: var(--space-2xl);
        }
        
        .service-price {
            font-size: 48px;
            font-weight: 700;
            color: var(--primary);
            margin: var(--space-lg) 0;
        }
        
        .service-features {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: var(--space-md);
            margin: var(--space-xl) 0;
        }
        
        .feature-item {
            display: flex;
            align-items: center;
            gap: var(--space-sm);
            padding: var(--space-md);
            background: var(--bg-secondary);
            border-radius: var(--radius-md);
        }
    </style>
    <link rel="stylesheet" href="../assets/css/product-cards.css">
</head>
<body>
    <!-- Navigation -->
    <nav class="nav-pinterest">
        <div class="container-pinterest">
            <div class="nav-content">
                <a href="index.php" class="nav-logo"><?php echo htmlspecialchars($logo_text); ?></a>
                <div class="nav-actions">
                    <button class="nav-icon-btn" onclick="history.back()" title="رجوع">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                            <line x1="19" y1="12" x2="5" y2="12"></line>
                            <polyline points="12 19 5 12 12 5"></polyline>
                        </svg>
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- Hero -->
    <div class="service-hero">
        <div>
            <h1 style="font-size: clamp(32px, 5vw, 56px); font-weight: 700; margin-bottom: 16px;">
                <?php echo htmlspecialchars($service['name']); ?>
            </h1>
            <?php if (!empty($service['category'])): ?>
            <p style="font-size: 18px; opacity: 0.95;">
                <?php echo htmlspecialchars($service['category']); ?>
            </p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Content -->
    <section style="padding: var(--space-2xl) 0;">
        <div class="service-content">
            <div class="service-card">
                <div class="service-price">
                    <?php echo number_format($service['price'], 0); ?> <?php echo $currency_symbol; ?>
                </div>
                
                <div class="service-features">
                    <?php if (!empty($service['duration'])): ?>
                    <div class="feature-item">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                            <circle cx="12" cy="12" r="10"></circle>
                            <polyline points="12 6 12 12 16 14"></polyline>
                        </svg>
                        <div>
                            <div style="font-weight: 600;">المدة</div>
                            <div style="color: var(--text-secondary); font-size: 14px;"><?php echo $service['duration']; ?> دقيقة</div>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="feature-item">
                        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#E57393" stroke-width="2">
                            <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path>
                            <polyline points="22 4 12 14.01 9 11.01"></polyline>
                        </svg>
                        <div>
                            <div style="font-weight: 600;">جودة مضمونة</div>
                            <div style="color: var(--text-secondary); font-size: 14px;">خدمة احترافية</div>
                        </div>
                    </div>
                </div>
                
                <div style="margin: var(--space-xl) 0;">
                    <h3 style="font-size: 24px; font-weight: 700; margin-bottom: var(--space-md);">وصف الخدمة</h3>
                    <p style="color: var(--text-secondary); line-height: 1.8; font-size: 16px;">
                        <?php echo nl2br(htmlspecialchars($service['description'] ?: 'خدمة متميزة لعناية فائقة بجمالك')); ?>
                    </p>
                </div>
                
                <?php if (!empty($service['usage_instructions'])): ?>
                <div style="margin: var(--space-xl) 0; padding: var(--space-lg); background: var(--bg-secondary); border-radius: var(--radius-lg);">
                    <h3 style="font-size: 20px; font-weight: 700; margin-bottom: var(--space-md);">تعليمات الاستخدام</h3>
                    <p style="color: var(--text-secondary); line-height: 1.8;">
                        <?php echo nl2br(htmlspecialchars($service['usage_instructions'])); ?>
                    </p>
                </div>
                <?php endif; ?>
                
                <button class="btn-primary" 
                        style="width: 100%; justify-content: center; padding: 18px 32px; font-size: 18px; margin-top: var(--space-xl);" 
                        onclick="showBookingModal(<?php echo $service['id']; ?>, '<?php echo addslashes($service['name']); ?>')">
                    احجزي موعدك الآن
                </button>
            </div>
        </div>
    </section>

    <!-- Booking Modal -->
    <div id="bookingModal" class="modal-overlay hidden" onclick="if(event.target === this) closeBookingModal()">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="bookingServiceName">حجز موعد</h3>
                <button class="modal-close" onclick="closeBookingModal()">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                        <line x1="18" y1="6" x2="6" y2="18"></line>
                        <line x1="6" y1="6" x2="18" y2="18"></line>
                    </svg>
                </button>
            </div>
            <div class="modal-body">
                <form id="bookingForm" onsubmit="handleBooking(event)">
                    <input type="hidden" id="serviceId" name="service_id">
                    
                    <div class="form-group">
                        <label class="form-label">اختر التاريخ</label>
                        <input type="date" name="appointment_date" class="form-input" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">اختر الوقت</label>
                        <select name="appointment_time" class="form-input" required>
                            <option value="">اختر الوقت</option>
                            <option value="09:00">9:00 صباحاً</option>
                            <option value="10:00">10:00 صباحاً</option>
                            <option value="11:00">11:00 صباحاً</option>
                            <option value="12:00">12:00 ظهراً</option>
                            <option value="13:00">1:00 مساءً</option>
                            <option value="14:00">2:00 مساءً</option>
                            <option value="15:00">3:00 مساءً</option>
                            <option value="16:00">4:00 مساءً</option>
                            <option value="17:00">5:00 مساءً</option>
                            <option value="18:00">6:00 مساءً</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">ملاحظات (اختياري)</label>
                        <textarea name="notes" class="form-input" rows="3" placeholder="أي ملاحظات خاصة..."></textarea>
                    </div>
                    
                    <button type="submit" class="btn-primary" style="width: 100%; justify-content: center;">
                        تأكيد الحجز
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div id="toast" class="toast-notification hidden"></div>

    <script>
        function showToast(message) {
            const toast = document.getElementById('toast');
            toast.textContent = message;
            toast.classList.remove('hidden');
            setTimeout(() => toast.classList.add('hidden'), 3000);
        }

        function showBookingModal(serviceId, serviceName) {
            <?php if (!isset($_SESSION['user_id'])): ?>
                showToast('يجب تسجيل الدخول أولاً');
                setTimeout(() => window.location.href = 'login.php', 1000);
                return;
            <?php endif; ?>
            
            document.getElementById('serviceId').value = serviceId;
            document.getElementById('bookingServiceName').textContent = serviceName;
            document.getElementById('bookingModal').classList.remove('hidden');
        }

        function closeBookingModal() {
            document.getElementById('bookingModal').classList.add('hidden');
            document.getElementById('bookingForm').reset();
        }

        function handleBooking(event) {
            event.preventDefault();
            const formData = new FormData(event.target);
            const submitBtn = event.target.querySelector('button[type="submit"]');
            const originalText = submitBtn.textContent;
            
            submitBtn.textContent = 'جاري الحجز...';
            submitBtn.disabled = true;

            fetch('../api/bookings/create.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('تم الحجز بنجاح! ✓');
                    closeBookingModal();
                } else {
                    showToast(data.message || 'حدث خطأ في الحجز');
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;
                }
            })
            .catch(() => {
                showToast('حدث خطأ، حاول مرة أخرى');
                submitBtn.textContent = originalText;
                submitBtn.disabled = false;
            });
        }
    </script>
</body>
</html>
