<?php
session_start();
include_once('includes/config.php');

if (strlen($_SESSION["aid"]) == 0) {
    header('location:logout.php');
    exit;
}

// Get filter parameters
$status = isset($_GET['status']) ? $_GET['status'] : 'all';
$fromDate = isset($_GET['from']) ? $_GET['from'] : '';
$toDate = isset($_GET['to']) ? $_GET['to'] : '';

// Build query
$query = "SELECT o.orderNumber, o.totalAmount, o.orderStatus, o.orderDate, 
          ud.name as customerName, u.email, ud.contactno 
          FROM orders o 
          JOIN users u ON o.userId = u.id 
          LEFT JOIN user_details ud ON ud.user_id = u.id 
          WHERE 1=1";

if ($status != 'all') {
    $query .= " AND o.orderStatus = '$status'";
}

if ($fromDate && $toDate) {
    $query .= " AND DATE(o.orderDate) BETWEEN '$fromDate' AND '$toDate'";
}

$query .= " ORDER BY o.orderDate DESC";

$result = mysqli_query($con, $query);

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

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

// Add CSV headers
fputcsv($output, ['Order Number', 'Customer Name', 'Email', 'Contact', 'Amount', 'Status', 'Order Date']);

// Add data rows
while ($row = mysqli_fetch_assoc($result)) {
    fputcsv($output, [
        $row['orderNumber'],
        $row['customerName'] ? $row['customerName'] : 'N/A',
        $row['email'],
        $row['contactno'] ? $row['contactno'] : 'N/A',
        '$' . number_format($row['totalAmount'], 2),
        $row['orderStatus'] ? $row['orderStatus'] : 'Pending',
        date('M d, Y h:i A', strtotime($row['orderDate']))
    ]);
}

fclose($output);
exit;
?>
