<?php
require_once __DIR__ . '/api/lib.php';
hw_require_auth(['client']);
$authUser = hw_get_auth_user();

$page_title = 'Book Appointment | Herbal Wellness Care';
$page_description = 'Schedule your consultation with our wellness guardians';
$page_content = function () use ($authUser) {
    $coachName = $_GET['coach'] ?? null;
    if (!$coachName) {
        header('Location: /atasteofafricanmarketplace/all-coaches.php');
        exit;
    }
    
    // Get actual coach data from database
    $db = hw_db();
    $stmt = $db->prepare("SELECT * FROM coaches WHERE display_name LIKE ? LIMIT 1");
    $stmt->execute(['%' . $coachName . '%']);
    $coach = $stmt->fetch();
    
    // If no exact match, try to find any coach for testing
    if (!$coach) {
        $stmt = $db->prepare("SELECT * FROM coaches WHERE id > 0 LIMIT 1");
        $stmt->execute();
        $coach = $stmt->fetch();
    }
    
    if (!$coach) {
        header('Location: /atasteofafricanmarketplace/all-coaches.php');
        exit;
    }
?>

<style>
    .booking-container {
        max-width: 1000px;
        margin: 80px auto;
        padding: 0 24px;
    }
    .booking-header {
        text-align: center;
        margin-bottom: 48px;
    }
    .booking-header h1 {
        font-size: 36px;
        font-weight: 800;
        color: #0b3d2e;
        margin-bottom: 12px;
    }
    .booking-header p {
        font-size: 18px;
        color: #64748b;
    }
    .booking-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 48px;
    }
    @media (max-width: 768px) {
        .booking-grid {
            grid-template-columns: 1fr;
            gap: 32px;
        }
    }
    .coach-card {
        background: linear-gradient(135deg, #f0f9f6, #fef9e7);
        padding: 32px;
        border-radius: 16px;
        border: 2px solid #d4ad31;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    }
    .coach-header {
        display: flex;
        align-items: center;
        gap: 16px;
        margin-bottom: 24px;
    }
    .coach-avatar {
        width: 80px;
        height: 80px;
        border-radius: 12px;
        object-fit: cover;
        border: 3px solid #d4ad31;
    }
    .coach-name {
        font-size: 24px;
        font-weight: 800;
        color: #0b3d2e;
        margin: 0;
    }
    .coach-title {
        color: #64748b;
        font-size: 14px;
        margin: 4px 0;
    }
    .coach-rate {
        color: #0f5240;
        font-weight: 700;
        font-size: 18px;
    }
    .coach-bio {
        color: #334155;
        font-style: italic;
        line-height: 1.6;
        padding: 16px;
        background: white;
        border-radius: 8px;
        border-left: 4px solid #0f5240;
    }
    .booking-form {
        background: white;
        padding: 32px;
        border-radius: 16px;
        border: 1px solid #e5e7eb;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    }
    .form-group {
        margin-bottom: 24px;
    }
    .form-label {
        display: block;
        font-size: 14px;
        font-weight: 600;
        color: #0b3d2e;
        margin-bottom: 8px;
    }
    .form-input {
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        font-size: 14px;
        transition: all 0.3s;
    }
    .form-input:focus {
        outline: none;
        border-color: #0f5240;
        box-shadow: 0 0 0 3px rgba(15, 82, 64, 0.1);
    }
    .time-slots-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 8px;
        margin-top: 8px;
    }
    .time-slot-btn {
        padding: 12px;
        border: 2px solid #e5e7eb;
        border-radius: 8px;
        background: white;
        cursor: pointer;
        font-size: 13px;
        font-weight: 600;
        color: #334155;
        transition: all 0.3s;
    }
    .time-slot-btn:hover {
        border-color: #0f5240;
        background: #f0f9f6;
    }
    .time-slot-btn.selected {
        border-color: #0f5240;
        background: #f0f9f6;
        color: #0f5240;
    }
    .submit-btn {
        width: 100%;
        background: linear-gradient(135deg, #10b981, #059669);
        color: white;
        padding: 16px 24px;
        border: none;
        border-radius: 12px;
        font-size: 16px;
        font-weight: 700;
        cursor: pointer;
        box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
        transition: all 0.3s;
    }
    .submit-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(16, 185, 129, 0.4);
    }
</style>

<div class="booking-container">
    <div class="booking-header">
        <h1>Book Your Session</h1>
        <p>Schedule your consultation with <?= htmlspecialchars($coach['display_name']) ?></p>
    </div>

    <div class="booking-grid">
        <!-- Coach Info -->
        <div class="coach-card">
            <div class="coach-header">
                <img src="<?= $coach['profile_image_url'] ?: 'https://i.pravatar.cc/300?u=' . urlencode($coach['display_name']) ?>" class="coach-avatar" alt="<?= htmlspecialchars($coach['display_name']) ?>">
                <div>
                    <h3 class="coach-name"><?= htmlspecialchars($coach['display_name']) ?></h3>
                    <p class="coach-title"><?= htmlspecialchars($coach['bio'] ?: 'Wellness Coach') ?></p>
                    <p class="coach-rate">$<?= number_format($coach['hourly_rate'] ?: 85, 0) ?>/hour</p>
                </div>
            </div>
            <div class="coach-bio">"<?= htmlspecialchars($coach['bio'] ?: 'Professional wellness coach ready to guide your journey.') ?>"</div>
        </div>

        <!-- Booking Form -->
        <div class="booking-form">
            <form id="booking-form">
                <input type="hidden" name="coach_id" value="<?= $coach['id'] ?>">
                
                <div class="form-group">
                    <label class="form-label">Select Date</label>
                    <input type="date" id="date-picker" name="date" required class="form-input" min="<?= date('Y-m-d', strtotime('+1 day')) ?>">
                </div>

                <div class="form-group">
                    <label class="form-label">Available Times</label>
                    <div id="time-slots" class="time-slots-grid">
                        <p style="grid-column: 1 / -1; text-align: center; color: #64748b; padding: 12px;">Select a date to see available times</p>
                    </div>
                    <input type="hidden" id="selected-time" name="selected_time" required>
                </div>

                <div class="form-group">
                    <label class="form-label">Session Notes (Optional)</label>
                    <textarea name="notes" rows="4" class="form-input" placeholder="What would you like to focus on in this session?"></textarea>
                </div>

                <button type="submit" class="submit-btn">
                    📅 Book Appointment
                </button>
            </form>
        </div>
    </div>
</div>

<script>
const coachId = <?= $coach['id'] ?>;
let selectedSlot = null;

// Load available times when date changes
document.getElementById('date-picker').addEventListener('change', async (e) => {
    const date = e.target.value;
    if (!date) return;
    
    const timeSlotsEl = document.getElementById('time-slots');
    timeSlotsEl.innerHTML = '<p class="text-gray-500 col-span-2">Loading available times...</p>';
    
    try {
        const response = await fetch(`/atasteofafricanmarketplace/api/scheduling/availability.php?coach_id=${coachId}&date=${date}`);
        const data = await response.json();
        
        if (data.success && data.available_slots.length > 0) {
            timeSlotsEl.innerHTML = data.available_slots.map(slot => `
                <button type="button" onclick="selectTimeSlot('${slot.datetime}', '${slot.start_time}', '${slot.end_time}')" 
                        class="time-slot-btn">
                    ${slot.start_time} - ${slot.end_time}
                </button>
            `).join('');
        } else {
            timeSlotsEl.innerHTML = '<p style="grid-column: 1 / -1; text-align: center; color: #64748b; padding: 12px;">No available times on this date. Please select another date.</p>';
        }
    } catch (error) {
        timeSlotsEl.innerHTML = '<p style="grid-column: 1 / -1; text-align: center; color: #ef4444; padding: 12px;">Error loading times. Please try again.</p>';
    }
});

function selectTimeSlot(datetime, startTime, endTime) {
    // Remove previous selection
    document.querySelectorAll('.time-slot-btn').forEach(btn => {
        btn.classList.remove('selected');
    });
    
    // Highlight selected slot
    event.target.classList.add('selected');
    
    // Store selection
    selectedSlot = { datetime, startTime, endTime };
    document.getElementById('selected-time').value = datetime;
}

document.getElementById('booking-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    
    if (!selectedSlot) {
        alert('Please select a time slot');
        return;
    }
    
    const formData = new FormData(e.target);
    const notes = formData.get('notes');
    
    // Create datetime strings for API
    const startDateTime = selectedSlot.datetime;
    const startTime = new Date(startDateTime);
    const endTime = new Date(startTime.getTime() + 60 * 60 * 1000); // 1 hour later
    const endDateTime = endTime.toISOString().slice(0, 19).replace('T', ' ');
    
    const data = {
        coach_id: parseInt(coachId),
        starts_at: startDateTime,
        ends_at: endDateTime,
        notes
    };
    
    try {
        const response = await fetch(`/atasteofafricanmarketplace/api/appointments/create.php`, {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'credentials': 'include'
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        
        if (response.ok) {
            alert(`Appointment booked successfully with ${selectedSlot.startTime} - ${selectedSlot.endTime}!`);
            window.location.href = '/atasteofafricanmarketplace/dashboard/user/index.php';
        } else {
            alert(result.message || 'Booking failed. Please try again.');
        }
    } catch (error) {
        alert('Network error. Please try again.');
    }
});
</script>

<?php };
include __DIR__ . '/partials/layout.php';
?>