<?php
// Sayfa başlığı
$page_title = "Randevular";
$active_page = "appointments";

// Header'ı dahil et
require_once 'templates/header.php';

// DB bağlantısı ve fonksiyonları dahil et
require_once 'config/database.php';
require_once 'includes/functions.php';

// Veritabanı bağlantısı
$database = new Database();
$db = $database->connect();

// İşlem türünü belirle (liste, ekle, düzenle, görüntüle, sil)
$action = isset($_GET['action']) ? $_GET['action'] : 'list';

// Görünüm türü (liste veya takvim)
$view_type = isset($_GET['view']) ? $_GET['view'] : 'list';

// Mesaj değişkeni
$message = '';

// İşleme göre sayfa başlığını güncelle
switch ($action) {
    case 'add':
        $page_title .= ' - Yeni Randevu Ekle';
        break;
    case 'edit':
        $page_title .= ' - Randevu Düzenle';
        break;
    case 'view':
        $page_title .= ' - Randevu Detayları';
        break;
}

// Randevu silme işlemi
if ($action == 'delete' && isset($_GET['id'])) {
    $id = $_GET['id'];
    
    try {
        $query = "DELETE FROM appointments WHERE id = :id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        
        $message = display_success("Randevu başarıyla silindi!");
        $action = 'list'; // Silme sonrası listeye dön
    } catch(PDOException $e) {
        $message = display_error("Hata: " . $e->getMessage());
    }
}

// Randevu durum güncelleme
if ($action == 'update_status' && isset($_GET['id']) && isset($_GET['status'])) {
    $id = $_GET['id'];
    $status = (int)$_GET['status'];
    
    try {
        // Önce randevu bilgilerini alıyoruz (özellikle hastanın ID'si ve mevcut durum)
        $query = "SELECT a.patient_id, a.appointment_date, a.status as current_status 
                 FROM appointments a
                 WHERE a.id = :id";
        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        
        if ($stmt->rowCount() > 0) {
            $appointment_info = $stmt->fetch(PDO::FETCH_ASSOC);
            $patient_id = $appointment_info['patient_id'];
            $appointment_date = $appointment_info['appointment_date'];
            $current_status = $appointment_info['current_status'];
            
            // Durumu güncelliyoruz
            $update_query = "UPDATE appointments SET status = :status WHERE id = :id";
            $update_stmt = $db->prepare($update_query);
            $update_stmt->bindParam(':id', $id);
            $update_stmt->bindParam(':status', $status);
            $update_stmt->execute();
            
            $message = display_success("Randevu durumu başarıyla güncellendi!");
            
            // Eğer durum "Gelmedi" olarak güncelleniyorsa, ceza uygula
            if ($status == 3 && $current_status != 3) {
                $penalty_date = date('Y-m-d', strtotime($appointment_date . ' + 15 days'));
                $penalty_query = "UPDATE patients SET penalty_until = :penalty_date WHERE id = :patient_id";
                $penalty_stmt = $db->prepare($penalty_query);
                $penalty_stmt->bindParam(':penalty_date', $penalty_date);
                $penalty_stmt->bindParam(':patient_id', $patient_id);
                $penalty_stmt->execute();
                
                $message .= display_info("Hasta randevuya gelmediği için " . format_date($penalty_date) . " tarihine kadar cezalandırıldı.");
            }
            // Eğer durum "Gelmedi"den başka bir duruma geçiyorsa cezayı kaldır
            else if ($current_status == 3 && $status != 3) {
                $remove_penalty_query = "UPDATE patients SET penalty_until = NULL WHERE id = :patient_id";
                $remove_penalty_stmt = $db->prepare($remove_penalty_query);
                $remove_penalty_stmt->bindParam(':patient_id', $patient_id);
                $remove_penalty_stmt->execute();
                
                $message .= display_info("Hastanın cezası kaldırıldı.");
            }
            
            // Görüntüleme sayfasına dön
            header("Location: appointments.php?action=view&id=$id");
            exit;
        } else {
            $message = display_error("Randevu bulunamadı!");
        }
    } catch(PDOException $e) {
        $message = display_error("Hata: " . $e->getMessage());
    }
}

