<?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 filter parameters
$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 for PDF
$query = "
    SELECT 
        a.*, 
        u.name as user_name, 
        u.mobile as user_mobile,
        u.city as user_city
    FROM appointments a
    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();

// Generate HTML for PDF
$html = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Appointments Report</title>
    <style>
        body { font-family: Arial, sans-serif; font-size: 12px; }
        .header { text-align: center; margin-bottom: 20px; border-bottom: 2px solid #333; padding-bottom: 10px; }
        .header h1 { margin: 0; color: #333; }
        .header p { margin: 5px 0; color: #666; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f2f2f2; font-weight: bold; }
        .status-pending { color: #856404; background-color: #fff3cd; }
        .status-confirmed { color: #155724; background-color: #d4edda; }
        .status-cancelled { color: #721c24; background-color: #f8d7da; }
        .status-completed { color: #0c5460; background-color: #d1ecf1; }
        .summary { margin: 20px 0; padding: 15px; background-color: #f8f9fa; border-radius: 5px; }
        .summary h3 { margin-top: 0; color: #333; }
        .summary p { margin: 5px 0; }
    </style>
</head>
<body>
    <div class="header">
        <h1>Appointments Report</h1>
        <p>Generated on: ' . date('d M Y H:i:s') . '</p>
        <p>Total Appointments: ' . count($appointments) . '</p>
    </div>';

// Add filter summary
if ($status_filter !== 'all' || $date_filter || $search_query || $consultation_filter !== 'all' || $amount_min || $amount_max) {
    $html .= '<div class="summary">
        <h3>Applied Filters:</h3>';
    if ($status_filter !== 'all') $html .= '<p><strong>Status:</strong> ' . ucfirst($status_filter) . '</p>';
    if ($date_filter) $html .= '<p><strong>Date:</strong> ' . $date_filter . '</p>';
    if ($search_query) $html .= '<p><strong>Search:</strong> ' . htmlspecialchars($search_query) . '</p>';
    if ($consultation_filter !== 'all') $html .= '<p><strong>Type:</strong> ' . ucfirst(str_replace('_', ' ', $consultation_filter)) . '</p>';
    if ($amount_min || $amount_max) {
        $html .= '<p><strong>Amount Range:</strong> ';
        if ($amount_min && $amount_max) $html .= '₹' . $amount_min . ' - ₹' . $amount_max;
        elseif ($amount_min) $html .= 'Min: ₹' . $amount_min;
        elseif ($amount_max) $html .= 'Max: ₹' . $amount_max;
        $html .= '</p>';
    }
    $html .= '</div>';
}

$html .= '
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Mobile</th>
                <th>City</th>
                <th>Date</th>
                <th>Time</th>
                <th>Type</th>
                <th>Status</th>
                <th>Amount</th>
            </tr>
        </thead>
        <tbody>';

foreach ($appointments as $appointment) {
    $types = [
        'office_meeting' => 'Office Meeting',
        'video_call' => 'Video Call',
        'audio_call' => 'Audio Call'
    ];
    
    $html .= '<tr>
        <td>' . $appointment['id'] . '</td>
        <td>' . htmlspecialchars($appointment['user_name']) . '</td>
        <td>' . htmlspecialchars($appointment['user_mobile']) . '</td>
        <td>' . htmlspecialchars($appointment['user_city']) . '</td>
        <td>' . date('d M Y', strtotime($appointment['appointment_date'])) . '</td>
        <td>' . $appointment['time_slot'] . '</td>
        <td>' . ($types[$appointment['consultation_type']] ?? $appointment['consultation_type']) . '</td>
        <td class="status-' . $appointment['status'] . '">' . ucfirst($appointment['status']) . '</td>
        <td>₹' . number_format($appointment['amount']) . '</td>
    </tr>';
}

$html .= '
        </tbody>
    </table>
</body>
</html>';

// Set headers for PDF download
header('Content-Type: text/html');
header('Content-Disposition: attachment; filename="appointments_' . date('Y-m-d') . '.html"');

// Output HTML
echo $html;
?> 