<?php
// Prevent any output before headers
ob_start();

date_default_timezone_set('Asia/Colombo');

// Error handling
error_reporting(E_ALL);
ini_set('display_errors', 0); // Don't display errors in output

try {
    include '../config.php';
    
    // Get parameters
    $start_date = $_GET['start_date'] ?? date('Y-m-d');
    $end_date = $_GET['end_date'] ?? date('Y-m-d');
    $report_type = $_GET['report_type'] ?? 'overview';
    
    // Validate dates
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date) || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_date)) {
        throw new Exception('Invalid date format');
    }
    
    // Clear any previous output
    ob_clean();
    
    // Set headers for CSV download
    header('Content-Type: text/csv; charset=UTF-8');
    header('Content-Disposition: attachment; filename="' . $report_type . '_report_' . $start_date . '_to_' . $end_date . '.csv"');
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
    
    // Open output stream
    $output = fopen('php://output', 'w');

if ($report_type === 'overview') {
    // Overview Report
    fputcsv($output, ['Sales Overview Report']);
    fputcsv($output, ['Period: ' . $start_date . ' to ' . $end_date]);
    fputcsv($output, []); // Empty line
    
    // Get overview data
    $stmt = $conn->prepare("
        SELECT 
            DATE(sale_date) as sale_date,
            COUNT(*) as total_sales,
            SUM(total_amount) as daily_revenue,
            AVG(total_amount) as avg_sale_amount
        FROM sales 
        WHERE DATE(sale_date) BETWEEN ? AND ?
        GROUP BY DATE(sale_date)
        ORDER BY sale_date
    ");
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // Headers
    fputcsv($output, ['Date', 'Total Sales', 'Daily Revenue (Rs)', 'Average Sale (Rs)']);
    
    $total_sales = 0;
    $total_revenue = 0;
    
    while ($row = $result->fetch_assoc()) {
        fputcsv($output, [
            $row['sale_date'],
            $row['total_sales'],
            number_format($row['daily_revenue'], 2),
            number_format($row['avg_sale_amount'], 2)
        ]);
        $total_sales += $row['total_sales'];
        $total_revenue += $row['daily_revenue'];
    }
    
    // Summary
    fputcsv($output, []); // Empty line
    fputcsv($output, ['SUMMARY']);
    fputcsv($output, ['Total Sales Count', $total_sales]);
    fputcsv($output, ['Total Revenue (Rs)', number_format($total_revenue, 2)]);
    fputcsv($output, ['Average Sale (Rs)', $total_sales > 0 ? number_format($total_revenue / $total_sales, 2) : '0.00']);

} elseif ($report_type === 'detailed') {
    // Detailed Sales Report
    fputcsv($output, ['Detailed Sales Report']);
    fputcsv($output, ['Period: ' . $start_date . ' to ' . $end_date]);
    fputcsv($output, []); // Empty line
    
    $stmt = $conn->prepare("
        SELECT 
            s.id as receipt_no,
            s.sale_date,
            COALESCE(c.name, 'Walk-in Customer') as customer_name,
            c.phone as customer_phone,
            s.total_amount,
            s.payment_method,
            s.discount,
            u.username as cashier
        FROM sales s
        LEFT JOIN customers c ON s.customer_id = c.id
        LEFT JOIN users u ON s.user_id = u.id
        WHERE DATE(s.sale_date) BETWEEN ? AND ?
        ORDER BY s.sale_date DESC
    ");
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // Headers
    fputcsv($output, ['Receipt No', 'Date & Time', 'Customer', 'Phone', 'Amount (Rs)', 'Payment Method', 'Discount (%)', 'Cashier']);
    
        while ($row = $result->fetch_assoc()) {
        fputcsv($output, [
            $row['receipt_no'],
            $row['sale_date'],
            $row['customer_name'],
            $row['customer_phone'] ?? '',
            number_format($row['total_amount'], 2),
            ucfirst($row['payment_method']),
            $row['discount'],
            $row['cashier'] ?? 'N/A'
        ]);
    }} elseif ($report_type === 'products') {
    // Product Sales Report
    fputcsv($output, ['Product Sales Report']);
    fputcsv($output, ['Period: ' . $start_date . ' to ' . $end_date]);
    fputcsv($output, []); // Empty line
    
    $stmt = $conn->prepare("
        SELECT 
            p.name as product_name,
            p.category,
            p.price as unit_price,
            SUM(si.quantity) as total_sold,
            SUM(si.total_price) as total_revenue
        FROM sale_items si
        JOIN products p ON si.product_id = p.id
        JOIN sales s ON si.sale_id = s.id
        WHERE DATE(s.sale_date) BETWEEN ? AND ?
        AND si.exchanged != 1  -- Exclude exchanged items
        GROUP BY si.product_id, p.name, p.category, p.price
        ORDER BY total_revenue DESC
    ");
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // Headers
    fputcsv($output, ['Product Name', 'Category', 'Unit Price (Rs)', 'Quantity Sold', 'Total Revenue (Rs)']);
    
    while ($row = $result->fetch_assoc()) {
        fputcsv($output, [
            $row['product_name'],
            $row['category'],
            number_format($row['unit_price'], 2),
            $row['total_sold'],
            number_format($row['total_revenue'], 2)
        ]);
    }

} elseif ($report_type === 'customers') {
    // Customer Report
    fputcsv($output, ['Customer Report']);
    fputcsv($output, ['Period: ' . $start_date . ' to ' . $end_date]);
    fputcsv($output, []); // Empty line
    
    $stmt = $conn->prepare("
        SELECT 
            COALESCE(c.name, 'Walk-in Customer') as customer_name,
            c.phone,
            c.email,
            COUNT(s.id) as total_purchases,
            SUM(s.total_amount) as total_spent,
            MAX(s.sale_date) as last_purchase
        FROM sales s
        LEFT JOIN customers c ON s.customer_id = c.id
        WHERE DATE(s.sale_date) BETWEEN ? AND ?
        GROUP BY s.customer_id, c.name, c.phone, c.email
        ORDER BY total_spent DESC
    ");
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // Headers
    fputcsv($output, ['Customer Name', 'Phone', 'Email', 'Total Purchases', 'Total Spent (Rs)', 'Last Purchase']);
    
    while ($row = $result->fetch_assoc()) {
        fputcsv($output, [
            $row['customer_name'],
            $row['phone'] ?? '',
            $row['email'] ?? '',
            $row['total_purchases'],
            number_format($row['total_spent'], 2),
            $row['last_purchase'] ? date('Y-m-d H:i', strtotime($row['last_purchase'])) : ''
        ]);
    }

} elseif ($report_type === 'inventory') {
    // Inventory Report
    fputcsv($output, ['Inventory Report']);
    fputcsv($output, ['Generated on: ' . date('Y-m-d H:i:s')]);
    fputcsv($output, []); // Empty line
    
    $stmt = $conn->prepare("
        SELECT 
            p.name,
            p.category,
            p.price,
            p.stock,
            p.stock * p.price as stock_value,
            COALESCE(sold.total_sold, 0) as sold_in_period
        FROM products p
        LEFT JOIN (
            SELECT 
                si.product_id,
                SUM(si.quantity) as total_sold
            FROM sale_items si
            JOIN sales s ON si.sale_id = s.id
            WHERE DATE(s.sale_date) BETWEEN ? AND ?
            AND si.exchanged != 1
            GROUP BY si.product_id
        ) sold ON p.id = sold.product_id
        ORDER BY p.category, p.name
    ");
    $stmt->bind_param("ss", $start_date, $end_date);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // Headers
    fputcsv($output, ['Product Name', 'Category', 'Unit Price (Rs)', 'Current Stock', 'Stock Value (Rs)', 'Sold in Period']);
    
    $total_stock_value = 0;
    while ($row = $result->fetch_assoc()) {
        fputcsv($output, [
            $row['name'],
            $row['category'],
            number_format($row['price'], 2),
            $row['stock'],
            number_format($row['stock_value'], 2),
            $row['sold_in_period']
        ]);
        $total_stock_value += $row['stock_value'];
    }
    
    // Summary
    fputcsv($output, []); // Empty line
    fputcsv($output, ['SUMMARY']);
    fputcsv($output, ['Total Stock Value (Rs)', number_format($total_stock_value, 2)]);

} else {
    fputcsv($output, ['Error: Invalid report type']);
}

// Close output stream
fclose($output);

} catch (Exception $e) {
    // Clear output buffer and send error response
    ob_clean();
    header('Content-Type: text/plain');
    echo 'Error generating report: ' . $e->getMessage();
} catch (Error $e) {
    ob_clean();
    header('Content-Type: text/plain');
    echo 'Fatal error: ' . $e->getMessage();
}

exit;
?>