// Bugünün tarihi
$today = date('Y-m-d');

// Seçilen tarih (filtreleme için)
$selected_date = isset($_GET['date']) ? $_GET['date'] : $today;

// Seçilen ay ve yıl (takvim için)
$month = isset($_GET['month']) ? (int)$_GET['month'] : (int)date('m');
$year = isset($_GET['year']) ? (int)$_GET['year'] : (int)date('Y');

// Ay başlangıç ve bitiş tarihleri (takvim için)
$start_date = "$year-" . str_pad($month, 2, '0', STR_PAD_LEFT) . "-01";
$end_date = date('Y-m-t', strtotime($start_date));

// Randevu ekleme ve düzenleme işlemi
if ($_SERVER['REQUEST_METHOD'] == 'POST' && ($action == 'add' || $action == 'edit')) {
    // Form verilerini al
    $patient_id = clean_input($_POST['patient_id']);
    $doctor_id = clean_input($_POST['doctor_id']);
    $appointment_date = clean_input($_POST['appointment_date']);
    $appointment_time = clean_input($_POST['appointment_time']);
    $status = isset($_POST['status']) ? (int)$_POST['status'] : 0;
    $notes = clean_input($_POST['notes']);
    
    // Geçmiş tarihe randevu kontrolü
    $today = date('Y-m-d');
    if (strtotime($appointment_date) < strtotime($today)) {
        $message = display_error("Geçmiş tarihe randevu alınamaz! Lütfen bugün veya ileri bir tarih seçin.");
    } else {
        try {
            // Randevu ekleme işleminde hastanın ceza durumunu kontrol et
            if ($action == 'add') {
                $penalty_query = "SELECT penalty_until FROM patients WHERE id = :patient_id";
                $penalty_stmt = $db->prepare($penalty_query);
                $penalty_stmt->bindParam(':patient_id', $patient_id);
                $penalty_stmt->execute();
                
                $patient_data = $penalty_stmt->fetch(PDO::FETCH_ASSOC);
                
                // Hastanın aktif bir cezası var mı kontrol et
                if ($patient_data && !empty($patient_data['penalty_until'])) {
                    $today = date('Y-m-d');
                    $penalty_date = $patient_data['penalty_until'];
                    
                    // Ceza süresi bugünden sonrası mı?
                    if (strtotime($penalty_date) > strtotime($today)) {
                        // Sadece seçilen randevu tarihi ceza tarihinden önce ise engelle
                        if (strtotime($appointment_date) <= strtotime($penalty_date)) {
                            $message = display_error("Bu hasta " . format_date($penalty_date) . " tarihine kadar cezalıdır ve bu tarihten öncesi için randevu alamaz!");
                            // Footer çağrılmadan önce action'ı listeye çevir ki form görüntülenmesin
                            $action = 'list';
                        }
                    }
                }
            }
            
            // Eğer hasta cezalı değilse veya düzenleme işlemiyse devam et
            if (empty($message)) {
                // Aynı gün ve saatte doktora ait başka randevu var mı kontrol et
                $check_query = "SELECT id FROM appointments WHERE doctor_id = :doctor_id AND appointment_date = :appointment_date AND appointment_time = :appointment_time";
                if ($action == 'edit' && isset($_GET['id'])) {
                    $check_query .= " AND id != :id";
                }
                
                $check_stmt = $db->prepare($check_query);
                $check_stmt->bindParam(':doctor_id', $doctor_id);
                $check_stmt->bindParam(':appointment_date', $appointment_date);
                $check_stmt->bindParam(':appointment_time', $appointment_time);
                
                if ($action == 'edit' && isset($_GET['id'])) {
                    $check_stmt->bindParam(':id', $_GET['id']);
                }
                
                $check_stmt->execute();
                
                if ($check_stmt->rowCount() > 0) {
                    $message = display_error("Bu saat için seçilen doktorun başka bir randevusu zaten var!");
                } else {
                    // Randevu ekleme veya güncelleme
                    if ($action == 'add') {
                        $query = "INSERT INTO appointments (patient_id, doctor_id, appointment_date, appointment_time, status, notes) 
                                VALUES (:patient_id, :doctor_id, :appointment_date, :appointment_time, :status, :notes)";
                    } else {
                        $query = "UPDATE appointments SET patient_id = :patient_id, doctor_id = :doctor_id, 
                                appointment_date = :appointment_date, appointment_time = :appointment_time,
                                status = :status, notes = :notes
                                WHERE id = :id";
                    }
                    
                    $stmt = $db->prepare($query);
                    $stmt->bindParam(':patient_id', $patient_id);
                    $stmt->bindParam(':doctor_id', $doctor_id);
                    $stmt->bindParam(':appointment_date', $appointment_date);
                    $stmt->bindParam(':appointment_time', $appointment_time);
                    $stmt->bindParam(':status', $status);
                    $stmt->bindParam(':notes', $notes);
                    
                    if ($action == 'edit') {
                        $stmt->bindParam(':id', $_GET['id']);
                    }
                    
                    $stmt->execute();
                    
                    if ($action == 'add') {
                        $message = display_success("Randevu başarıyla eklendi!");
                        // Yeni eklenen randevunun ID'sini al
                        $id = $db->lastInsertId();
                        // Randevuyu görüntüle
                        header("Location: appointments.php?action=view&id=$id");
                        exit;
                    } else {
                        // Randevu düzenleme işlemi
                        // Randevunun önceki durumunu al
                        $query = "SELECT status FROM appointments WHERE id = :id";
                        $stmt = $db->prepare($query);
                        $stmt->bindParam(':id', $_GET['id']);
                        $stmt->execute();
                        $old_status = $stmt->fetchColumn();
                        
                        // Durum "Gelmedi"ye değiştirildiyse ceza uygula
                        if ($status == 3 && $old_status != 3) {
                            $penalty_date = date('Y-m-d', strtotime($appointment_date . ' + 15 days'));
                            
                            $penalty_query = "UPDATE patients SET penalty_until = :penalty_date WHERE id = :patient_id";
                            $penalty_stmt = $db->prepare($penalty_query);
                            $penalty_stmt->bindParam(':penalty_date', $penalty_date);
                            $penalty_stmt->bindParam(':patient_id', $patient_id);
                            $penalty_stmt->execute();
                            
                            $message = display_success("Randevu bilgileri güncellendi. Hasta randevuya gelmediği için " . format_date($penalty_date) . " tarihine kadar cezalandırıldı.");
                        }
                        // "Gelmedi" durumundan başka bir duruma değiştirildiyse cezayı kaldır
                        else if ($old_status == 3 && $status != 3) {
                            $penalty_query = "UPDATE patients SET penalty_until = NULL WHERE id = :patient_id";
                            $penalty_stmt = $db->prepare($penalty_query);
                            $penalty_stmt->bindParam(':patient_id', $patient_id);
                            $penalty_stmt->execute();
                            
                            $message = display_success("Randevu bilgileri güncellendi. Hastanın cezası kaldırıldı.");
                        }
                        else {
                            $message = display_success("Randevu bilgileri başarıyla güncellendi!");
                        }
                    }
                }
            }
        } catch(PDOException $e) {
            $message = display_error("Hata: " . $e->getMessage());
        }
    }
}

