<?php

namespace App\Livewire\Reports;

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

    protected $paginationTheme = 'bootstrap';

    public string $dateFrom = '';
    public string $dateTo = '';
    public string $paymentMethodFilter = '';
    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 Sale::query()
            ->with(['partner', 'paymentMethod', 'user'])
            ->when($this->dateFrom, fn($q) => $q->whereDate('created_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn($q) => $q->whereDate('created_at', '<=', $this->dateTo))
            ->when($this->paymentMethodFilter, fn($q) => $q->where('payment_method_id', $this->paymentMethodFilter))
            ->where('total', '>', 0);
    }

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

        return Excel::download(new GenericExport(
            $payments,
            ['Date', 'Sale #', 'Customer', 'Method', 'Total', 'Paid', 'Remaining'],
            function ($row) {
                return [
                    $row->created_at->format('Y-m-d H:i'),
                    $row->sale_number,
                    $row->partner?->name ?? 'Walk-in',
                    $row->paymentMethod?->name ?? '-',
                    number_format($row->total, 2),
                    number_format($row->paid, 2),
                    number_format($row->total - $row->paid, 2),
                ];
            },
            'Payment_Collection_Report_' . now()->format('Y-m-d')
        ), 'payment_collections_' . now()->format('YmdHis') . '.xlsx');
    }

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

        $summary = Sale::query()
            ->when($this->dateFrom, fn($q) => $q->whereDate('created_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn($q) => $q->whereDate('created_at', '<=', $this->dateTo))
            ->when($this->paymentMethodFilter, fn($q) => $q->where('payment_method_id', $this->paymentMethodFilter))
            ->selectRaw('COUNT(*) as total_sales, COALESCE(SUM(total), 0) as total_collected, COALESCE(SUM(paid), 0) as total_paid, COALESCE(SUM(total - paid), 0) as total_remaining')
            ->first();

        $byMethod = Sale::query()
            ->when($this->dateFrom, fn($q) => $q->whereDate('sales.created_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn($q) => $q->whereDate('sales.created_at', '<=', $this->dateTo))
            ->join('payment_methods', 'sales.payment_method_id', '=', 'payment_methods.id')
            ->select('payment_methods.name', DB::raw('SUM(sales.total) as amount'), DB::raw('COUNT(*) as count'))
            ->groupBy('payment_methods.id', 'payment_methods.name')
            ->get();

        $paymentMethods = \App\Models\PaymentMethod::active()->orderBy('name')->get(['id', 'name']);

        return view('livewire.reports.payment-collection', [
            'payments' => $payments,
            'summary' => $summary,
            'byMethod' => $byMethod,
            'paymentMethods' => $paymentMethods,
            'currency' => Setting::get('default_currency', 'EGP'),
        ]);
    }
}
