<?php
/**
 * Export Doctors to CSV
 * Export filtered doctor list to CSV file
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';

requireAdmin();

$pdo = getDB();

// Get filter parameters (same as index.php)
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? 'all';
$plan = $_GET['plan'] ?? 'all';

// Build query
$whereConditions = ["u.role = 'doctor'"];
$params = [];

if (!empty($search)) {
    $whereConditions[] = "(u.full_name LIKE ? OR u.email LIKE ? OR u.username LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

if ($status == 'active') {
    $whereConditions[] = "u.is_active = 1";
} elseif ($status == 'inactive') {
    $whereConditions[] = "u.is_active = 0";
}

if ($plan != 'all') {
    $whereConditions[] = "s.plan_type = ?";
    $params[] = $plan;
}

$whereClause = implode(" AND ", $whereConditions);

// Get doctors data
$sql = "SELECT u.id, u.username, u.email, u.full_name, u.is_active, u.created_at, u.last_login,
        s.plan_type, s.start_date, s.end_date, s.amount,
        (SELECT COUNT(*) FROM cases WHERE user_id = u.id) as total_cases
        FROM users u 
        LEFT JOIN subscriptions s ON u.id = s.user_id AND s.is_active = 1
        WHERE $whereClause
        ORDER BY u.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$doctors = $stmt->fetchAll();

// Prepare CSV data
$csvData = [];
$csvData[] = [
    'ID', 'Username', 'Full Name', 'Email', 'Status', 
    'Subscription Plan', 'Amount', 'Start Date', 'End Date',
    'Total Cases', 'Joined Date', 'Last Login'
];

foreach ($doctors as $doctor) {
    $csvData[] = [
        $doctor['id'],
        $doctor['username'],
        $doctor['full_name'],
        $doctor['email'],
        $doctor['is_active'] ? 'Active' : 'Inactive',
        $doctor['plan_type'] ?? 'None',
        $doctor['amount'] ?? 0,
        $doctor['start_date'] ?? '',
        $doctor['end_date'] ?? '',
        $doctor['total_cases'],
        date(DISPLAY_DATE_FORMAT, strtotime($doctor['created_at'])),
        $doctor['last_login'] ? date(DISPLAY_DATE_TIME_FORMAT, strtotime($doctor['last_login'])) : 'Never'
    ];
}

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

// Create output stream
$output = fopen('php://output', 'w');
foreach ($csvData as $row) {
    fputcsv($output, $row);
}
fclose($output);
exit;
?>