<?php
session_start();
require_once 'config.php';

// Check if patient is logged in
if (!isset($_SESSION['patient_id'])) {
    // If not logged in, redirect to login page
    header('Location: patient_login.php');
    exit;
}

$patient_id = $_SESSION['patient_id'];

// --- Handle Appointment Cancellation ---
if (isset($_GET['cancel']) && isset($_GET['id'])) {
    $appointment_id = intval($_GET['id']);
    
    // Verify this appointment belongs to the patient
    $check_query = "SELECT id, time_slot_id, status FROM appointments 
                    WHERE id = $appointment_id AND patient_id = $patient_id AND status = 'confirmed'";
    $check_result = mysqli_query($conn, $check_query);
    
    if ($check_result && mysqli_num_rows($check_result) > 0) {
        $appointment = mysqli_fetch_assoc($check_result);
        
        // Begin transaction
        mysqli_begin_transaction($conn);
        
        try {
            // Update appointment status to cancelled
            $update_query = "UPDATE appointments SET status = 'cancelled' WHERE id = $appointment_id";
            mysqli_query($conn, $update_query);
            
            // Free up the time slot
            if ($appointment['time_slot_id']) {
                $update_slot = "UPDATE time_slots SET is_booked = 0 WHERE id = {$appointment['time_slot_id']}";
                mysqli_query($conn, $update_slot);
            }
            
            mysqli_commit($conn);
            $_SESSION['success'] = "Appointment cancelled successfully!";
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $_SESSION['error'] = "Failed to cancel appointment: " . $e->getMessage();
        }
    } else {
        $_SESSION['error'] = "Invalid appointment or you don't have permission to cancel this.";
    }
    
    header('Location: my_appointments.php');
    exit;
}

// --- Fetch Patient Appointments ---
$query = "SELECT 
            a.id,
            a.appointment_date,
            a.patient_category,
            a.fee,
            a.status,
            a.booking_time,
            d.name as doctor_name,
            d.qualification as doctor_qualification,
            d.image as doctor_image,
            c.name as chamber_name,
            c.address as chamber_address,
            c.phone as chamber_phone,
            ts.start_time,
            ts.end_time
          FROM appointments a
          LEFT JOIN doctors d ON a.doctor_id = d.id
          LEFT JOIN chambers c ON a.chamber_id = c.id
          LEFT JOIN time_slots ts ON a.time_slot_id = ts.id
          WHERE a.patient_id = $patient_id
          ORDER BY a.appointment_date DESC, ts.start_time DESC";

$result = mysqli_query($conn, $query);

if (!$result) {
    $error = "Error fetching appointments: " . mysqli_error($conn);
}

