<?php

namespace App\Livewire\Reports;

use App\Models\PurchaseOrder;
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 PurchaseReport extends Component
{
    use WithPagination;

    protected $paginationTheme = 'bootstrap';

    public string $dateFrom = '';
    public string $dateTo = '';
    public string $supplierFilter = '';
    public string $statusFilter = '';
    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 PurchaseOrder::query()
            ->with(['supplier', 'creator'])
            ->when($this->dateFrom, fn($q) => $q->whereDate('order_date', '>=', $this->dateFrom))
            ->when($this->dateTo, fn($q) => $q->whereDate('order_date', '<=', $this->dateTo))
            ->when($this->supplierFilter, fn($q) => $q->where('supplier_id', $this->supplierFilter))
            ->when($this->statusFilter, fn($q) => $q->where('status', $this->statusFilter));
    }

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

        return Excel::download(new GenericExport(
            $orders,
            ['Order Date', 'PO #', 'Supplier', 'Status', 'Total', 'Creator'],
            function ($row) {
                return [
                    $row->order_date->format('Y-m-d'),
                    $row->po_number,
                    $row->supplier?->name ?? 'N/A',
                    ucfirst($row->status),
                    number_format($row->total, 2),
                    $row->creator?->name ?? 'System',
                ];
            },
            'Purchase_Report_' . now()->format('Y-m-d')
        ), 'purchases_' . now()->format('YmdHis') . '.xlsx');
    }

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

        $totals = PurchaseOrder::query()
            ->when($this->dateFrom, fn($q) => $q->whereDate('order_date', '>=', $this->dateFrom))
            ->when($this->dateTo, fn($q) => $q->whereDate('order_date', '<=', $this->dateTo))
            ->when($this->supplierFilter, fn($q) => $q->where('supplier_id', $this->supplierFilter))
            ->when($this->statusFilter, fn($q) => $q->where('status', $this->statusFilter))
            ->selectRaw('COUNT(*) as total_count, COALESCE(SUM(total), 0) as total_amount')
            ->first();

        $suppliers = \App\Models\Partner::suppliers()->orderBy('name')->get(['id', 'name']);

        return view('livewire.reports.purchase-report', [
            'orders' => $orders,
            'totals' => $totals,
            'suppliers' => $suppliers,
            'currency' => Setting::get('default_currency', 'EGP'),
        ]);
    }
}
