<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Services\AnalyticsService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\StreamedResponse;

class ReportController extends Controller
{
    public function __construct(private readonly AnalyticsService $analytics) {}

    public function index(Request $request): View
    {
        [$from, $to] = $this->resolveRange($request);

        $summary = $this->analytics->summary($from, $to);
        $salesTrend = $this->analytics->salesTrend($from, $to);
        $topProducts = $this->analytics->topProducts($from, $to, 10);
        $categoryPerformance = $this->analytics->categoryPerformance($from, $to);
        $paymentMethodBreakdown = $this->analytics->paymentMethodBreakdown($from, $to);

        return view('admin.reports.index', compact(
            'from', 'to', 'summary', 'salesTrend', 'topProducts', 'categoryPerformance', 'paymentMethodBreakdown',
        ));
    }

    public function export(Request $request): StreamedResponse
    {
        [$from, $to] = $this->resolveRange($request);

        $orders = Order::whereBetween('created_at', [$from->copy()->startOfDay(), $to->copy()->endOfDay()])
            ->oldest()
            ->get();

        $filename = "niayarsa-orders-{$from->format('Ymd')}-{$to->format('Ymd')}.csv";

        return response()->streamDownload(function () use ($orders) {
            $handle = fopen('php://output', 'w');
            fputcsv($handle, ['Order Number', 'Date', 'Customer', 'Phone', 'City', 'Payment Method', 'Payment Status', 'Order Status', 'Grand Total']);

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

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

    /**
     * @return array{0: Carbon, 1: Carbon}
     */
    private function resolveRange(Request $request): array
    {
        $request->validate([
            'from' => ['nullable', 'date'],
            'to' => ['nullable', 'date', 'after_or_equal:from'],
        ]);

        $to = $request->filled('to') ? Carbon::parse($request->string('to')) : now();
        $from = $request->filled('from') ? Carbon::parse($request->string('from')) : $to->copy()->subDays(29);

        return [$from, $to];
    }
}
