<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\InventoryBalance;
use App\Models\Order;
use App\Models\StockTransfer;
use App\Services\LocationService;
use Illuminate\Http\Request;
use Illuminate\View\View;

class LocationReportController extends Controller
{
    public function __construct(protected LocationService $locationService)
    {
        $this->middleware('auth');
    }

    public function index(Request $request): View
    {
        $user = $request->user();
        $locations = $this->locationService->accessibleLocations($user);
        $locationId = $this->locationService->resolveAuthorizedFilterLocationId(
            $user,
            $request->input('location_id')
        );

        $sales = Order::query()
            ->when($locationId, fn ($q) => $q->where('fulfillment_location_id', $locationId))
            ->when(!$locationId && !$this->locationService->userCanViewAllLocations($user), function ($q) use ($locations) {
                $q->whereIn('fulfillment_location_id', $locations->pluck('id'));
            })
            ->where('payment_status', Order::PAYMENT_PAID)
            ->selectRaw('COUNT(*) as orders_count, COALESCE(SUM(total_payable),0) as sales_total')
            ->first();

        $stockValueRows = InventoryBalance::query()
            ->with('product:id,purchase_price')
            ->when($locationId, fn ($q) => $q->where('location_id', $locationId))
            ->when(!$locationId && !$this->locationService->userCanViewAllLocations($user), function ($q) use ($locations) {
                $q->whereIn('location_id', $locations->pluck('id'));
            })
            ->get();

        $onHandUnits = $stockValueRows->sum('on_hand');
        $approxStockCost = $stockValueRows->sum(function (InventoryBalance $b) {
            return $b->on_hand * (float) ($b->product?->purchase_price ?? 0);
        });

        $openTransfers = StockTransfer::query()
            ->when($locationId, function ($q) use ($locationId) {
                $q->where(function ($q2) use ($locationId) {
                    $q2->where('from_location_id', $locationId)
                        ->orWhere('to_location_id', $locationId);
                });
            })
            ->when(!$locationId && !$this->locationService->userCanViewAllLocations($user), function ($q) use ($locations) {
                $ids = $locations->pluck('id');
                $q->where(function ($q2) use ($ids) {
                    $q2->whereIn('from_location_id', $ids)
                        ->orWhereIn('to_location_id', $ids);
                });
            })
            ->whereIn('status', ['draft', 'approved', 'in_transit'])
            ->count();

        return view('admin.reports.location-ops', compact(
            'locations',
            'locationId',
            'sales',
            'onHandUnits',
            'approxStockCost',
            'openTransfers'
        ));
    }
}
