<?php

namespace App\Livewire\Reports;

use App\Models\StockAdjustment;
use App\Models\InventoryAdjustmentBatch;
use App\Models\Setting;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use App\Exports\GenericExport;
use Maatwebsite\Excel\Facades\Excel;
use Livewire\WithPagination;

class StockAdjustmentReport extends Component
{
    use WithPagination;

    protected $paginationTheme = 'bootstrap';

    public string $dateFrom = '';
    public string $dateTo = '';
    public string $typeFilter = '';
    public int $perPage = 25;

    public function mount()
    {
        $this->dateFrom = now()->startOfMonth()->format('Y-m-d');
        $this->dateTo = now()->format('Y-m-d');
    }

    protected function getFilteredQuery()
    {
        return StockAdjustment::query()
            ->with(['product:id,name,name_ar,sku', 'user:id,name', 'branch:id,name'])
            ->when($this->dateFrom, fn($q) => $q->whereDate('created_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn($q) => $q->whereDate('created_at', '<=', $this->dateTo))
            ->when($this->typeFilter, fn($q) => $q->where('type', $this->typeFilter));
    }

    public function export()
    {
        $adjustments = $this->getFilteredQuery()
            ->orderBy('created_at', 'desc')
            ->get();

        return Excel::download(new GenericExport(
            $adjustments,
            ['Date', 'Product', 'SKU', 'Type', 'Quantity', 'User', 'Reason'],
            function ($row) {
                return [
                    $row->created_at->format('Y-m-d H:i'),
                    $row->product?->localized_name ?? '-',
                    $row->product?->sku ?? '-',
                    ucfirst($row->type),
                    $row->quantity,
                    $row->user?->name ?? 'N/A',
                    $row->reason ?? '-',
                ];
            },
            'Stock_Adjustments_Report_' . now()->format('Y-m-d')
        ), 'stock_adjustments_' . now()->format('YmdHis') . '.xlsx');
    }

    public function render()
    {
        $adjustments = $this->getFilteredQuery()
            ->orderBy('created_at', 'desc')
            ->paginate($this->perPage);

        $summary = StockAdjustment::query()
            ->when($this->dateFrom, fn($q) => $q->whereDate('created_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn($q) => $q->whereDate('created_at', '<=', $this->dateTo))
            ->selectRaw("
                COUNT(*) as total_adjustments,
                SUM(CASE WHEN type = 'in' THEN quantity ELSE 0 END) as total_in,
                SUM(CASE WHEN type = 'out' THEN quantity ELSE 0 END) as total_out
            ")
            ->first();

        return view('livewire.reports.stock-adjustment-report', [
            'adjustments' => $adjustments,
            'summary' => $summary,
            'currency' => Setting::get('default_currency', 'EGP'),
        ]);
    }
}
