<?php

namespace App\Livewire\Reports;

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

class BatchExpiryReport extends Component
{
    use WithPagination;

    protected $paginationTheme = 'bootstrap';

    public string $search = '';
    public string $locationFilter = '';
    public string $expiryHorizon = '90'; // days
    public bool $expiredOnly = false;
    public int $perPage = 25;

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


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

        $query = InventoryLot::query()
            ->with(['product:id,name,name_ar,sku', 'location:id,name,name_ar'])
            ->where('branch_id', $branchId)
            ->where('quantity_remaining', '>', 0)
            ->where(function ($q) {
                $q->whereNotNull('batch_no')
                  ->orWhereNotNull('expiry_date');
            })
            ->when($this->locationFilter, fn($q) => $q->where('location_id', $this->locationFilter))
            ->when($this->search, function ($q) {
                $q->where(function ($sq) {
                    $sq->where('batch_no', 'like', '%' . $this->search . '%')
                       ->orWhereHas('product', function ($pq) {
                           $pq->where('name', 'like', '%' . $this->search . '%')
                              ->orWhere('name_ar', 'like', '%' . $this->search . '%')
                              ->orWhere('sku', 'like', '%' . $this->search . '%');
                       });
                });
            });

        if ($this->expiredOnly) {
            $query->whereNotNull('expiry_date')->where('expiry_date', '<', now());
        } elseif ($this->expiryHorizon) {
            $query->whereNotNull('expiry_date')
                  ->where('expiry_date', '<=', now()->addDays((int) $this->expiryHorizon));
        }

        return $query;
    }

    public function export()
    {
        $lots = $this->getFilteredQuery()
            ->orderBy('expiry_date', 'asc')
            ->get();

        return Excel::download(new GenericExport(
            $lots,
            ['Batch No', 'Product', 'SKU', 'Location', 'Expiry Date', 'Qty Remaining', 'Cost Price'],
            function ($row) {
                return [
                    $row->batch_no ?? '-',
                    $row->product?->localized_name ?? '-',
                    $row->product?->sku ?? '-',
                    $row->location?->localized_name ?? '-',
                    $row->expiry_date ? $row->expiry_date->format('Y-m-d') : '-',
                    $row->quantity_remaining,
                    number_format($row->cost_price, 2),
                ];
            },
            'Batch_Expiry_Report_' . now()->format('Y-m-d')
        ), 'batch_expiry_' . now()->format('YmdHis') . '.xlsx');
    }

    public function render()
    {
        $branchId = auth()->user()->branch_id ?? 1;
        $lots = $this->getFilteredQuery()
            ->orderBy('expiry_date', 'asc')
            ->paginate($this->perPage);

        $locations = Location::where('branch_id', $branchId)->active()->orderBy('sort_order')->get();

        // Summary
        $baseSummary = InventoryLot::where('branch_id', $branchId)
            ->where('quantity_remaining', '>', 0)
            ->whereNotNull('expiry_date');

        $expiredCount = (clone $baseSummary)->where('expiry_date', '<', now())->count();
        $nearExpiryCount = (clone $baseSummary)
            ->where('expiry_date', '>=', now())
            ->where('expiry_date', '<=', now()->addDays(30))
            ->count();
        $totalBatches = InventoryLot::where('branch_id', $branchId)
            ->where('quantity_remaining', '>', 0)
            ->whereNotNull('batch_no')
            ->count();

        return view('livewire.reports.batch-expiry', [
            'lots' => $lots,
            'locations' => $locations,
            'expiredCount' => $expiredCount,
            'nearExpiryCount' => $nearExpiryCount,
            'totalBatches' => $totalBatches,
            'currency' => Setting::get('default_currency', 'EGP'),
        ]);
    }
}
