<?php
// جلب الاستشارات النشطة
$consultations = [];
try {
    $check_table = $conn->query("SHOW TABLES LIKE 'consultations'");
    if ($check_table->rowCount() > 0) {
        $query = "SELECT * FROM consultations WHERE is_active = 1 ORDER BY order_position ASC, created_at DESC LIMIT 3";
        $stmt = $conn->prepare($query);
        $stmt->execute();
        $consultations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
} catch (Exception $e) {
    $consultations = [];
}
?>

<?php if (!empty($consultations)): ?>
<!-- Consultations Section -->
<section style="padding: 60px 0; background: linear-gradient(135deg, #fff9f5 0%, #ffebf0 100%);">
    <div class="container-pinterest">
        <div class="section-header" style="text-align: center; margin-bottom: 48px;">
            <h2 style="font-size: 32px; font-weight: 800; background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text; margin-bottom: 8px;">
                استشارات متخصصة
            </h2>
            <p style="color: #666; font-size: 15px; max-width: 500px; margin: 0 auto;">
                احجزي جلستك مع خبرائنا
            </p>
        </div>

        <!-- Consultations Carousel -->
        <div style="position: relative; max-width: 340px; margin: 0 auto;">
            <div id="consultationsCarousel" style="position: relative; min-height: 480px; overflow: hidden;">
                <style>
                    .consultation-card {
                        position: absolute;
                        width: 100%;
                        opacity: 0;
                        transform: scale(0.9) translateX(40px);
                        transition: all 0.6s cubic-bezier(0.34, 1.56, 0.64, 1);
                    }
                    .consultation-card.active {
                        opacity: 1;
                        transform: scale(1) translateX(0);
                        z-index: 2;
                    }
                    .consultation-card.prev {
                        opacity: 0;
                        transform: scale(0.9) translateX(-40px);
                    }
                </style>
            <?php foreach($consultations as $consultation): 
                $discount_percentage = 0;
                if ($consultation['discount_price'] && $consultation['price'] > 0) {
                    $discount_percentage = round((($consultation['price'] - $consultation['discount_price']) / $consultation['price']) * 100);
                }
                $final_price = $consultation['discount_price'] ?: $consultation['price'];
            ?>
            <?php $consultation_index = array_search($consultation, $consultations); ?>
            <div class="consultation-card <?php echo $consultation_index === 0 ? 'active' : ''; ?>" data-consultation-index="<?php echo $consultation_index; ?>" style="background: white; border-radius: 28px; overflow: hidden; box-shadow: 0 8px 32px rgba(229, 115, 147, 0.12); padding: 24px; border: 1px solid rgba(229, 115, 147, 0.08);"
                 onmouseover="this.style.transform='translateY(-6px)'; this.style.boxShadow='0 16px 48px rgba(229, 115, 147, 0.18)'"
                 onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 8px 32px rgba(229, 115, 147, 0.12)'">
                
                <!-- Header with badges -->
                <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 14px; flex-wrap: wrap; gap: 6px;">
                    <div style="display: flex; gap: 6px; flex-wrap: wrap;">
                        <?php if ($discount_percentage > 0): ?>
                        <div style="background: linear-gradient(135deg, #ff6b6b 0%, #ee5a6f 100%); color: white; padding: 4px 10px; border-radius: 16px; font-weight: 700; font-size: 11px; box-shadow: 0 2px 8px rgba(255, 107, 107, 0.25);">
                            خصم <?php echo $discount_percentage; ?>%
                        </div>
                        <?php endif; ?>
                        
                        <div style="background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); color: white; padding: 4px 10px; border-radius: 16px; font-weight: 700; font-size: 11px; box-shadow: 0 2px 8px rgba(229, 115, 147, 0.25); display: flex; align-items: center; gap: 4px;">
                            <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
                                <circle cx="12" cy="12" r="10"></circle>
                                <polyline points="12 6 12 12 16 14"></polyline>
                            </svg>
                            <?php echo $consultation['duration']; ?> دقيقة
                        </div>
                    </div>
                    
                    <div style="background: linear-gradient(135deg, rgba(255, 212, 196, 0.5) 0%, rgba(255, 196, 214, 0.5) 100%); padding: 4px 10px; border-radius: 14px; display: flex; align-items: center; gap: 3px; box-shadow: 0 2px 6px rgba(229, 115, 147, 0.15); border: 1px solid rgba(229, 115, 147, 0.2);">
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="#fbbf24" stroke="#fbbf24">
                            <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
                        </svg>
                        <span style="font-weight: 700; font-size: 11px; color: #D1537A;">4.8</span>
                    </div>
                </div>
                
                <!-- Doctor Image (Circular Profile) -->
                <div style="display: flex; justify-content: center; margin-bottom: 14px;">
                    <div style="position: relative; width: 140px; height: 140px; border-radius: 50%; background: linear-gradient(135deg, #E57393 0%, #f4a582 100%); display: flex; align-items: center; justify-content: center; overflow: hidden; box-shadow: 0 4px 16px rgba(229, 115, 147, 0.25); border: 4px solid white;">
                        <?php if ($consultation['image']): ?>
                            <img src="../<?php echo htmlspecialchars($consultation['image']); ?>" 
                                 alt="<?php echo htmlspecialchars($consultation['title']); ?>"
                                 style="width: 100%; height: 100%; object-fit: cover;">
                        <?php else: ?>
                            <div style="font-size: 56px;">👨‍⚕️</div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Consultant Info -->
                <div style="margin-bottom: 14px;">
                    <h3 style="font-size: 17px; font-weight: 800; color: #1f2937; margin-bottom: 4px; line-height: 1.3;">
                        <?php echo htmlspecialchars($consultation['consultant_name'] ?: 'استشاري متخصص'); ?>
                    </h3>
                    <?php if ($consultation['consultant_title']): ?>
                    <p style="color: #6b7280; font-size: 12px; font-weight: 500; margin-bottom: 8px;">
                        <?php echo htmlspecialchars($consultation['consultant_title']); ?>
                    </p>
                    <?php endif; ?>
                    
                    <h4 style="font-size: 14px; font-weight: 700; color: #374151; margin-bottom: 6px;">
                        <?php echo htmlspecialchars($consultation['title']); ?>
                    </h4>
                    <p style="color: #9ca3af; font-size: 11px; line-height: 1.5; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;">
                        <?php echo htmlspecialchars($consultation['description']); ?>
                    </p>
                </div>
                

                
                <!-- Price & Book Button -->
                <div style="background: rgba(255,255,255,0.95); padding: 12px; border-radius: 16px; display: flex; align-items: center; justify-content: space-between; box-shadow: 0 2px 8px rgba(229, 115, 147, 0.1);">
                    <div>
                        <?php if ($consultation['discount_price']): ?>
                        <div style="text-decoration: line-through; color: #9ca3af; font-size: 10px; margin-bottom: 1px;">
                            <?php echo number_format($consultation['price'], 0); ?> <?php echo $currency_symbol; ?>
                        </div>
                        <?php endif; ?>
                        <div style="font-size: 19px; font-weight: 800; color: #E57393;">
                            ~<?php echo number_format($final_price, 0); ?>
                        </div>
                        <div style="font-size: 9px; color: #9ca3af;">لكل جلسة</div>
                    </div>
                    
                    <button onclick="showConsultationBooking(<?php echo $consultation['id']; ?>, '<?php echo addslashes($consultation['title']); ?>', <?php echo $final_price; ?>)" 
                            style="background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); color: white; border: none; padding: 10px 18px; border-radius: 14px; font-size: 13px; font-weight: 700; cursor: pointer; transition: all 0.3s; box-shadow: 0 3px 12px rgba(229, 115, 147, 0.3);"
                            onmouseover="this.style.transform='scale(1.05)'; this.style.boxShadow='0 5px 18px rgba(229, 115, 147, 0.4)'"
                            onmouseout="this.style.transform='scale(1)'; this.style.boxShadow='0 3px 12px rgba(229, 115, 147, 0.3)'">
                        احجزي
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="display: inline-block; margin-right: 4px; vertical-align: middle;">
                            <path d="M5 12h14M12 5l7 7-7 7"/>
                        </svg>
                    </button>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
        
        <!-- Carousel Indicators -->
        <div style="text-align: center; margin-top: 20px;">
            <div id="consultationsIndicators" style="display: inline-flex; gap: 8px;"></div>
        </div>
        </div>
    </div>
</section>

<script>
// Consultations Carousel Auto-Rotate (1 card at a time, every 2 seconds)
let currentConsultationIndex = 0;
const consultationCards = document.querySelectorAll('.consultation-card');
const totalConsultations = consultationCards.length;

function showConsultationCard(index) {
    consultationCards.forEach((card, i) => {
        card.classList.remove('active', 'prev');
        if (i === index) {
            card.classList.add('active');
        } else if (i === (index - 1 + totalConsultations) % totalConsultations) {
            card.classList.add('prev');
        }
    });
    
    // Update indicators
    updateConsultationsIndicators();
}

function updateConsultationsIndicators() {
    const indicatorsContainer = document.getElementById('consultationsIndicators');
    if (!indicatorsContainer) return;
    
    let html = '';
    for (let i = 0; i < totalConsultations; i++) {
        const isActive = i === currentConsultationIndex;
        html += `<div style="width: ${isActive ? '24px' : '8px'}; height: 8px; background: ${isActive ? '#E57393' : 'rgba(229, 115, 147, 0.3)'}; border-radius: 4px; transition: all 0.3s; cursor: pointer;" onclick="goToConsultationCard(${i})"></div>`;
    }
    indicatorsContainer.innerHTML = html;
}

function nextConsultationCard() {
    currentConsultationIndex = (currentConsultationIndex + 1) % totalConsultations;
    showConsultationCard(currentConsultationIndex);
}

function goToConsultationCard(index) {
    currentConsultationIndex = index;
    showConsultationCard(currentConsultationIndex);
}

// Auto-rotate every 2 seconds
if (totalConsultations > 1) {
    setInterval(nextConsultationCard, 2000);
    updateConsultationsIndicators();
}
</script>

<script>
function showConsultationBooking(id, title, price) {
    <?php if (!isset($_SESSION['user_id'])): ?>
        alert('يجب تسجيل الدخول أولاً للحجز');
        window.location.href = 'account.php';
        return;
    <?php endif; ?>
    
    // Show booking modal
    document.getElementById('bookingConsultationId').value = id;
    document.getElementById('bookingConsultationTitle').textContent = title;
    document.getElementById('bookingConsultationPrice').textContent = price;
    document.getElementById('consultationBookingModal').style.display = 'flex';
}

function closeConsultationBooking() {
    document.getElementById('consultationBookingModal').style.display = 'none';
    document.getElementById('consultationBookingForm').reset();
}
</script>

<!-- Consultation Booking Modal -->
<div id="consultationBookingModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6); backdrop-filter: blur(8px); z-index: 99999; align-items: center; justify-content: center;">
    <div style="background: linear-gradient(135deg, #f0f4f8 0%, #ffffff 100%); border-radius: 28px; max-width: 480px; width: 90%; max-height: 90vh; overflow-y: auto; box-shadow: 0 20px 60px rgba(0,0,0,0.3); position: relative; padding: 32px;">
        
        <!-- Close Button -->
        <button onclick="closeConsultationBooking()" style="position: absolute; top: 16px; left: 16px; background: rgba(0,0,0,0.05); border: none; width: 36px; height: 36px; border-radius: 50%; cursor: pointer; display: flex; align-items: center; justify-content: center; transition: all 0.3s; color: #666; font-size: 24px;" onmouseover="this.style.background='rgba(0,0,0,0.1)'" onmouseout="this.style.background='rgba(0,0,0,0.05)'">
            ×
        </button>
        
        <!-- Header -->
        <div style="text-align: center; margin-bottom: 28px;">
            <div style="width: 80px; height: 80px; background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 16px; box-shadow: 0 8px 24px rgba(229, 115, 147, 0.3);">
                <svg width="40" height="40" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
                    <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
                    <line x1="16" y1="2" x2="16" y2="6"></line>
                    <line x1="8" y1="2" x2="8" y2="6"></line>
                    <line x1="3" y1="10" x2="21" y2="10"></line>
                </svg>
            </div>
            <h3 style="font-size: 24px; font-weight: 800; color: #1f2937; margin-bottom: 8px;">احجزي موعدك</h3>
            <p style="font-size: 14px; color: #6b7280;" id="bookingConsultationTitle">استشارة متخصصة</p>
        </div>
        
        <form id="consultationBookingForm" onsubmit="submitConsultationBooking(event)">
            <input type="hidden" id="bookingConsultationId" name="consultation_id">
            
            <!-- Select Date -->
            <div style="margin-bottom: 20px;">
                <label style="display: block; font-size: 13px; font-weight: 700; color: #374151; margin-bottom: 8px;">اختاري التاريخ</label>
                <div style="background: white; padding: 16px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;">
                        <button type="button" onclick="changeMonth(-1)" style="background: none; border: none; color: #0f766e; font-size: 20px; cursor: pointer;">‹</button>
                        <span style="font-weight: 700; color: #1f2937;" id="currentMonth">يناير 2025</span>
                        <button type="button" onclick="changeMonth(1)" style="background: none; border: none; color: #0f766e; font-size: 20px; cursor: pointer;">›</button>
                    </div>
                    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px;" id="dateGrid">
                        <!-- Dates will be generated by JS -->
                    </div>
                </div>
            </div>
            
            <!-- Select Time -->
            <div style="margin-bottom: 20px;">
                <label style="display: block; font-size: 13px; font-weight: 700; color: #374151; margin-bottom: 8px;">اختاري الوقت</label>
                <div style="background: white; padding: 16px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.06);">
                    <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px;" id="timeGrid">
                        <!-- Times will be generated by JS -->
                    </div>
                </div>
            </div>
            
            <!-- Notes -->
            <div style="margin-bottom: 24px;">
                <label style="display: block; font-size: 13px; font-weight: 700; color: #374151; margin-bottom: 8px;">ملاحظات (اختياري)</label>
                <textarea name="notes" rows="3" style="width: 100%; padding: 12px; border: 2px solid #e5e7eb; border-radius: 12px; font-size: 14px; resize: none;" placeholder="أي ملاحظات أو استفسارات..."></textarea>
            </div>
            
            <!-- Price & Submit -->
            <div style="background: rgba(229, 115, 147, 0.1); padding: 16px; border-radius: 16px; margin-bottom: 20px;">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="font-size: 14px; color: #6b7280;">السعر الإجمالي</span>
                    <span style="font-size: 24px; font-weight: 800; color: #E57393;"><span id="bookingConsultationPrice">0</span> ج.م</span>
                </div>
            </div>
            
            <button type="submit" style="width: 100%; background: linear-gradient(135deg, #E57393 0%, #D1537A 100%); color: white; border: none; padding: 16px; border-radius: 16px; font-size: 16px; font-weight: 700; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 16px rgba(229, 115, 147, 0.3);" onmouseover="this.style.transform='translateY(-2px)'; this.style.boxShadow='0 6px 24px rgba(229, 115, 147, 0.4)'" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 4px 16px rgba(229, 115, 147, 0.3)'">
                تأكيد الحجز
            </button>
        </form>
    </div>
</div>

<script>
// Generate dates for next 14 days
function generateDates() {
    const dateGrid = document.getElementById('dateGrid');
    const today = new Date();
    let html = '';
    
    for (let i = 0; i < 14; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        const dayNum = date.getDate();
        const dayName = ['الأحد', 'الإثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'][date.getDay()];
        const dateStr = date.toISOString().split('T')[0]; // YYYY-MM-DD format
        
        html += `<div onclick="selectDate(this, '${dateStr}')" data-date="${dateStr}" style="background: ${i === 0 ? '#a8d5e2' : '#f3f4f6'}; padding: 12px 8px; border-radius: 12px; text-align: center; cursor: pointer; transition: all 0.3s;" class="date-option">
            <div style="font-size: 18px; font-weight: 700; color: #1f2937;">${dayNum}</div>
            <div style="font-size: 10px; color: #6b7280;">${dayName}</div>
        </div>`;
    }
    
    dateGrid.innerHTML = html;
}

// Generate time slots
function generateTimes() {
    const timeGrid = document.getElementById('timeGrid');
    const times = ['7:30', '8:00', '8:30', '9:00', '9:30', '10:00', '10:30', '11:00'];
    let html = '';
    
    times.forEach((time, i) => {
        html += `<div onclick="selectTime(this, '${time}')" data-time="${time}:00" style="background: ${i === 2 ? '#a8d5e2' : '#f3f4f6'}; padding: 10px; border-radius: 10px; text-align: center; cursor: pointer; transition: all 0.3s; font-size: 13px; font-weight: 600; color: #1f2937;" class="time-option">${time}</div>`;
    });
    
    timeGrid.innerHTML = html;
}

function selectDate(element, date) {
    document.querySelectorAll('.date-option').forEach(el => el.style.background = '#f3f4f6');
    element.style.background = '#a8d5e2';
    element.dataset.date = date;
}

function selectTime(element, time) {
    document.querySelectorAll('.time-option').forEach(el => el.style.background = '#f3f4f6');
    element.style.background = '#a8d5e2';
    element.dataset.time = time;
}

function submitConsultationBooking(e) {
    e.preventDefault();
    
    const consultationId = document.getElementById('bookingConsultationId').value;
    const notes = document.querySelector('textarea[name="notes"]').value;
    
    // Get selected date
    const selectedDate = document.querySelector('.date-option[style*="rgb(168, 213, 226)"]');
    if (!selectedDate) {
        alert('❌ الرجاء اختيار التاريخ');
        return;
    }
    const bookingDate = selectedDate.dataset.date;
    
    // Get selected time
    const selectedTime = document.querySelector('.time-option[style*="rgb(168, 213, 226)"]');
    if (!selectedTime) {
        alert('❌ الرجاء اختيار الوقت');
        return;
    }
    const bookingTime = selectedTime.dataset.time;
    
    // Send booking request
    fetch('../api/consultation-booking.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            consultation_id: consultationId,
            booking_date: bookingDate,
            booking_time: bookingTime,
            notes: notes
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('✅ ' + data.message + '\n\nسيتم التواصل معك قريباً.');
            closeConsultationBooking();
        } else {
            alert('❌ ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('❌ حدث خطأ أثناء الحجز');
    });
}

// Initialize on modal open
document.getElementById('consultationBookingModal').addEventListener('click', function(e) {
    if (e.target === this) closeConsultationBooking();
});

// Generate dates and times when page loads
if (document.getElementById('dateGrid')) {
    generateDates();
    generateTimes();
}
</script>
<?php endif; ?>