// Randevu bilgilerini getir (düzenleme ve görüntüleme için)
if (($action == 'edit' || $action == 'view') && isset($_GET['id'])) {
    $id = $_GET['id'];
    
    try {
        $query = "SELECT a.*, 
                        p.tc_no AS patient_tc, p.name AS patient_name, p.surname AS patient_surname,
                        d.tc_no AS doctor_tc, d.name AS doctor_name, d.surname AS doctor_surname, d.specialty
                 FROM appointments a
                 JOIN patients p ON a.patient_id = p.id
                 JOIN doctors d ON a.doctor_id = d.id
                 WHERE a.id = :id";
        
        $stmt = $db->prepare($query);
        $stmt->bindParam(':id', $id);
        $stmt->execute();
        
        if ($stmt->rowCount() == 0) {
            $message = display_error("Randevu bulunamadı!");
            $action = 'list'; // Randevu bulunamadıysa listeye dön
        } else {
            $appointment = $stmt->fetch(PDO::FETCH_ASSOC);
            
            // Randevu bilgilerini değişkenlere aktar
            $patient_id = $appointment['patient_id'];
            $doctor_id = $appointment['doctor_id'];
            $appointment_date = $appointment['appointment_date'];
            $appointment_time = $appointment['appointment_time'];
            $status = $appointment['status'];
            $notes = $appointment['notes'];
        }
    } catch(PDOException $e) {
        $message = display_error("Hata: " . $e->getMessage());
    }
}

