<?php

namespace App\Http\Controllers;

use App\Models\Branch;
use App\Models\Order;
use App\Models\OrderDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class LeaderboardController extends Controller
{
    public function index(Request $request)
    {
        $period = $request->input('period', 'monthly');
        $year = max(2000, min(2100, (int) $request->input('year', now()->year)));
        $month = max(1, min(12, (int) $request->input('month', now()->month)));
        [$start, $end] = $this->dateRange($period, $year, $month);
        $branchId = $request->user()->isOwner() ? $request->integer('branch_id') : $request->user()->branch_id;

        $branchLeaderboard = Order::query()
            ->join('branches', 'branches.id', '=', 'orders.branch_id')
            ->whereBetween('orders.created_at', [$start, $end])
            ->when($branchId, fn ($q) => $q->where('orders.branch_id', $branchId))
            ->select(
                'branches.id',
                'branches.name',
                DB::raw('count(orders.id) as total_orders'),
                DB::raw('sum(orders.grand_total) as total_sales'),
                DB::raw('sum(orders.paid_total) as total_paid'),
                DB::raw('avg(orders.grand_total) as average_order')
            )
            ->groupBy('branches.id', 'branches.name')
            ->orderByDesc('total_sales')
            ->get();

        $staffLeaderboard = OrderDetail::query()
            ->join('orders', 'orders.id', '=', 'order_details.order_id')
            ->leftJoin('users', 'users.id', '=', 'order_details.staff_id')
            ->where('orders.payment_status', 'lunas')
            ->where('order_details.is_reward_free_item', false)
            ->whereBetween('orders.created_at', [$start, $end])
            ->when($branchId, fn ($q) => $q->where('orders.branch_id', $branchId))
            ->select(
                'users.id',
                DB::raw("coalesce(users.name, 'Tanpa staff') as staff_name"),
                DB::raw('count(order_details.id) as total_items'),
                DB::raw('count(distinct orders.id) as total_orders'),
                DB::raw('sum(order_details.line_total) as total_sales'),
                DB::raw('sum(order_details.bonus_amount) as total_bonus')
            )
            ->groupBy('users.id', 'users.name')
            ->orderByDesc('total_sales')
            ->get();

        return view('leaderboards.index', [
            'period' => $period,
            'year' => $year,
            'month' => $month,
            'start' => $start,
            'end' => $end,
            'branchId' => $branchId,
            'branches' => Branch::query()->where('is_active', true)->orderBy('name')->get(),
            'branchLeaderboard' => $branchLeaderboard,
            'staffLeaderboard' => $staffLeaderboard,
            'maxBranchSales' => max(1, (float) $branchLeaderboard->max('total_sales')),
            'maxStaffSales' => max(1, (float) $staffLeaderboard->max('total_sales')),
        ]);
    }

    private function dateRange(string $period, int $year, int $month): array
    {
        if ($period === 'yearly') {
            $start = Carbon::create($year, 1, 1)->startOfDay();

            return [$start, $start->copy()->endOfYear()];
        }

        $start = Carbon::create($year, $month, 1)->startOfDay();

        return [$start, $start->copy()->endOfMonth()];
    }
}
