<?php

class ReportController extends Controller
{
    private function dateRange(): array
    {
        $from = $this->input('date_from', date('Y-m-01'));
        $to = $this->input('date_to', date('Y-m-d'));
        return [$from, $to];
    }

    public function index(): void
    {
        Auth::requirePermission('reports', 'view');
        [$from, $to] = $this->dateRange();

        $reportModel = new Report();

        $this->view('reports.index', [
            'pageTitle'       => 'Reports',
            'dateFrom'        => $from,
            'dateTo'          => $to,
            'salesSummary'    => $reportModel->salesSummary($from, $to),
            'dailySales'      => $reportModel->dailySales($from, $to),
            'revenueByChannel'=> $reportModel->revenueByChannel($from, $to),
            'revenueByStatus' => $reportModel->revenueByStatus($from, $to),
            'topItems'        => $reportModel->topItems($from, $to),
            'pnl'             => $reportModel->pnl($from, $to),
            'stockValuation'  => $reportModel->stockValuation(),
            'deliveryPerf'    => $reportModel->deliveryPerformance($from, $to),
        ]);
    }

    public function exportSales(): void
    {
        Auth::requirePermission('reports', 'view');
        [$from, $to] = $this->dateRange();

        $reportModel = new Report();
        $rows = $reportModel->dailySales($from, $to);

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="sales-report-' . $from . '-to-' . $to . '.csv"');

        $out = fopen('php://output', 'w');
        fputcsv($out, ['Date', 'Orders', 'Revenue (LKR)']);
        foreach ($rows as $r) {
            fputcsv($out, [$r['sales_date'], $r['order_count'], number_format((float) $r['revenue'], 2, '.', '')]);
        }
        fclose($out);
        exit;
    }

    public function exportItems(): void
    {
        Auth::requirePermission('reports', 'view');
        [$from, $to] = $this->dateRange();

        $reportModel = new Report();
        $rows = $reportModel->topItems($from, $to, 100);

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="item-performance-' . $from . '-to-' . $to . '.csv"');

        $out = fopen('php://output', 'w');
        fputcsv($out, ['Item', 'Qty Sold', 'Revenue (LKR)']);
        foreach ($rows as $r) {
            fputcsv($out, [$r['item_name'], $r['qty_sold'], number_format((float) $r['revenue'], 2, '.', '')]);
        }
        fclose($out);
        exit;
    }

    public function exportPnl(): void
    {
        Auth::requirePermission('reports', 'view');
        [$from, $to] = $this->dateRange();

        $reportModel = new Report();
        $pnl = $reportModel->pnl($from, $to);

        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="pnl-' . $from . '-to-' . $to . '.csv"');

        $out = fopen('php://output', 'w');
        fputcsv($out, ['Category', 'Amount (LKR)']);
        fputcsv($out, ['Income (Payments Collected)', number_format($pnl['income'], 2, '.', '')]);
        fputcsv($out, ['Expenses', number_format(-$pnl['expenses'], 2, '.', '')]);
        fputcsv($out, ['Payroll Paid', number_format(-$pnl['payroll'], 2, '.', '')]);
        fputcsv($out, ['Supplier Payments', number_format(-$pnl['purchases'], 2, '.', '')]);
        fputcsv($out, ['Net P&L', number_format($pnl['net'], 2, '.', '')]);
        fclose($out);
        exit;
    }
}