// Yeni randevu ekleme için varsayılan değerler
if ($action == 'add') {
    // URL'den hasta veya doktor ID'si alınmışsa onu kullan
    $patient_id = isset($_GET['patient_id']) ? $_GET['patient_id'] : '';
    $doctor_id = isset($_GET['doctor_id']) ? $_GET['doctor_id'] : '';
    $appointment_date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
    $appointment_time = '';
    $status = 0;
    $notes = '';
}

// Tüm hasta ve doktorları listele (form için)
try {
    // Hastalar
    $query = "SELECT id, tc_no, name, surname FROM patients ORDER BY name, surname";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $patients = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Doktorlar
    $query = "SELECT id, tc_no, name, surname, specialty FROM doctors WHERE status = 1 ORDER BY name, surname";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $doctors = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $message = display_error("Hata: " . $e->getMessage());
}

// Tarih aralığına göre randevuları getir (takvim için)
if ($view_type == 'calendar') {
    try {
        $query = "SELECT a.id, a.appointment_date, a.appointment_time, a.status,
                        p.name AS patient_name, p.surname AS patient_surname,
                        d.name AS doctor_name, d.surname AS doctor_surname
                 FROM appointments a
                 JOIN patients p ON a.patient_id = p.id
                 JOIN doctors d ON a.doctor_id = d.id
                 WHERE a.appointment_date BETWEEN :start_date AND :end_date
                 ORDER BY a.appointment_date, a.appointment_time";
        
        $stmt = $db->prepare($query);
        $stmt->bindParam(':start_date', $start_date);
        $stmt->bindParam(':end_date', $end_date);
        $stmt->execute();
        
        $calendar_appointments = array();
        
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $date = $row['appointment_date'];
            if (!isset($calendar_appointments[$date])) {
                $calendar_appointments[$date] = array();
            }
            
            $calendar_appointments[$date][] = array(
                'id' => $row['id'],
                'time' => format_time($row['appointment_time']),
                'patient' => $row['patient_name'] . ' ' . $row['patient_surname'],
                'doctor' => $row['doctor_name'] . ' ' . $row['doctor_surname'],
                'status' => $row['status']
            );
        }
    } catch(PDOException $e) {
        $message = display_error("Hata: " . $e->getMessage());
    }
}

// Belirli bir güne ait randevuları listele
if ($action == 'list' && $view_type == 'list') {
    try {
        $query = "SELECT a.id, a.appointment_date, a.appointment_time, a.status, a.notes,
                        p.name AS patient_name, p.surname AS patient_surname,
                        d.name AS doctor_name, d.surname AS doctor_surname, d.specialty
                 FROM appointments a
                 JOIN patients p ON a.patient_id = p.id
                 JOIN doctors d ON a.doctor_id = d.id
                 WHERE a.appointment_date = :selected_date
                 ORDER BY a.appointment_time";
        
        $stmt = $db->prepare($query);
        $stmt->bindParam(':selected_date', $selected_date);
        $stmt->execute();
        
        $appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        $message = display_error("Hata: " . $e->getMessage());
    }
}
?>

<?php echo $message; ?>