// Get patient info
$patient_query = "SELECT name, phone, email FROM patients WHERE id = $patient_id";
$patient_result = mysqli_query($conn, $patient_query);
$patient = mysqli_fetch_assoc($patient_result);
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>আমার অ্যাপয়েন্টমেন্ট - ডা. মোঃ ফেরদৌস</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { 
            background: #f0f8ff; 
            font-family: 'SolaimanLipi', Arial, sans-serif; 
        }
        .container { 
            max-width: 1200px; 
            margin: 30px auto; 
        }
        .card { 
            border-radius: 15px; 
            box-shadow: 0 0 20px rgba(0,0,0,0.1); 
            border: none; 
            margin-bottom: 20px;
        }
        .card-header { 
            background: linear-gradient(135deg, #1a5276, #2e86c1); 
            color: white; 
            border-radius: 15px 15px 0 0 !important;
            padding: 20px;
        }
        .appointment-card {
            border: 1px solid #e0e0e0;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            background: white;
            transition: all 0.3s;
            position: relative;
        }
        .appointment-card:hover {
            box-shadow: 0 5px 20px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        .appointment-card .status-badge {
            position: absolute;
            top: 15px;
            right: 15px;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        .status-confirmed { background: #d4edda; color: #155724; }
        .status-pending { background: #fff3cd; color: #856404; }
        .status-cancelled { background: #f8d7da; color: #721c24; }
        .status-completed { background: #cce5ff; color: #004085; }
        
        .doctor-image {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            object-fit: cover;
            border: 3px solid #1a5276;
        }
        .placeholder-image {
            width: 70px;
            height: 70px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #6c757d;
            font-size: 30px;
            border: 3px solid #1a5276;
        }
        .btn-cancel {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 20px;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .btn-cancel:hover {
            background: #c82333;
            color: white;
        }
        .btn-book {
            background: linear-gradient(135deg, #1a5276, #2e86c1);
            color: white;
            border: none;
            padding: 10px 25px;
            border-radius: 8px;
            font-weight: 600;
        }
        .btn-book:hover {
            background: linear-gradient(135deg, #154360, #1a5276);
            color: white;
        }
        .no-appointments {
            text-align: center;
            padding: 50px 20px;
        }
        .no-appointments i {
            font-size: 60px;
            color: #6c757d;
            margin-bottom: 20px;
        }
        .filter-section {
            background: white;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .appointment-details {
            font-size: 14px;
        }
        .appointment-details i {
            width: 20px;
            color: #1a5276;
        }
        .fee-tag {
            background: #eaf4f9;
            padding: 3px 12px;
            border-radius: 15px;
            font-weight: 600;
            color: #1a5276;
            font-size: 14px;
        }
        .btn-back {
            background: #95a5a6;
            color: white;
            border: none;
            padding: 10px 25px;
            border-radius: 8px;
            transition: all 0.3s;
        }
        .btn-back:hover {
            background: #7f8c8d;
            color: white;
        }
        .modal-content {
            border-radius: 15px;
        }
        .modal-header {
            background: linear-gradient(135deg, #1a5276, #2e86c1);
            color: white;
            border-radius: 15px 15px 0 0;
        }
        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Header -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <div>
                    <h3 class="mb-0"><i class="fas fa-calendar-check"></i> আমার অ্যাপয়েন্টমেন্ট</h3>
                    <small>স্বাগতম, <?php echo htmlspecialchars($patient['name'] ?? 'রোগী'); ?></small>
                </div>
                <div>
                    <a href="book_appointment.php" class="btn btn-light btn-sm">
                        <i class="fas fa-plus-circle"></i> নতুন অ্যাপয়েন্টমেন্ট
                    </a>
                    <a href="patient_dashboard.php" class="btn btn-light btn-sm">
                        <i class="fas fa-home"></i> ড্যাশবোর্ড
                    </a>
                </div>
            </div>
        </div>

        <!-- Success/Error Messages -->
        <?php if (isset($_SESSION['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($_SESSION['error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle"></i> <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Filter/Search Section -->
        <div class="filter-section">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <div class="btn-group" role="group">
                        <button type="button" class="btn btn-outline-primary active" onclick="filterAppointments('all')">
                            <i class="fas fa-list"></i> সব
                        </button>
                        <button type="button" class="btn btn-outline-success" onclick="filterAppointments('confirmed')">
                            <i class="fas fa-check-circle"></i> নিশ্চিত
                        </button>
                        <button type="button" class="btn btn-outline-warning" onclick="filterAppointments('pending')">
                            <i class="fas fa-clock"></i> পেন্ডিং
                        </button>
                        <button type="button" class="btn btn-outline-danger" onclick="filterAppointments('cancelled')">
                            <i class="fas fa-times-circle"></i> বাতিল
                        </button>
                    </div>
                </div>
                <div class="col-md-6 text-end">
                    <span class="text-muted">মোট অ্যাপয়েন্টমেন্ট: <strong><?php echo mysqli_num_rows($result); ?></strong></span>
                </div>
            </div>
        </div>

        <!-- Appointments List -->
        <?php if ($result && mysqli_num_rows($result) > 0): ?>
            <div id="appointmentsContainer">
                <?php while ($appointment = mysqli_fetch_assoc($result)): 
                    $status_class = 'status-' . ($appointment['status'] ?? 'pending');
                    $status_text = [
                        'confirmed' => 'নিশ্চিত',
                        'pending' => 'পেন্ডিং',
                        'cancelled' => 'বাতিল',
                        'completed' => 'সম্পন্ন'
                    ][$appointment['status'] ?? 'pending'] ?? $appointment['status'];
                ?>
                    <div class="appointment-card" data-status="<?php echo $appointment['status'] ?? 'pending'; ?>">
                        <span class="status-badge <?php echo $status_class; ?>">
                            <?php echo $status_text; ?>
                        </span>
                        
                        <div class="row">
                            <!-- Doctor Info -->
                            <div class="col-md-3 col-12">
                                <div class="d-flex align-items-center">
                                    <?php if (!empty($appointment['doctor_image']) && file_exists($appointment['doctor_image'])): ?>
                                        <img src="<?php echo $appointment['doctor_image']; ?>" class="doctor-image" alt="<?php echo $appointment['doctor_name']; ?>">
                                    <?php else: ?>
                                        <div class="placeholder-image">
                                            <i class="fas fa-user-md"></i>
                                        </div>
                                    <?php endif; ?>
                                    <div class="ms-3">
                                        <h5 class="mb-0"><?php echo htmlspecialchars($appointment['doctor_name'] ?? 'N/A'); ?></h5>
                                        <small class="text-muted"><?php echo htmlspecialchars($appointment['doctor_qualification'] ?? ''); ?></small>
                                    </div>
                                </div>
                            </div>

                            <!-- Appointment Details -->
                            <div class="col-md-5 col-12">
                                <div class="appointment-details">
                                    <div><i class="fas fa-hospital"></i> <strong><?php echo htmlspecialchars($appointment['chamber_name'] ?? 'N/A'); ?></strong></div>
                                    <div><i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($appointment['chamber_address'] ?? 'N/A'); ?></div>
                                    <div><i class="fas fa-calendar-day"></i> <?php echo date('d-m-Y', strtotime($appointment['appointment_date'])); ?></div>
                                    <div><i class="fas fa-clock"></i> <?php echo date('h:i A', strtotime($appointment['start_time'] ?? '00:00')); ?> - <?php echo date('h:i A', strtotime($appointment['end_time'] ?? '00:00')); ?></div>
                                    <div><i class="fas fa-phone"></i> <?php echo htmlspecialchars($appointment['chamber_phone'] ?? 'N/A'); ?></div>
                                </div>
                            </div>

                            <!-- Fee & Actions -->
                            <div class="col-md-4 col-12 text-md-end text-start">
                                <div class="mb-2">
                                    <span class="fee-tag">
                                        <i class="fas fa-money-bill-wave"></i> <?php echo number_format($appointment['fee'] ?? 0, 0); ?> টাকা
                                    </span>
                                    <span class="badge bg-info ms-2">
                                        <?php echo ucfirst(str_replace('_', ' ', $appointment['patient_category'] ?? 'regular')); ?>
                                    </span>
                                </div>
                                
                                <div class="mt-2">
                                    <?php if (($appointment['status'] ?? '') == 'confirmed'): ?>
                                        <button class="btn-cancel btn-sm" onclick="confirmCancel(<?php echo $appointment['id']; ?>)">
                                            <i class="fas fa-times"></i> বাতিল করুন
                                        </button>
                                    <?php endif; ?>
                                    
                                    <?php if (($appointment['status'] ?? '') == 'cancelled'): ?>
                                        <a href="book_appointment.php?reschedule=<?php echo $appointment['id']; ?>" class="btn btn-primary btn-sm">
                                            <i class="fas fa-redo"></i> পুনরায় বুক করুন
                                        </a>
                                    <?php endif; ?>
                                    
                                    <button class="btn btn-outline-info btn-sm" onclick="viewDetails(<?php echo htmlspecialchars(json_encode($appointment)); ?>)">
                                        <i class="fas fa-eye"></i> বিস্তারিত
                                    </button>
                                </div>
                                
                                <small class="text-muted d-block mt-2">
                                    বুকিং: <?php echo date('d-m-Y h:i A', strtotime($appointment['booking_time'])); ?>
                                </small>
                            </div>
                        </div>
                    </div>
                <?php endwhile; ?>
            </div>
        <?php else: ?>
            <div class="card">
                <div class="card-body">
                    <div class="no-appointments">
                        <i class="fas fa-calendar-times"></i>
                        <h4>কোনও অ্যাপয়েন্টমেন্ট পাওয়া যায়নি</h4>
                        <p class="text-muted">আপনি এখনো কোনো অ্যাপয়েন্টমেন্ট বুক করেননি।</p>
                        <a href="book_appointment.php" class="btn btn-book">
                            <i class="fas fa-plus-circle"></i> নতুন অ্যাপয়েন্টমেন্ট বুক করুন
                        </a>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Cancel Confirmation Modal -->
    <div class="modal fade" id="cancelModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-exclamation-triangle"></i> নিশ্চিত করুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>আপনি কি এই অ্যাপয়েন্টমেন্টটি বাতিল করতে চান?</p>
                    <p class="text-danger"><small>বাতিল করার পর এই স্লটটি অন্য রোগীদের জন্য উন্মুক্ত হবে।</small></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">না</button>
                    <a href="#" id="confirmCancelBtn" class="btn btn-danger">হ্যাঁ, বাতিল করুন</a>
                </div>
            </div>
        </div>
    </div>

    <!-- Appointment Details Modal -->
    <div class="modal fade" id="detailsModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><i class="fas fa-info-circle"></i> অ্যাপয়েন্টমেন্ট বিস্তারিত</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="detailsContent">
                    <!-- Dynamic content will be loaded here -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বন্ধ করুন</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Cancel confirmation
        function confirmCancel(appointmentId) {
            document.getElementById('confirmCancelBtn').href = 'my_appointments.php?cancel=1&id=' + appointmentId;
            var modal = new bootstrap.Modal(document.getElementById('cancelModal'));
            modal.show();
        }

        // View details
        function viewDetails(appointment) {
            var content = `
                <div class="row">
                    <div class="col-md-6">
                        <h6><i class="fas fa-user-md text-primary"></i> ডাক্তার</h6>
                        <p><strong>${appointment.doctor_name || 'N/A'}</strong><br>
                        <small>${appointment.doctor_qualification || ''}</small></p>
                    </div>
                    <div class="col-md-6">
                        <h6><i class="fas fa-hospital text-primary"></i> চেম্বার</h6>
                        <p><strong>${appointment.chamber_name || 'N/A'}</strong><br>
                        <small>${appointment.chamber_address || ''}</small></p>
                    </div>
                </div>
                <hr>
                <div class="row">
                    <div class="col-md-4">
                        <h6><i class="fas fa-calendar-day text-primary"></i> তারিখ</h6>
                        <p>${appointment.appointment_date ? new Date(appointment.appointment_date).toLocaleDateString('bn-BD') : 'N/A'}</p>
                    </div>
                    <div class="col-md-4">
                        <h6><i class="fas fa-clock text-primary"></i> সময়</h6>
                        <p>${appointment.start_time ? new Date('1970-01-01T' + appointment.start_time).toLocaleTimeString('en-US', {hour:'2-digit', minute:'2-digit'}) : 'N/A'}</p>
                    </div>
                    <div class="col-md-4">
                        <h6><i class="fas fa-money-bill-wave text-primary"></i> ফি</h6>
                        <p><strong>${appointment.fee || 0} টাকা</strong></p>
                    </div>
                </div>
                <hr>
                <div class="row">
                    <div class="col-md-6">
                        <h6><i class="fas fa-tag text-primary"></i> ক্যাটাগরি</h6>
                        <p>${appointment.patient_category || 'regular'}</p>
                    </div>
                    <div class="col-md-6">
                        <h6><i class="fas fa-info-circle text-primary"></i> স্ট্যাটাস</h6>
                        <p><span class="badge bg-${appointment.status === 'confirmed' ? 'success' : appointment.status === 'pending' ? 'warning' : 'danger'}">${appointment.status || 'pending'}</span></p>
                    </div>
                </div>
                ${appointment.notes ? `<hr><div class="row"><div class="col-12"><h6><i class="fas fa-sticky-note text-primary"></i> নোট</h6><p>${appointment.notes}</p></div></div>` : ''}
            `;
            document.getElementById('detailsContent').innerHTML = content;
            var modal = new bootstrap.Modal(document.getElementById('detailsModal'));
            modal.show();
        }

        // Filter appointments
        function filterAppointments(status) {
            var cards = document.querySelectorAll('.appointment-card');
            var buttons = document.querySelectorAll('.btn-group .btn');
            
            // Update active button
            buttons.forEach(function(btn) {
                btn.classList.remove('active');
            });
            document.querySelector('.btn-group .btn-' + (status === 'all' ? 'outline-primary' : 
                status === 'confirmed' ? 'outline-success' : 
                status === 'pending' ? 'outline-warning' : 'outline-danger')).classList.add('active');
            
            // Filter cards
            cards.forEach(function(card) {
                if (status === 'all') {
                    card.style.display = 'block';
                } else {
                    card.style.display = card.dataset.status === status ? 'block' : 'none';
                }
            });
        }

        // Auto-hide alerts after 5 seconds
        setTimeout(function() {
            var alerts = document.querySelectorAll('.alert');
            alerts.forEach(function(alert) {
                var bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            });
        }, 5000);
    </script>
</body>
</html>