72 lines
1.7 KiB
PHP
72 lines
1.7 KiB
PHP
<?php
|
|
require_once 'includes/auth.php';
|
|
require_login();
|
|
|
|
require_once 'db/config.php';
|
|
|
|
$pdo = db();
|
|
|
|
// Filter logic
|
|
$start_date = $_GET['start_date'] ?? '';
|
|
$end_date = $_GET['end_date'] ?? '';
|
|
$payment_method = $_GET['payment_method'] ?? '';
|
|
|
|
$sql = "SELECT s.id, s.sale_date, s.total_amount, s.payment_method, GROUP_CONCAT(CONCAT(p.name, ' (', si.quantity, ' x $', si.price, ')')) AS items
|
|
FROM sales s
|
|
JOIN sale_items si ON s.id = si.sale_id
|
|
JOIN products p ON si.product_id = p.id";
|
|
|
|
$conditions = [];
|
|
$params = [];
|
|
|
|
if ($start_date) {
|
|
$conditions[] = "s.sale_date >= ?";
|
|
$params[] = $start_date . ' 00:00:00';
|
|
}
|
|
if ($end_date) {
|
|
$conditions[] = "s.sale_date <= ?";
|
|
$params[] = $end_date . ' 23:59:59';
|
|
}
|
|
if ($payment_method) {
|
|
$conditions[] = "s.payment_method = ?";
|
|
$params[] = $payment_method;
|
|
}
|
|
|
|
if (count($conditions) > 0) {
|
|
$sql .= " WHERE " . implode(' AND ', $conditions);
|
|
}
|
|
|
|
$sql .= " GROUP BY s.id ORDER BY s.sale_date DESC";
|
|
|
|
$stmt = $pdo->prepare($sql);
|
|
$stmt->execute($params);
|
|
$sales = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
|
|
// CSV generation
|
|
$filename = "sales_report_" . date('Y-m-d') . ".csv";
|
|
|
|
header('Content-Type: text/csv');
|
|
header('Content-Disposition: attachment; filename="' . $filename . '"');
|
|
|
|
$output = fopen('php://output', 'w');
|
|
|
|
// Add BOM to support UTF-8 in Excel
|
|
fputs($output, "\xEF\xBB\xBF");
|
|
|
|
// Header row
|
|
fputcsv($output, ['Sale ID', 'Date', 'Total Amount', 'Payment Method', 'Items']);
|
|
|
|
// Data rows
|
|
foreach ($sales as $sale) {
|
|
fputcsv($output, [
|
|
$sale['id'],
|
|
$sale['sale_date'],
|
|
number_format($sale['total_amount'], 2),
|
|
$sale['payment_method'],
|
|
$sale['items']
|
|
]);
|
|
}
|
|
|
|
fclose($output);
|
|
exit;
|