<?php if ($action == 'list'): ?>
<!-- Randevu Görünüm Seçenekleri -->
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="h4 mb-0">
            <?php if ($view_type == 'calendar'): ?>
                <?php echo date('F Y', strtotime("$year-$month-01")); ?> Takvimi
            <?php else: ?>
                <?php echo format_date($selected_date); ?> Tarihli Randevular
            <?php endif; ?>
        </h2>
    </div>
    <div class="d-flex">
        <a href="?action=add" class="btn btn-primary me-2">
            <i class="fas fa-plus"></i> Yeni Randevu
        </a>
        <div class="btn-group">
            <a href="?view=list<?php echo isset($_GET['date']) ? '&date='.$_GET['date'] : ''; ?>" class="btn btn-outline-primary <?php echo $view_type == 'list' ? 'active' : ''; ?>">
                <i class="fas fa-list"></i> Liste
            </a>
            <a href="?view=calendar<?php echo isset($_GET['month']) && isset($_GET['year']) ? '&month='.$_GET['month'].'&year='.$_GET['year'] : ''; ?>" class="btn btn-outline-primary <?php echo $view_type == 'calendar' ? 'active' : ''; ?>">
                <i class="fas fa-calendar-alt"></i> Takvim
            </a>
        </div>
    </div>
</div>

<?php if ($view_type == 'list'): ?>
<!-- Liste Görünümü -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 font-weight-bold text-primary">Randevu Listesi</h6>
        <div class="input-group" style="max-width: 200px;">
            <input type="date" class="form-control" id="dateFilter" value="<?php echo $selected_date; ?>">
            <button class="btn btn-primary" id="dateFilterBtn">
                <i class="fas fa-filter"></i>
            </button>
        </div>
    </div>
    <div class="card-body">
        <?php if (empty($appointments)): ?>
            <div class="alert alert-info">Bu tarih için randevu bulunmamaktadır.</div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="appointmentsTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>Saat</th>
                            <th>Hasta</th>
                            <th>Doktor</th>
                            <th>Bölüm</th>
                            <th>Durum</th>
                            <th>İşlemler</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($appointments as $appointment): ?>
                        <tr>
                            <td><?php echo format_time($appointment['appointment_time']); ?></td>
                            <td><?php echo $appointment['patient_name'] . ' ' . $appointment['patient_surname']; ?></td>
                            <td><?php echo $appointment['doctor_name'] . ' ' . $appointment['doctor_surname']; ?></td>
                            <td><?php echo $appointment['specialty']; ?></td>
                            <td>
                                <?php 
                                $status_class = '';
                                switch($appointment['status']) {
                                    case 0:
                                        $status_class = 'status-waiting';
                                        break;
                                    case 1:
                                        $status_class = 'status-completed';
                                        break;
                                    case 2:
                                        $status_class = 'status-cancelled';
                                        break;
                                    case 3:
                                        $status_class = 'status-missed';
                                        break;
                                }
                                ?>
                                <span class="<?php echo $status_class; ?>">
                                    <?php echo get_appointment_status($appointment['status']); ?>
                                </span>
                            </td>
                            <td class="table-actions">
                                <a href="?action=view&id=<?php echo $appointment['id']; ?>" class="btn btn-info btn-sm">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="?action=edit&id=<?php echo $appointment['id']; ?>" class="btn btn-primary btn-sm">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="?action=delete&id=<?php echo $appointment['id']; ?>" class="btn btn-danger btn-sm delete-btn">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Tarih filtreleme
    document.getElementById('dateFilterBtn').addEventListener('click', function() {
        const date = document.getElementById('dateFilter').value;
        if (date) {
            window.location.href = 'appointments.php?view=list&date=' + date;
        }
    });
    
    // Tarih inputlarını kontrol edecek fonksiyon
    function validateDateInputs() {
        const dateInputs = document.querySelectorAll('input[type="date"]');
        dateInputs.forEach(input => {
            input.addEventListener('input', function(e) {
                const value = e.target.value;
                // Eğer yıl 4 haneden fazlaysa, değeri son geçerli değere sıfırla
                if (value && value.split('-')[0].length > 4) {
                    // Kullanıcıya bir uyarı göster
                    alert('Yıl en fazla 4 haneli olabilir!');
                    // Son geçerli değeri bul (4 haneli yıl)
                    const year = value.split('-')[0].substring(0, 4);
                    const month = value.split('-')[1] || '01';
                    const day = value.split('-')[2] || '01';
                    e.target.value = `${year}-${month}-${day}`;
                }
            });
        });
    }
    
    // Doğrulama fonksiyonunu çağır
    validateDateInputs();
});
</script>

