<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';
require 'dompdf/vendor/autoload.php';
use Dompdf\Dompdf;

$customer_id = intval($_GET['id'] ?? 0);
$start = $_GET['start'] ?? '';
$end = $_GET['end'] ?? '';
$export = $_GET['export'] ?? '';

$where = "WHERE 1=1";
if ($customer_id) $where .= " AND s.customer_id = $customer_id";
if ($start && $end) $where .= " AND DATE(s.sale_date) BETWEEN '$start' AND '$end'";

$sql = "SELECT s.id, s.sale_date, s.payment_method, s.total FROM sales s $where ORDER BY s.sale_date DESC";
$res = $conn->query($sql);

// Export PDF
if ($export == 'pdf') {
    $html = "<h3>Customer Sales Report</h3>";
    $html .= "<table border='1' cellpadding='5' cellspacing='0' width='100%'>
                <tr style='background:#000;color:#fff;'><th>#</th><th>Date</th><th>Sale ID</th><th>Payment</th><th>Total</th></tr>";
    $i=1; $sum = 0;
    while($r = $res->fetch_assoc()){
        $html .= "<tr><td>{$i}</td><td>{$r['sale_date']}</td><td>{$r['id']}</td><td>{$r['payment_method']}</td><td style='text-align:right;'>" . number_format($r['total'],2) . "</td></tr>";
        $sum += $r['total']; $i++;
    }
    $html .= "<tr><td colspan='4' style='text-align:right;font-weight:bold;'>Total</td><td style='text-align:right;font-weight:bold;'>" . number_format($sum,2) . "</td></tr>";
    $html .= "</table>";
    $dompdf = new Dompdf(); $dompdf->loadHtml($html); $dompdf->setPaper('A4','portrait'); $dompdf->render();
    $dompdf->stream("customer_sales_report.pdf", ["Attachment"=>true]); exit;
}

// Export CSV
if ($export == 'csv') {
    header('Content-Type: text/csv'); header('Content-Disposition: attachment;filename=customer_sales.csv');
    $out = fopen('php://output','w'); fputcsv($out, ['#','Date','Sale ID','Payment','Total']);
    $i=1; while($r = $res->fetch_assoc()){ fputcsv($out, [$i,$r['sale_date'],$r['id'],$r['payment_method'],$r['total']]); $i++; }
    fclose($out); exit;
}

// Page UI (simple)
?>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
    <h3>Customer Sales Report</h3>
    <form method="GET" class="row g-3 mb-3">
        <input type="hidden" name="id" value="<?= $customer_id ?>">
        <div class="col-md-3"><input type="date" name="start" class="form-control" value="<?= htmlspecialchars($start) ?>"></div>
        <div class="col-md-3"><input type="date" name="end" class="form-control" value="<?= htmlspecialchars($end) ?>"></div>
        <div class="col-md-3"><button class="btn btn-primary">Filter</button></div>
        <div class="col-md-3 text-end">
            <a href="?<?= http_build_query(['id'=>$customer_id,'start'=>$start,'end'=>$end,'export'=>'pdf']) ?>" class="btn btn-danger">Export PDF</a>
            <a href="?<?= http_build_query(['id'=>$customer_id,'start'=>$start,'end'=>$end,'export'=>'csv']) ?>" class="btn btn-success">Export CSV</a>
        </div>
    </form>

    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white"><tr><th>#</th><th>Date</th><th>Sale ID</th><th>Payment</th><th>Total</th></tr></thead>
        <tbody>
            <?php $res->data_seek(0); $i=1; $sum=0;
            while($r = $res->fetch_assoc()){ $sum += $r['total'];
                echo "<tr><td>{$i}</td><td>{$r['sale_date']}</td><td>{$r['id']}</td><td>{$r['payment_method']}</td><td>" . number_format($r['total'],2) . "</td></tr>";
                $i++;
            } ?>
        </tbody>
        <tfoot><tr><th colspan="4" class="text-end">Total:</th><th>MK <?= number_format($sum,2) ?></th></tr></tfoot>
    </table>
</div>

<?php include 'includes/footer.php'; ?>
