<?php
session_start();
include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$doctor_id = $_SESSION['user_id'];

// Get doctor name
$doctor_query = "SELECT u.full_name FROM users u WHERE u.user_id = ?";
$doctor_stmt = $conn->prepare($doctor_query);
$doctor_stmt->bind_param("i", $doctor_id);
$doctor_stmt->execute();
$doctor_result = $doctor_stmt->get_result()->fetch_assoc();
$doctor_name = $doctor_result['full_name'];

// Fetch appointments
$query = "SELECT 
    a.appointment_number,
    a.appointment_date,
    a.appointment_time,
    a.appointment_type,
    a.status,
    a.chief_complaint,
    a.booking_source,
    p.patient_number,
    p.first_name,
    p.last_name,
    p.phone_number,
    p.email,
    p.date_of_birth,
    p.gender
FROM appointments a
INNER JOIN patients p ON a.patient_id = p.patient_id
WHERE a.doctor_id = ?
ORDER BY a.appointment_date DESC, a.appointment_time DESC";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$result = $stmt->get_result();

// Set headers for CSV download
$filename = "My_Appointments_" . date('Y-m-d_His') . ".csv";
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');

// Create file pointer
$output = fopen('php://output', 'w');

// Add BOM for Excel UTF-8 recognition
fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));

// Add title row
fputcsv($output, ['My Appointments Report - Dr. ' . $doctor_name]);
fputcsv($output, ['Generated: ' . date('d/m/Y H:i:s')]);
fputcsv($output, []); // Empty row

// Add column headers
fputcsv($output, [
    'Appointment No',
    'Date',
    'Time',
    'Patient No',
    'Patient Name',
    'Gender',
    'Age',
    'Phone',
    'Email',
    'Type',
    'Booking Source',
    'Chief Complaint',
    'Status'
]);

// Add data rows
while ($row = $result->fetch_assoc()) {
    // Calculate age
    $age = '';
    if ($row['date_of_birth']) {
        $dob = new DateTime($row['date_of_birth']);
        $now = new DateTime();
        $age = $dob->diff($now)->y . ' years';
    }
    
    // Format patient name
    $patient_name = $row['first_name'] . ' ' . $row['last_name'];
    
    // Format date and time
    $date = date('d/m/Y', strtotime($row['appointment_date']));
    $time = date('h:i A', strtotime($row['appointment_time']));
    
    fputcsv($output, [
        $row['appointment_number'],
        $date,
        $time,
        $row['patient_number'],
        $patient_name,
        $row['gender'],
        $age,
        $row['phone_number'],
        $row['email'],
        str_replace('_', ' ', $row['appointment_type']),
        str_replace('_', ' ', $row['booking_source']),
        $row['chief_complaint'],
        str_replace('_', ' ', $row['status'])
    ]);
}

// Add summary row
fputcsv($output, []); // Empty row
fputcsv($output, ['Total Appointments', $result->num_rows]);

fclose($output);
exit();
?>