<?php else: ?>
<!-- Takvim Görünümü -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 font-weight-bold text-primary">Randevu Takvimi</h6>
        <div>
            <div class="btn-group">
                <a href="?view=calendar&month=<?php echo ($month == 1) ? 12 : $month-1; ?>&year=<?php echo ($month == 1) ? $year-1 : $year; ?>" class="btn btn-outline-primary">
                    <i class="fas fa-chevron-left"></i>
                </a>
                <a href="?view=calendar&month=<?php echo ($month == 12) ? 1 : $month+1; ?>&year=<?php echo ($month == 12) ? $year+1 : $year; ?>" class="btn btn-outline-primary">
                    <i class="fas fa-chevron-right"></i>
                </a>
            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="calendar-container">
            <div class="calendar-weekdays">
                <div class="calendar-weekday">Pazartesi</div>
                <div class="calendar-weekday">Salı</div>
                <div class="calendar-weekday">Çarşamba</div>
                <div class="calendar-weekday">Perşembe</div>
                <div class="calendar-weekday">Cuma</div>
                <div class="calendar-weekday">Cumartesi</div>
                <div class="calendar-weekday">Pazar</div>
            </div>
            <div class="calendar-days" id="calendarDays">
                <!-- Takvim günleri JavaScript ile oluşturulacak -->
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const year = <?php echo $year; ?>;
    const month = <?php echo $month; ?>; // 1-12
    const today = new Date();
    
    // PHP'den gelen randevu verilerini JavaScript'e aktar
    const appointments = <?php echo json_encode($calendar_appointments); ?>;
    
    // Takvimi oluştur
    createCalendarDays(year, month, appointments);
});
</script>

<?php endif; ?>

