<?php

namespace App\Http\Controllers\Admin;

use App\Enums\OrderStatus;
use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Symfony\Component\HttpFoundation\StreamedResponse;

class LaporanController extends Controller
{
    /**
     * Export laporan penjualan ke CSV atau Excel.
     *
     * MENGAPA TANPA PACKAGE TAMBAHAN (mis. maatwebsite/excel):
     * Project ini tidak memiliki dependency Excel apa pun di composer.json.
     * Menambahkannya berarti composer require + ubah composer.json,
     * di luar instruksi "minimal diff". Maka:
     * - CSV  : fputcsv() bawaan PHP, di-stream langsung (tanpa file sementara).
     * - Excel: HTML table dengan ekstensi .xls — trik standar yang didukung
     *          Microsoft Excel sejak lama, tanpa dependency apa pun.
     */
    public function export(Request $request): StreamedResponse
    {
        abort_unless($request->user()->can('report.export'), 403);

        $type = $request->query('type', 'csv');
        [$from, $to] = $this->resolveDateRange($request);

        $orders = Order::where('status', OrderStatus::Completed->value)
            ->whereBetween('created_at', [$from, $to])
            ->orderBy('created_at')
            ->get();

        return $type === 'excel'
            ? $this->exportExcel($orders, $from, $to)
            : $this->exportCsv($orders, $from, $to);
    }

    /**
     * Tentukan rentang tanggal dari query string, mengikuti logika
     * yang sama persis dengan Livewire\Admin\Laporan\Index::getDateRange()
     * agar data yang diexport selalu konsisten dengan yang ditampilkan di layar.
     */
    private function resolveDateRange(Request $request): array
    {
        $period = $request->query('period', 'today');

        return match ($period) {
            'week'   => [now()->startOfWeek(), now()->endOfWeek()],
            'month'  => [now()->startOfMonth(), now()->endOfMonth()],
            'custom' => [
                Carbon::parse($request->query('dateFrom') ?: now())->startOfDay(),
                Carbon::parse($request->query('dateTo') ?: now())->endOfDay(),
            ],
            default  => [now()->startOfDay(), now()->endOfDay()],
        };
    }

    private function exportCsv($orders, Carbon $from, Carbon $to): StreamedResponse
    {
        $filename = 'laporan-penjualan-' . $from->format('Ymd') . '-' . $to->format('Ymd') . '.csv';

        return response()->streamDownload(function () use ($orders) {
            $handle = fopen('php://output', 'w');

            // BOM agar Excel membaca karakter UTF-8 (Rp, dst) dengan benar
            fwrite($handle, "\xEF\xBB\xBF");

            fputcsv($handle, ['Tanggal', 'Invoice', 'Customer', 'Total', 'Status']);

            foreach ($orders as $order) {
                fputcsv($handle, [
                    $order->created_at->format('d-m-Y H:i'),
                    $order->order_number,
                    $order->customer_name,
                    $order->grand_total,
                    $order->status->label(),
                ]);
            }

            fclose($handle);
        }, $filename, [
            'Content-Type' => 'text/csv; charset=UTF-8',
        ]);
    }

    private function exportExcel($orders, Carbon $from, Carbon $to): StreamedResponse
    {
        $filename = 'laporan-penjualan-' . $from->format('Ymd') . '-' . $to->format('Ymd') . '.xls';

        return response()->streamDownload(function () use ($orders) {
            echo '<table border="1">';
            echo '<tr><th>Tanggal</th><th>Invoice</th><th>Customer</th><th>Total</th><th>Status</th></tr>';

            foreach ($orders as $order) {
                echo '<tr>';
                echo '<td>' . e($order->created_at->format('d-m-Y H:i')) . '</td>';
                echo '<td>' . e($order->order_number) . '</td>';
                echo '<td>' . e($order->customer_name) . '</td>';
                echo '<td>' . e(number_format($order->grand_total, 0, ',', '.')) . '</td>';
                echo '<td>' . e($order->status->label()) . '</td>';
                echo '</tr>';
            }

            echo '</table>';
        }, $filename, [
            'Content-Type' => 'application/vnd.ms-excel; charset=UTF-8',
        ]);
    }
}
