<?php
require_once __DIR__ . '/../../includes/dashboard-config.php';

// For role-specific pages, add:
checkRoleAccess(ROLE_STUDENT); // or ROLE_COUNSELOR or ROLE_ADMIN
require_once '../../includes/config.php';
require_once '../../includes/auth.php';
require_once '../../includes/functions.php';

if (!isLoggedIn() || !hasRole('counselor')) {
    header('Location: ../login.php');
    exit();
}

$counselor_id = $_SESSION['user_id'];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_appointment'])) {
        $student_id = $_POST['student_id'];
        $appointment_type = $_POST['appointment_type'];
        $scheduled_time = $_POST['scheduled_time'];
        $duration = $_POST['duration'];
        $notes = $_POST['notes'];
        
        try {
            $stmt = $pdo->prepare("INSERT INTO appointments 
                                 (student_id, counselor_id, appointment_type, scheduled_time, duration_minutes, notes) 
                                 VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$student_id, $counselor_id, $appointment_type, $scheduled_time, $duration, $notes]);
            
            $_SESSION['success_message'] = "Appointment scheduled successfully!";
            header("Location: appointments.php");
            exit();
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "Error scheduling appointment: " . $e->getMessage();
        }
    } elseif (isset($_POST['update_status'])) {
        $appointment_id = $_POST['appointment_id'];
        $status = $_POST['status'];
        
        $pdo->prepare("UPDATE appointments SET status = ? WHERE id = ?")
            ->execute([$status, $appointment_id]);
        
        $_SESSION['success_message'] = "Appointment status updated!";
        header("Location: appointments.php");
        exit();
    }
}