<?php elseif ($action == 'add' || $action == 'edit'): ?>
<!-- Hasta Ceza Uyarısı -->
<?php
if ($action == 'add' && !empty($patient_id)) {
    try {
        $penalty_query = "SELECT penalty_until FROM patients WHERE id = :patient_id";
        $penalty_stmt = $db->prepare($penalty_query);
        $penalty_stmt->bindParam(':patient_id', $patient_id);
        $penalty_stmt->execute();
        
        $patient_data = $penalty_stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($patient_data && !empty($patient_data['penalty_until'])) {
            $today = date('Y-m-d');
            $penalty_date = $patient_data['penalty_until'];
            
            if (strtotime($penalty_date) > strtotime($today)) {
                echo '<div class="alert alert-warning mb-4"><i class="fas fa-exclamation-triangle"></i> Bu hasta ' . format_date($penalty_date) . ' tarihine kadar cezalıdır ve bu tarihten öncesi için randevu alamaz.</div>';
            }
        }
    } catch(PDOException $e) {
        // Hata durumunda sessizce geç
    }
}
?>
<!-- Randevu Ekle/Düzenle Formu -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 font-weight-bold text-primary">
            <?php echo $action == 'add' ? 'Yeni Randevu Ekle' : 'Randevu Düzenle'; ?>
        </h6>
    </div>
    <div class="card-body">
        <?php if (isset($message)) echo $message; ?>
        
        <form method="post" action="appointments.php?action=<?php echo $action; ?><?php echo ($action == 'edit') ? '&id=' . $_GET['id'] : ''; ?>">
            <!-- Randevu detayları -->
            <div class="row">
                <!-- Hasta seçimi -->
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="patient_id">Hasta</label>
                        <select class="form-control" id="patient_id" name="patient_id" required>
                            <option value="">Hasta Seçin</option>
                            <?php foreach ($patients as $patient): ?>
                            <option value="<?php echo $patient['id']; ?>" <?php echo (isset($patient_id) && $patient_id == $patient['id']) ? 'selected' : ''; ?>>
                                <?php echo $patient['name'] . ' ' . $patient['surname'] . ' (' . $patient['tc_no'] . ')'; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <!-- Doktor seçimi -->
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="doctor_id">Doktor</label>
                        <select class="form-control" id="doctor_id" name="doctor_id" required>
                            <option value="">Doktor Seçin</option>
                            <?php foreach ($doctors as $doctor): ?>
                            <option value="<?php echo $doctor['id']; ?>" <?php echo (isset($doctor_id) && $doctor_id == $doctor['id']) ? 'selected' : ''; ?>>
                                <?php echo $doctor['name'] . ' ' . $doctor['surname'] . ' (' . $doctor['specialty'] . ')'; ?>
                            </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
            </div>
            
            <div class="row mt-3">
                <!-- Randevu Tarihi -->
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="appointment_date" class="form-label">Randevu Tarihi *</label>
                        <input type="date" class="form-control" id="appointment_date" name="appointment_date" 
                            <?php if ($action == 'add'): ?>
                            min="<?php echo date('Y-m-d'); ?>"
                            <?php endif; ?>
                            value="<?php echo isset($appointment_date) ? $appointment_date : ''; ?>" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="appointment_time">Randevu Saati</label>
                        <select class="form-control" id="appointment_time" name="appointment_time" required>
                            <option value="">Saat Seçin</option>
                            <?php if ($action == 'edit'): ?>
                            <option value="<?php echo $appointment_time; ?>" selected>
                                <?php echo format_time($appointment_time); ?>
                            </option>
                            <?php endif; ?>
                        </select>
                    </div>
                </div>
            </div>
            
            <?php if ($action == 'edit'): ?>
            <div class="form-group">
                <label for="status">Durum</label>
                <select class="form-control" id="status" name="status">
                    <option value="0" <?php echo (isset($status) && $status == 0) ? 'selected' : ''; ?>>Bekliyor</option>
                    <option value="1" <?php echo (isset($status) && $status == 1) ? 'selected' : ''; ?>>Tamamlandı</option>
                    <option value="2" <?php echo (isset($status) && $status == 2) ? 'selected' : ''; ?>>İptal</option>
                    <option value="3" <?php echo (isset($status) && $status == 3) ? 'selected' : ''; ?>>Gelmedi</option>
                </select>
            </div>
            <?php endif; ?>
            
            <div class="form-group">
                <label for="notes">Notlar</label>
                <textarea class="form-control" id="notes" name="notes" rows="3"><?php echo isset($notes) ? $notes : ''; ?></textarea>
            </div>
            
            <button type="submit" class="btn btn-primary">
                <?php echo $action == 'add' ? 'Randevu Oluştur' : 'Randevuyu Güncelle'; ?>
            </button>
            <a href="appointments.php" class="btn btn-secondary">İptal</a>
        </form>
    </div>
</div>

