<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\SalaryPayment;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class ReportController extends Controller
{
    protected function dateRange(Request $request): array
    {
        $from = $request->query('from') ? Carbon::parse($request->query('from'))->startOfDay() : now()->startOfMonth();
        $to = $request->query('to') ? Carbon::parse($request->query('to'))->endOfDay() : now()->endOfDay();

        return [$from, $to];
    }

    public function index(Request $request)
    {
        $tab = $request->query('tab', 'sales');
        $shopId = $this->shopId();
        [$from, $to] = $this->dateRange($request);

        $data = match ($tab) {
            'pipeline' => $this->pipelineData($shopId),
            'balances' => $this->balancesData($shopId),
            'salary' => $this->salaryData($shopId, $from, $to),
            default => $this->salesData($shopId, $from, $to),
        };

        return view('admin.reports.index', [
            'tab' => $tab,
            'from' => $from->format('Y-m-d'),
            'to' => $to->format('Y-m-d'),
            'data' => $data,
        ]);
    }

    protected function salesData(int $shopId, $from, $to): array
    {
        $orders = Order::where('shop_id', $shopId)
            ->whereBetween('created_at', [$from, $to])
            ->with('customer')
            ->latest()
            ->get();

        return [
            'orders' => $orders,
            'total_orders' => $orders->count(),
            'total_revenue' => $orders->sum('total_amount'),
            'total_advance' => $orders->sum('advance_amount'),
            'total_balance' => $orders->sum('balance_amount'),
        ];
    }

    protected function pipelineData(int $shopId): array
    {
        $stages = ['received', 'cutting', 'stitching', 'finishing', 'ready', 'delivered'];

        $counts = collect($stages)->mapWithKeys(fn ($s) => [
            $s => Order::where('shop_id', $shopId)->where('stage', $s)->count(),
        ]);

        $ordersByStage = Order::where('shop_id', $shopId)
            ->whereIn('stage', $stages)
            ->with('customer')
            ->get()
            ->groupBy('stage');

        return ['counts' => $counts, 'ordersByStage' => $ordersByStage];
    }

    protected function balancesData(int $shopId): array
    {
        $orders = Order::where('shop_id', $shopId)
            ->where('balance_amount', '>', 0)
            ->with('customer')
            ->orderByDesc('balance_amount')
            ->get();

        return [
            'orders' => $orders,
            'total_outstanding' => $orders->sum('balance_amount'),
            'customer_count' => $orders->pluck('customer_id')->unique()->count(),
        ];
    }

    protected function salaryData(int $shopId, $from, $to): array
    {
        $payments = SalaryPayment::where('shop_id', $shopId)
            ->whereBetween('paid_on', [$from, $to])
            ->with('staff')
            ->latest('paid_on')
            ->get();

        return [
            'payments' => $payments,
            'total_paid' => $payments->sum('amount'),
        ];
    }

    public function exportExcel(Request $request)
    {
        $tab = $request->query('tab', 'sales');
        $shopId = $this->shopId();
        [$from, $to] = $this->dateRange($request);

        return \Maatwebsite\Excel\Facades\Excel::download(
            new \App\Exports\ReportExport($tab, $shopId, $from, $to),
            "report-{$tab}-" . now()->format('Y-m-d') . ".xlsx"
        );
    }

    public function exportPdf(Request $request)
    {
        $tab = $request->query('tab', 'sales');
        $shopId = $this->shopId();
        [$from, $to] = $this->dateRange($request);

        $data = match ($tab) {
            'pipeline' => $this->pipelineData($shopId),
            'balances' => $this->balancesData($shopId),
            'salary' => $this->salaryData($shopId, $from, $to),
            default => $this->salesData($shopId, $from, $to),
        };

        $pdf = \Barryvdh\DomPDF\Facade\Pdf::loadView('admin.reports.pdf', [
            'tab' => $tab,
            'from' => $from->format('d M Y'),
            'to' => $to->format('d M Y'),
            'data' => $data,
            'shopName' => Auth::guard('admin')->user()->shop->name,
        ]);

        return $pdf->download("report-{$tab}-" . now()->format('Y-m-d') . ".pdf");
    }

    protected function shopId(): int
    {
        return Auth::guard('admin')->user()->shop_id;
    }
}
