<?php
// modules/sales/ajax_export_sales.php - SIMPLIFIED VERSION
session_start();
require_once '../assets/db_connect.php';

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

$shop_id = $_SESSION['user']['shop_id'] ?? 0;

if ($shop_id == 0) {
    // Return error file
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="error.csv"');
    echo "Error,Message\n";
    echo "Session Error,Shop session missing. Please login again.\n";
    exit;
}

// Get parameters from GET or POST
$from_date = $_REQUEST['from_date'] ?? date('Y-m-d', strtotime('-30 days'));
$to_date = $_REQUEST['to_date'] ?? date('Y-m-d');
$status = $_REQUEST['status'] ?? '';
$payment_method = $_REQUEST['payment_method'] ?? '';

// Build WHERE clause
$where_clauses = ["s.shop_id = ?", "DATE(s.sale_date) BETWEEN ? AND ?"];
$params = [$shop_id, $from_date, $to_date];

if (!empty($status)) {
    $where_clauses[] = "s.status = ?";
    $params[] = $status;
}

if (!empty($payment_method)) {
    $where_clauses[] = "p.method = ?";
    $params[] = $payment_method;
}

$where_sql = !empty($where_clauses) ? "WHERE " . implode(" AND ", $where_clauses) : "";

// Simplified query
$sql = "SELECT 
            s.id,
            s.invoice_no,
            DATE(s.sale_date) as sale_date,
            COALESCE(c.name, 'Walk-in') as customer,
            s.total,
            s.paid,
            (s.total - s.paid) as due,
            s.status
        FROM sales s
        LEFT JOIN customers c ON s.customer_id = c.id
        LEFT JOIN payments p ON s.id = p.sale_id
        $where_sql
        GROUP BY s.id
        ORDER BY s.sale_date DESC";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $sales = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Generate filename
    $filename = 'sales_' . date('Y-m-d_His') . '.csv';
    
    // Set headers
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Pragma: no-cache');
    header('Expires: 0');
    
    // Open output stream
    $output = fopen('php://output', 'w');
    
    // Write headers
    fputcsv($output, ['ID', 'Invoice No', 'Date', 'Customer', 'Total', 'Paid', 'Due', 'Status']);
    
    // Write data
    foreach ($sales as $sale) {
        fputcsv($output, [
            $sale['id'],
            $sale['invoice_no'],
            $sale['sale_date'],
            $sale['customer'],
            $sale['total'],
            $sale['paid'],
            $sale['due'],
            ucfirst($sale['status'])
        ]);
    }
    
    fclose($output);
    
} catch (Exception $e) {
    // Return error CSV
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="error.csv"');
    echo "Error,Message\n";
    echo "Export Error," . $e->getMessage() . "\n";
}
exit;
?>