<?php elseif ($action == 'view' && isset($appointment)): ?>
<!-- Randevu Detay Görünümü -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
        <h6 class="m-0 font-weight-bold text-primary">Randevu Detayları</h6>
        <div>
            <a href="?action=edit&id=<?php echo $appointment['id']; ?>" class="btn btn-primary btn-sm">
                <i class="fas fa-edit"></i> Düzenle
            </a>
            <a href="appointments.php" class="btn btn-secondary btn-sm">
                <i class="fas fa-arrow-left"></i> Listeye Dön
            </a>
        </div>
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-md-6">
                <h5 class="mb-3">Randevu Bilgileri</h5>
                <table class="table table-bordered">
                    <tr>
                        <th style="width: 30%">Tarih:</th>
                        <td><?php echo format_date($appointment['appointment_date']); ?></td>
                    </tr>
                    <tr>
                        <th>Saat:</th>
                        <td><?php echo format_time($appointment['appointment_time']); ?></td>
                    </tr>
                    <tr>
                        <th>Durum:</th>
                        <td>
                            <?php 
                            $status_class = '';
                            switch($appointment['status']) {
                                case 0:
                                    $status_class = 'status-waiting';
                                    break;
                                case 1:
                                    $status_class = 'status-completed';
                                    break;
                                case 2:
                                    $status_class = 'status-cancelled';
                                    break;
                                case 3:
                                    $status_class = 'status-missed';
                                    break;
                            }
                            ?>
                            <span class="<?php echo $status_class; ?>">
                                <?php echo get_appointment_status($appointment['status']); ?>
                            </span>
                            
                            <div class="mt-2">
                                <?php if ($appointment['status'] != 0): ?>
                                <a href="?action=update_status&id=<?php echo $appointment['id']; ?>&status=0" class="btn btn-warning btn-sm">
                                    Beklemeye Al
                                </a>
                                <?php endif; ?>
                                
                                <?php if ($appointment['status'] != 1): ?>
                                <a href="?action=update_status&id=<?php echo $appointment['id']; ?>&status=1" class="btn btn-success btn-sm">
                                    Tamamlandı
                                </a>
                                <?php endif; ?>
                                
                                <?php if ($appointment['status'] != 2): ?>
                                <a href="?action=update_status&id=<?php echo $appointment['id']; ?>&status=2" class="btn btn-danger btn-sm">
                                    İptal Et
                                </a>
                                <?php endif; ?>
                                
                                <?php if ($appointment['status'] != 3): ?>
                                <a href="?action=update_status&id=<?php echo $appointment['id']; ?>&status=3" class="btn btn-warning btn-sm">
                                    Gelmedi
                                </a>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th>Notlar:</th>
                        <td><?php echo nl2br($appointment['notes'] ? $appointment['notes'] : '-'); ?></td>
                    </tr>
                </table>
            </div>
            <div class="col-md-6">
                <div class="row">
                    <div class="col-md-12">
                        <h5 class="mb-3">Hasta Bilgileri</h5>
                        <table class="table table-bordered">
                            <tr>
                                <th style="width: 30%">TC No:</th>
                                <td><?php echo $appointment['patient_tc']; ?></td>
                            </tr>
                            <tr>
                                <th>Ad Soyad:</th>
                                <td>
                                    <?php echo $appointment['patient_name'] . ' ' . $appointment['patient_surname']; ?>
                                    <a href="patients.php?action=view&id=<?php echo $appointment['patient_id']; ?>" class="btn btn-info btn-sm ml-2">
                                        <i class="fas fa-external-link-alt"></i>
                                    </a>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <div class="col-md-12 mt-4">
                        <h5 class="mb-3">Doktor Bilgileri</h5>
                        <table class="table table-bordered">
                            <tr>
                                <th style="width: 30%">TC No:</th>
                                <td><?php echo $appointment['doctor_tc']; ?></td>
                            </tr>
                            <tr>
                                <th>Ad Soyad:</th>
                                <td>
                                    <?php echo $appointment['doctor_name'] . ' ' . $appointment['doctor_surname']; ?>
                                    <a href="doctors.php?action=view&id=<?php echo $appointment['doctor_id']; ?>" class="btn btn-info btn-sm ml-2">
                                        <i class="fas fa-external-link-alt"></i>
                                    </a>
                                </td>
                            </tr>
                            <tr>
                                <th>Uzmanlık:</th>
                                <td><?php echo $appointment['specialty']; ?></td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Muayene Oluştur Butonu -->
        <?php if ($appointment['status'] == 0): ?>
        <div class="mt-4">
            <a href="examinations.php?action=add&appointment_id=<?php echo $appointment['id']; ?>" class="btn btn-success">
                <i class="fas fa-stethoscope"></i> Muayene Oluştur
            </a>
        </div>
        <?php endif; ?>
        
        <!-- Mevcut Muayeneyi Görüntüle -->
        <?php
        try {
            $query = "SELECT id FROM examinations WHERE appointment_id = :appointment_id LIMIT 1";
            $stmt = $db->prepare($query);
            $stmt->bindParam(':appointment_id', $appointment['id']);
            $stmt->execute();
            
            if ($stmt->rowCount() > 0) {
                $examination = $stmt->fetch(PDO::FETCH_ASSOC);
                ?>
                <div class="mt-4">
                    <a href="examinations.php?action=view&id=<?php echo $examination['id']; ?>" class="btn btn-primary">
                        <i class="fas fa-file-medical"></i> Muayene Kaydını Görüntüle
                    </a>
                </div>
                <?php
            }
        } catch(PDOException $e) {
            // Hata gösterme
        }
        ?>
    </div>
</div>
<?php endif; ?>

<?php
// Footer'ı dahil et
require_once 'templates/footer.php';
?> 