<?php

namespace App\Livewire\Reports;

use App\Models\Location;
use App\Models\ProductStock;
use App\Models\Setting;
use Livewire\Component;
use App\Exports\GenericExport;
use Maatwebsite\Excel\Facades\Excel;
use Livewire\WithPagination;

class StockByLocationReport extends Component
{
    use WithPagination;

    protected $paginationTheme = 'bootstrap';

    public string $search = '';
    public string $locationFilter = '';
    public string $categoryFilter = '';
    public int $perPage = 25;

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function updatingLocationFilter()
    {
        $this->resetPage();
    }


    protected function getFilteredQuery()
    {
        $branchId = auth()->user()->branch_id ?? 1;

        return ProductStock::query()
            ->with(['product.category', 'location'])
            ->where('branch_id', $branchId)
            ->where('quantity', '>', 0)
            ->when($this->locationFilter, fn($q) => $q->where('location_id', $this->locationFilter))
            ->when($this->categoryFilter, fn($q) => $q->whereHas('product', fn($pq) => $pq->where('category_id', $this->categoryFilter)))
            ->when($this->search, function ($q) {
                $q->whereHas('product', function ($pq) {
                    $pq->where('name', 'like', '%' . $this->search . '%')
                       ->orWhere('name_ar', 'like', '%' . $this->search . '%')
                       ->orWhere('sku', 'like', '%' . $this->search . '%');
                });
            });
    }

    public function export()
    {
        $stocks = $this->getFilteredQuery()
            ->orderBy('location_id')
            ->get();

        return Excel::download(new GenericExport(
            $stocks,
            ['Location', 'Product', 'SKU', 'Category', 'Quantity', 'Cost Price', 'Value'],
            function ($row) {
                return [
                    $row->location?->localized_name ?? '-',
                    $row->product?->localized_name ?? '-',
                    $row->product?->sku ?? '-',
                    $row->product?->category?->localized_name ?? '-',
                    $row->quantity,
                    number_format($row->product?->cost_price ?? 0, 2),
                    number_format($row->quantity * ($row->product?->cost_price ?? 0), 2),
                ];
            },
            'Stock_By_Location_Report_' . now()->format('Y-m-d')
        ), 'stock_by_location_' . now()->format('YmdHis') . '.xlsx');
    }

    public function render()
    {
        $branchId = auth()->user()->branch_id ?? 1;
        $stocks = $this->getFilteredQuery()
            ->orderBy('location_id')
            ->paginate($this->perPage);

        $locations = Location::where('branch_id', $branchId)->active()->orderBy('sort_order')->get();
        $categories = \App\Models\Category::active()->orderBy('name')->get();

        // Summary
        $summaryQuery = ProductStock::where('branch_id', $branchId)
            ->where('quantity', '>', 0)
            ->when($this->locationFilter, fn($q) => $q->where('location_id', $this->locationFilter));

        $totalUnits = (clone $summaryQuery)->sum('quantity');
        $totalProducts = (clone $summaryQuery)->distinct('product_id')->count('product_id');
        $totalValue = (clone $summaryQuery)
            ->join('products', 'inventory.product_id', '=', 'products.id')
            ->selectRaw('SUM(inventory.quantity * products.cost_price) as total')
            ->value('total') ?? 0;

        return view('livewire.reports.stock-by-location', [
            'stocks' => $stocks,
            'locations' => $locations,
            'categories' => $categories,
            'totalUnits' => $totalUnits,
            'totalProducts' => $totalProducts,
            'totalValue' => $totalValue,
            'locationCount' => $locations->count(),
            'currency' => Setting::get('default_currency', 'EGP'),
        ]);
    }
}