// Get upcoming appointments
$upcoming = $pdo->prepare("
    SELECT a.*, s.first_name, s.last_name, s.profile_photo
    FROM appointments a
    JOIN students s ON a.student_id = s.id
    WHERE a.counselor_id = ? 
    AND a.scheduled_time >= NOW()
    ORDER BY a.scheduled_time
");
$upcoming->execute([$counselor_id]);

// Get past appointments
$past = $pdo->prepare("
    SELECT a.*, s.first_name, s.last_name, s.profile_photo
    FROM appointments a
    JOIN students s ON a.student_id = s.id
    WHERE a.counselor_id = ? 
    AND a.scheduled_time < NOW()
    ORDER BY a.scheduled_time DESC
    LIMIT 10
");
$past->execute([$counselor_id]);

// Get assigned students for dropdown
$students = $pdo->prepare("
    SELECT id, first_name, last_name 
    FROM students 
    WHERE assigned_counselor_id = ?
    ORDER BY first_name
");
$students->execute([$counselor_id]);

include '../../includes/header.php';
?>

<div class="container py-5">
    <h2 class="mb-4">Appointment Management</h2>
    
    <?php displayMessages(); ?>
    
    <div class="row">
        <div class="col-lg-8">
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Upcoming Appointments</h5>
                    <button class="btn btn-primary" data-toggle="modal" data-target="#newAppointmentModal">
                        <i class="fas fa-plus"></i> New Appointment
                    </button>
                </div>
                <div class="card-body">
                    <?php if ($upcoming->rowCount() > 0): ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Student</th>
                                        <th>Type</th>
                                        <th>Date & Time</th>
                                        <th>Duration</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($appt = $upcoming->fetch()): ?>
                                        <tr>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <img src="../../<?= $appt['profile_photo'] ? 'uploads/profile-photos/'.$appt['profile_photo'] : 'assets/images/default-profile.jpg' ?>" 
                                                         class="rounded-circle mr-3" width="40" height="40">
                                                    <?= htmlspecialchars($appt['first_name'].' '.$appt['last_name']) ?>
                                                </div>
                                            </td>
                                            <td><?= ucwords(str_replace('_', ' ', $appt['appointment_type'])) ?></td>
                                            <td><?= date('M j, Y g:i a', strtotime($appt['scheduled_time'])) ?></td>
                                            <td><?= $appt['duration_minutes'] ?> mins</td>
                                            <td>
                                                <span class="badge badge-<?= 
                                                    $appt['status'] == 'scheduled' ? 'primary' : 
                                                    ($appt['status'] == 'completed' ? 'success' : 'warning') ?>">
                                                    <?= ucfirst($appt['status']) ?>
                                                </span>
                                            </td>
                                            <td>
                                                <a href="appointment-details.php?id=<?= $appt['id'] ?>" 
                                                   class="btn btn-sm btn-outline-primary">
                                                    View
                                                </a>
                                                <?php if ($appt['status'] == 'scheduled'): ?>
                                                    <button class="btn btn-sm btn-outline-success update-status" 
                                                            data-id="<?= $appt['id'] ?>" data-status="completed">
                                                        Complete
                                                    </button>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info">
                            No upcoming appointments scheduled.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Recent Past Appointments</h5>
                </div>
                <div class="card-body">
                    <?php if ($past->rowCount() > 0): ?>
                        <ul class="list-group">
                            <?php while ($appt = $past->fetch()): ?>
                                <li class="list-group-item">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <h6 class="mb-1"><?= htmlspecialchars($appt['first_name'].' '.$appt['last_name']) ?></h6>
                                            <small class="text-muted">
                                                <?= ucwords(str_replace('_', ' ', $appt['appointment_type'])) ?> - 
                                                <?= date('M j, Y g:i a', strtotime($appt['scheduled_time'])) ?>
                                            </small>
                                        </div>
                                        <span class="badge badge-<?= 
                                            $appt['status'] == 'completed' ? 'success' : 
                                            ($appt['status'] == 'no_show' ? 'danger' : 'warning') ?>">
                                            <?= ucfirst($appt['status']) ?>
                                        </span>
                                    </div>
                                </li>
                            <?php endwhile; ?>
                        </ul>
                    <?php else: ?>
                        <div class="alert alert-info">
                            No past appointments found.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Appointment Calendar</h5>
                </div>
                <div class="card-body">
                    <div id="appointmentCalendar"></div>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Quick Links</h5>
                </div>
                <div class="card-body">
                    <div class="list-group">
                        <a href="students.php" class="list-group-item list-group-item-action">
                            <i class="fas fa-users mr-2"></i> My Students
                        </a>
                        <a href="messages.php" class="list-group-item list-group-item-action">
                            <i class="fas fa-envelope mr-2"></i> Messages
                        </a>
                        <a href="applications.php" class="list-group-item list-group-item-action">
                            <i class="fas fa-file-alt mr-2"></i> Applications
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- New Appointment Modal -->
<div class="modal fade" id="newAppointmentModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="post">
                <div class="modal-header">
                    <h5 class="modal-title">Schedule New Appointment</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="student_id">Student</label>
                        <select class="form-control" id="student_id" name="student_id" required>
                            <option value="">Select student</option>
                            <?php while ($student = $students->fetch()): ?>
                                <option value="<?= $student['id'] ?>">
                                    <?= htmlspecialchars($student['first_name'].' '.$student['last_name']) ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="appointment_type">Appointment Type</label>
                        <select class="form-control" id="appointment_type" name="appointment_type" required>
                            <option value="consultation">Consultation</option>
                            <option value="document_review">Document Review</option>
                            <option value="interview_prep">Interview Preparation</option>
                            <option value="visa_guidance">Visa Guidance</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="scheduled_time">Date & Time</label>
                        <input type="datetime-local" class="form-control" id="scheduled_time" 
                               name="scheduled_time" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="duration">Duration (minutes)</label>
                        <select class="form-control" id="duration" name="duration" required>
                            <option value="30">30 minutes</option>
                            <option value="45">45 minutes</option>
                            <option value="60">60 minutes</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="notes">Notes</label>
                        <textarea class="form-control" id="notes" name="notes" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" name="add_appointment" class="btn btn-primary">Schedule</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Status Update Modal -->
<div class="modal fade" id="statusModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form method="post">
                <input type="hidden" id="appointment_id" name="appointment_id">
                <input type="hidden" name="update_status" value="1">
                
                <div class="modal-header">
                    <h5 class="modal-title">Update Appointment Status</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="status">Status</label>
                        <select class="form-control" id="status" name="status" required>
                            <option value="completed">Completed</option>
                            <option value="cancelled">Cancelled</option>
                            <option value="no_show">No Show</option>
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update</button>
                </div>
            </form>
        </div>
    </div>
</div>

<link href="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.1/main.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.1/main.min.js"></script>

<script>
// Initialize calendar
document.addEventListener('DOMContentLoaded', function() {
    const calendarEl = document.getElementById('appointmentCalendar');
    const calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
        events: '../../api/appointments.php?counselor=<?= $counselor_id ?>',
        eventClick: function(info) {
            window.location.href = 'appointment-details.php?id=' + info.event.id;
        }
    });
    calendar.render();
});

// Handle status update buttons
document.querySelectorAll('.update-status').forEach(button => {
    button.addEventListener('click', function() {
        document.getElementById('appointment_id').value = this.dataset.id;
        document.getElementById('status').value = this.dataset.status;
        $('#statusModal').modal('show');
    });
});
</script>

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