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

// Check if admin is logged in
if (!isset($_SESSION['admin_logged_in']) || $_SESSION['admin_logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

$pdo = getDBConnection();

// Get filters from GET request
$status_filter = $_GET['status'] ?? 'all';
$date_filter = $_GET['date'] ?? '';
$search_query = $_GET['search'] ?? '';
$consultation_filter = $_GET['consultation_type'] ?? 'all';
$amount_min = $_GET['amount_min'] ?? '';
$amount_max = $_GET['amount_max'] ?? '';

$where_conditions = [];
$params = [];

if ($status_filter !== 'all') {
    $where_conditions[] = "a.status = ?";
    $params[] = $status_filter;
}

if ($date_filter) {
    $where_conditions[] = "a.appointment_date = ?";
    $params[] = $date_filter;
}

if ($search_query) {
    $where_conditions[] = "(u.name LIKE ? OR u.mobile LIKE ? OR u.city LIKE ?)";
    $search_param = "%$search_query%";
    $params[] = $search_param;
    $params[] = $search_param;
    $params[] = $search_param;
}

if ($consultation_filter !== 'all') {
    $where_conditions[] = "a.consultation_type = ?";
    $params[] = $consultation_filter;
}

if ($amount_min !== '') {
    $where_conditions[] = "a.amount >= ?";
    $params[] = (float)$amount_min;
}

if ($amount_max !== '') {
    $where_conditions[] = "a.amount <= ?";
    $params[] = (float)$amount_max;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get appointments
$query = "
    SELECT 
        a.id, a.appointment_date, a.time_slot, a.consultation_type, 
        a.status, a.amount, a.created_at,
        u.name as user_name, u.mobile as user_mobile, u.city as user_city
    FROM appointments a
    INNER JOIN users u ON a.user_id = u.id
    $where_clause
    ORDER BY a.appointment_date DESC, a.time_slot ASC
";

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$appointments = $stmt->fetchAll();

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

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

// Output the column headings
fputcsv($output, ['ID', 'Date', 'Time', 'Type', 'Status', 'Amount', 'Name', 'Mobile', 'City', 'Booked At']);

// Loop over the rows, outputting them
foreach ($appointments as $row) {
    fputcsv($output, [
        $row['id'],
        $row['appointment_date'],
        $row['time_slot'],
        $row['consultation_type'],
        $row['status'],
        $row['amount'],
        $row['user_name'],
        $row['user_mobile'],
        $row['user_city'],
        $row['created_at']
    ]);
}

fclose($output);
exit;
