<?php
/**
 * JV Overseas Education - Book New Appointment
 * Single-file PHP with integrated HTML and backend logic
 * Matches design of original index.html
 */

session_start();

// Database connection
$host = 'localhost';
$dbname = 'jv_overseas';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Authentication check
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'student') {
    header('Location: student-login.php');
    exit;
}

// Get student data
$stmt = $pdo->prepare("SELECT s.*, u.email, 
                      CONCAT(c.first_name, ' ', c.last_name) as counselor_name,
                      c.id as counselor_id, c.specialization
                      FROM students s 
                      LEFT JOIN counselors c ON s.assigned_counselor_id = c.id
                      JOIN users u ON s.id = u.id 
                      WHERE s.id = ?");
$stmt->execute([$_SESSION['user_id']]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    die("Student profile not found.");
}

// Get available counselors
$counselors = $pdo->query("SELECT c.*, u.email, 
                          CONCAT(c.first_name, ' ', c.last_name) as full_name
                          FROM counselors c
                          JOIN users u ON c.id = u.id
                          WHERE u.is_active = 1
                          ORDER BY c.performance_rating DESC, c.first_name");
$counselors = $counselors->fetchAll();

// Get appointment types
$appointment_types = [
    'consultation' => [
        'name' => 'Initial Consultation',
        'duration' => 30,
        'description' => 'Discuss your study abroad goals, preferred destinations, and academic background'
    ],
    'document_review' => [
        'name' => 'Document Review',
        'duration' => 45,
        'description' => 'Review your application documents, transcripts, and recommendation letters'
    ],
    'interview_prep' => [
        'name' => 'Interview Preparation',
        'duration' => 60,
        'description' => 'Prepare for university admission interviews with mock sessions and feedback'
    ],
    'visa_guidance' => [
        'name' => 'Visa Guidance',
        'duration' => 30,
        'description' => 'Get guidance on visa application process, required documents, and interview tips'
    ],
    'other' => [
        'name' => 'Other Inquiry',
        'duration' => 30,
        'description' => 'Any other questions or concerns about your study abroad journey'
    ]
];

$error = '';
$success = '';

// Handle appointment booking
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['book_appointment'])) {
    $counselor_id = $_POST['counselor_id'] ?? '';
    $appointment_type = $_POST['appointment_type'] ?? '';
    $scheduled_date = $_POST['scheduled_date'] ?? '';
    $scheduled_time = $_POST['scheduled_time'] ?? '';
    $notes = trim($_POST['notes'] ?? '');
    
    if (empty($counselor_id) || empty($appointment_type) || empty($scheduled_date) || empty($scheduled_time)) {
        $error = "All required fields must be filled.";
    } elseif (!in_array($appointment_type, array_keys($appointment_types))) {
        $error = "Invalid appointment type selected.";
    } elseif (!strtotime($scheduled_date)) {
        $error = "Invalid date format.";
    } elseif (!strtotime($scheduled_time)) {
        $error = "Invalid time format.";
    } else {
        // Combine date and time
        $scheduled_datetime = $scheduled_date . ' ' . $scheduled_time;
        
        // Validate date is in the future
        if (strtotime($scheduled_datetime) <= time()) {
            $error = "Please select a date and time in the future.";
        } else {
            try {
                // Check if counselor is available at that time
                $stmt = $pdo->prepare("SELECT id FROM appointments 
                                      WHERE counselor_id = ? AND scheduled_time = ? 
                                      AND status IN ('scheduled', 'in_progress')");
                $stmt->execute([$counselor_id, $scheduled_datetime]);
                
                if ($stmt->fetch()) {
                    $error = "The selected counselor is not available at this time. Please choose another time slot.";
                } else {
                    // Get duration for this appointment type
                    $duration = $appointment_types[$appointment_type]['duration'];
                    
                    // Insert appointment
                    $stmt = $pdo->prepare("INSERT INTO appointments (
                        student_id, counselor_id, appointment_type, scheduled_time, duration_minutes, 
                        status, notes, google_meet_link, created_at
                    ) VALUES (?, ?, ?, ?, ?, 'scheduled', ?, NULL, NOW())");
                    
                    $stmt->execute([
                        $_SESSION['user_id'], $counselor_id, $appointment_type, $scheduled_datetime, 
                        $duration, $notes
                    ]);
                    
                    $appointment_id = $pdo->lastInsertId();
                    
                    // Create Google Meet link (simulated)
                    $google_meet_link = "https://meet.google.com/" . substr(md5($appointment_id), 0, 12);
                    $pdo->prepare("UPDATE appointments SET google_meet_link = ? WHERE id = ?")
                        ->execute([$google_meet_link, $appointment_id]);
                    
                    // Create notification for counselor
                    $pdo->prepare("INSERT INTO notifications (
                        user_id, title, message, is_read, notification_type, created_at
                    ) VALUES (?, ?, ?, 0, 'appointment', NOW())")->execute([
                        $counselor_id,
                        "New Appointment Scheduled",
                        "Student {$_SESSION['first_name']} {$_SESSION['last_name']} has scheduled a {$appointment_types[$appointment_type]['name']} appointment"
                    ]);
                    
                    // Create task for counselor
                    $pdo->prepare("INSERT INTO tasks (
                        title, description, assigned_to, assigned_by, related_student_id, priority, status, deadline, created_at
                    ) VALUES (?, ?, ?, ?, ?, 'medium', 'pending', ?, NOW())")->execute([
                        "Prepare for {$appointment_types[$appointment_type]['name']}",
                        "Meeting with {$_SESSION['first_name']} {$_SESSION['last_name']} on {$scheduled_datetime}",
                        $counselor_id, $_SESSION['user_id'], $_SESSION['user_id'],
                        $scheduled_datetime
                    ]);
                    
                    $_SESSION['success'] = "Appointment booked successfully! You will receive a confirmation email with the Google Meet link.";
                    header("Location: book-new-appointment.php");
                    exit;
                }
            } catch (Exception $e) {
                $error = "Failed to book appointment. Please try again.";
            }
        }
    }
}

