<?php
/**
 * GET /api/business/sales_export.php
 * Business-only. Streams a CSV of the caller's own sales (as seller) -
 * the vendor-facing counterpart to admin/sales_report.php, which is
 * platform-wide and admin-only.
 */

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/response.php';
require_once __DIR__ . '/../includes/auth.php';

$userId = require_login();
require_role(['business']);

$pdo = Database::connect();
$stmt = $pdo->prepare('
    SELECT o.id AS order_id, o.created_at, p.name AS product_name,
           oi.quantity, oi.unit_price, (oi.quantity * oi.unit_price) AS line_total, oi.status,
           buyer.email AS buyer_email
    FROM order_items oi
    JOIN orders o ON o.id = oi.order_id
    JOIN products p ON p.id = oi.product_id
    JOIN users buyer ON buyer.id = o.buyer_id
    WHERE oi.seller_id = ?
    ORDER BY o.created_at DESC
');
$stmt->execute([$userId]);
$rows = $stmt->fetchAll();

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="my-ragreen-sales.csv"');
$out = fopen('php://output', 'w');
fputcsv($out, ['Order ID', 'Date', 'Product', 'Qty', 'Unit Price', 'Line Total', 'Status', 'Buyer Email']);
foreach ($rows as $r) {
    fputcsv($out, [$r['order_id'], $r['created_at'], $r['product_name'], $r['quantity'], $r['unit_price'], $r['line_total'], $r['status'], $r['buyer_email']]);
}
fclose($out);