// Logout
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: student-dashboard.php');
    exit;
}

// Display success message from session if exists
$success = $_SESSION['success'] ?? '';
unset($_SESSION['success']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Book Appointment - JV Overseas Education</title>
    <meta content="width=device-width, initial-scale=1.0" name="viewport">
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css2?family=Jost:wght@500;600;700&family=Open+Sans:wght@400;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet">
    <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">
    <style>
        .counselor-card {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            transition: all 0.3s;
        }
        .counselor-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }
        .counselor-card.selected {
            border-color: #3fb7fe;
            background: #f8f9ff;
        }
        .counselor-photo {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            object-fit: cover;
        }
        .rating {
            color: #ffc107;
        }
        .appointment-type {
            border: 1px solid #eee;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .appointment-type:hover {
            border-color: #3fb7fe;
        }
        .appointment-type.selected {
            border-color: #3fb7fe;
            background: #f8f9ff;
        }
        .time-slot {
            display: inline-block;
            padding: 8px 15px;
            margin: 5px;
            border: 1px solid #ddd;
            border-radius: 20px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .time-slot:hover {
            border-color: #3fb7fe;
            color: #3fb7fe;
        }
        .time-slot.selected {
            background: #3fb7fe;
            color: white;
            border-color: #3fb7fe;
        }
        .time-slot.unavailable {
            background: #f8f9fa;
            color: #6c757d;
            border-color: #dee2e6;
            cursor: not-allowed;
        }
        .duration-badge {
            font-size: 0.8em;
            padding: 3px 8px;
            border-radius: 15px;
        }
        .availability-calendar {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-top: 20px;
        }
    </style>
</head>
<body>

<?php include 'student-navbar.php'; ?>

<div class="container py-5">
    <div class="section-title position-relative mb-4">
        <h6 class="d-inline-block position-relative text-secondary text-uppercase pb-2">Schedule Appointment</h6>
        <h1 class="display-5">Book a Counseling Session</h1>
    </div>

    <?php if (isset($error)): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>
    
    <?php if (!empty($success)): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <div class="text-center">
            <a href="student-dashboard.php" class="btn btn-primary">Return to Dashboard</a>
        </div>
    <?php else: ?>
        <div class="row">
            <div class="col-lg-8">
                <!-- Step 1: Select Appointment Type -->
                <div class="bg-white p-4 rounded mb-4">
                    <h5 class="mb-3">1. Select Appointment Type</h5>
                    
                    <div class="row">
                        <?php foreach ($appointment_types as $type => $info): ?>
                        <div class="col-md-6 mb-3">
                            <div class="appointment-type" data-type="<?= $type ?>">
                                <div class="d-flex justify-content-between">
                                    <strong><?= $info['name'] ?></strong>
                                    <span class="duration-badge bg-primary">
                                        <?= $info['duration'] ?> min
                                    </span>
                                </div>
                                <div class="small mt-1"><?= $info['description'] ?></div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <input type="hidden" name="appointment_type" id="selected_appointment_type" required>
                </div>

                <!-- Step 2: Select Counselor -->
                <div class="bg-white p-4 rounded mb-4">
                    <h5 class="mb-3">2. Select Counselor</h5>
                    
                    <?php if (empty($counselors)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-user-tie fa-3x text-muted mb-3"></i>
                            <p>No counselors available at the moment.</p>
                            <p class="small">Please contact our office for assistance.</p>
                        </div>
                    <?php else: ?>
                        <div class="row">
                            <?php foreach ($counselors as $counselor): ?>
                            <div class="col-md-6 mb-3">
                                <div class="counselor-card" data-counselor="<?= $counselor['id'] ?>">
                                    <div class="d-flex">
                                        <img src="<?= htmlspecialchars($counselor['profile_photo'] ?: 'img/counselor-placeholder.jpg') ?>" 
                                             alt="<?= htmlspecialchars($counselor['full_name']) ?>" 
                                             class="counselor-photo mr-3">
                                        <div>
                                            <h6 class="mb-1"><?= htmlspecialchars($counselor['full_name']) ?></h6>
                                            <p class="small mb-1">
                                                <i class="fas fa-briefcase"></i> 
                                                <?= htmlspecialchars($counselor['specialization'] ?: 'Study Abroad Consultant') ?>
                                            </p>
                                            <p class="small mb-1">
                                                <i class="fas fa-envelope"></i> <?= htmlspecialchars($counselor['email']) ?>
                                            </p>
                                            <div class="rating">
                                                <i class="fas fa-star"></i>
                                                <i class="fas fa-star"></i>
                                                <i class="fas fa-star"></i>
                                                <i class="fas fa-star"></i>
                                                <i class="fas fa-star<?= $counselor['performance_rating'] >= 4.5 ? '' : '-half-alt' ?>"></i>
                                                <span class="ml-1 small"><?= number_format($counselor['performance_rating'], 1) ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                    
                    <input type="hidden" name="counselor_id" id="selected_counselor_id" required>
                </div>

                <!-- Step 3: Select Date & Time -->
                <div class="bg-white p-4 rounded mb-4">
                    <h5 class="mb-3">3. Select Date & Time</h5>
                    
                    <div class="form-group">
                        <label>Select Date</label>
                        <input type="date" class="form-control" id="scheduled_date" min="<?= date('Y-m-d') ?>" required>
                    </div>
                    
                    <div class="availability-calendar">
                        <h6>Available Time Slots</h6>
                        <p class="text-muted small">Select a date above to see available time slots</p>
                        <div id="time_slots_container">
                            <!-- Time slots will be populated by JavaScript -->
                        </div>
                    </div>
                    
                    <input type="hidden" name="scheduled_time" id="selected_scheduled_time" required>
                </div>

                <!-- Additional Notes -->
                <div class="bg-white p-4 rounded mb-4">
                    <h5 class="mb-3">4. Additional Information</h5>
                    <div class="form-group">
                        <label>Notes (Optional)</label>
                        <textarea name="notes" id="notes" class="form-control" rows="4" 
                                  placeholder="Any specific topics you'd like to discuss? Documents you'll bring?"></textarea>
                    </div>
                </div>

                <!-- Book Appointment Button -->
                <div class="text-center">
                    <button type="button" id="book_appointment_btn" class="btn btn-primary btn-lg px-5" disabled>
                        <i class="fas fa-calendar-check"></i> Book Appointment
                    </button>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="bg-light p-4 rounded">
                    <h6><i class="fas fa-info-circle"></i> Appointment Guidelines</h6>
                    <ul class="small">
                        <li>Appointments can be scheduled up to 4 weeks in advance</li>
                        <li>Cancel or reschedule at least 24 hours in advance</li>
                        <li>Sessions are conducted via Google Meet (link provided)</li>
                        <li>Have your documents ready if discussing applications</li>
                        <li>Be on time - sessions start promptly</li>
                    </ul>
                    
                    <hr>
                    
                    <h6><i class="fas fa-clock"></i> Typical Response Time</h6>
                    <p class="small">Counselors typically confirm appointments within 24 business hours.</p>
                    
                    <hr>
                    
                    <h6><i class="fas fa-question-circle"></i> Need Help?</h6>
                    <p class="small mb-1">Contact our office:</p>
                    <p class="font-weight-bold">+256 788 289 235</p>
                    <p class="small mb-1">Office hours:</p>
                    <p class="small">Mon-Fri: 8:00 AM - 5:00 PM EAT</p>
                </div>
            </div>
        </div>
        
        <!-- Hidden form for submission -->
        <form method="POST" id="appointment_form">
            <input type="hidden" name="book_appointment" value="1">
            <input type="hidden" name="counselor_id" id="form_counselor_id">
            <input type="hidden" name="appointment_type" id="form_appointment_type">
            <input type="hidden" name="scheduled_date" id="form_scheduled_date">
            <input type="hidden" name="scheduled_time" id="form_scheduled_time">
            <input type="hidden" name="notes" id="form_notes">
        </form>
    <?php endif; ?>
</div>

<?php include 'footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.bundle.min.js"></script>
<script>
    $(document).ready(function() {
        let selectedType = null;
        let selectedCounselor = null;
        let selectedTime = null;
        
        // Select appointment type
        $('.appointment-type').on('click', function() {
            $('.appointment-type').removeClass('selected');
            $(this).addClass('selected');
            selectedType = $(this).data('type');
            $('#selected_appointment_type').val(selectedType);
            updateBookButton();
        });
        
        // Select counselor
        $('.counselor-card').on('click', function() {
            $('.counselor-card').removeClass('selected');
            $(this).addClass('selected');
            selectedCounselor = $(this).data('counselor');
            $('#selected_counselor_id').val(selectedCounselor);
            updateBookButton();
        });
        
        // Update time slots when date changes
        $('#scheduled_date').on('change', function() {
            const date = $(this).val();
            if (date && selectedCounselor && selectedType) {
                fetchAvailableTimes(date, selectedCounselor);
            }
        });
        
        // Select time slot
        $(document).on('click', '.time-slot:not(.unavailable)', function() {
            $('.time-slot').removeClass('selected');
            $(this).addClass('selected');
            selectedTime = $(this).data('time');
            $('#selected_scheduled_time').val(selectedTime);
            updateBookButton();
        });
        
        // Update book button state
        function updateBookButton() {
            const isEnabled = selectedType && selectedCounselor && selectedTime;
            $('#book_appointment_btn').prop('disabled', !isEnabled);
        }
        
        // Fetch available time slots
        function fetchAvailableTimes(date, counselorId) {
            // In a real application, this would be an AJAX call to a backend endpoint
            // For demo purposes, we'll generate sample time slots
            
            const container = $('#time_slots_container');
            container.html('<p class="text-muted small">Loading available times...</p>');
            
            // Simulate API delay
            setTimeout(() => {
                const slots = generateTimeSlots(date, counselorId);
                container.empty();
                
                if (slots.length === 0) {
                    container.html('<p class="text-muted small">No available time slots for this date.</p>');
                } else {
                    slots.forEach(slot => {
                        const classes = ['time-slot'];
                        if (slot.available) {
                            classes.push('available');
                        } else {
                            classes.push('unavailable');
                        }
                        container.append(`<span class="${classes.join(' ')}" 
                                              data-time="${slot.time}" 
                                              title="${slot.available ? '' : 'Unavailable'}">${slot.display}</span>`);
                    });
                }
            }, 500);
        }
        
        // Generate sample time slots (in a real app, this would come from the server)
        function generateTimeSlots(date, counselorId) {
            const slots = [];
            const now = new Date();
            const selectedDate = new Date(date);
            const isToday = selectedDate.toDateString() === now.toDateString();
            
            // Business hours: 8 AM to 5 PM
            for (let hour = 8; hour <= 17; hour++) {
                for (let minute = 0; minute < 60; minute += 30) {
                    const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
                    const dateTimeStr = `${date} ${timeStr}:00`;
                    const slotTime = new Date(dateTimeStr);
                    
                    // Skip past times for today
                    if (isToday && slotTime <= now) {
                        slots.push({
                            time: timeStr,
                            display: formatTime(timeStr),
                            available: false
                        });
                        continue;
                    }
                    
                    // Skip lunch break (12:00 - 1:00 PM)
                    if (hour === 12) {
                        slots.push({
                            time: timeStr,
                            display: formatTime(timeStr),
                            available: false
                        });
                        continue;
                    }
                    
                    // Randomly mark some slots as unavailable (simulating existing appointments)
                    const isAvailable = Math.random() > 0.3; // 70% chance of being available
                    
                    slots.push({
                        time: timeStr,
                        display: formatTime(timeStr),
                        available: isAvailable
                    });
                }
            }
            
            return slots;
        }
        
        // Format time for display
        function formatTime(timeStr) {
            const [hour, minute] = timeStr.split(':');
            const h = parseInt(hour);
            const period = h >= 12 ? 'PM' : 'AM';
            const displayHour = h % 12 || 12;
            return `${displayHour}:${minute} ${period}`;
        }
        
        // Book appointment button click
        $('#book_appointment_btn').on('click', function() {
            if (selectedType && selectedCounselor && selectedTime) {
                if (confirm('You are about to book a session with your counselor. Continue?')) {
                    $('#form_counselor_id').val(selectedCounselor);
                    $('#form_appointment_type').val(selectedType);
                    $('#form_scheduled_date').val($('#scheduled_date').val());
                    $('#form_scheduled_time').val(selectedTime);
                    $('#form_notes').val($('#notes').val());
                    $('#appointment_form').submit();
                }
            }
        });
    });
</script>
</body>
</html>