<?php

namespace App\Livewire\Sales;

use App\Models\DailySale;
use Livewire\Component;
use Livewire\WithPagination;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\GenericExport;

class DailySalesIndex extends Component
{
    use WithPagination;

    protected $paginationTheme = 'bootstrap';

    public $dateFrom;
    public $dateTo;
    public $perPage = 15;

    public array $selectedRows = [];
    public bool $selectAll = false;

    public function updatedSelectAll($value)
    {
        if ($value) {
            $this->selectedRows = DailySale::whereBetween('sale_date', [$this->dateFrom, $this->dateTo])
                ->pluck('id')->map(fn($id) => (string)$id)->toArray();
        } else {
            $this->selectedRows = [];
        }
    }

    public function export()
    {
        $query = DailySale::query()
            ->when(!empty($this->selectedRows), fn($q) => $q->whereIn('id', $this->selectedRows))
            ->when(empty($this->selectedRows), fn($q) => $q->whereBetween('sale_date', [$this->dateFrom, $this->dateTo]))
            ->with(['payments.paymentMethod', 'user']);

        $sales = $query->orderBy('sale_date', 'desc')->get();

        return Excel::download(new GenericExport(
            $sales,
            ['Reference', 'Date', 'Total', 'Payments Breakdown', 'Recorded By'],
            function ($row) {
                return [
                    $row->reference,
                    $row->sale_date->format('Y-m-d'),
                    number_format($row->total, 2),
                    $row->payments->map(fn($p) => ($p->paymentMethod?->name ?? 'N/A') . '(' . number_format($p->amount, 2) . ')')->implode(', '),
                    $row->user->name ?? 'Unknown',
                ];
            },
            'Daily_Sales_Export_' . now()->format('Y-m-d')
        ), 'daily_sales_' . now()->format('YmdHis') . '.xlsx');
    }

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

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

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

    public function render()
    {
        $dailySales = DailySale::with(['payments.paymentMethod', 'user', 'branch'])
            ->whereBetween('sale_date', [$this->dateFrom, $this->dateTo])
            ->orderBy('sale_date', 'desc')
            ->paginate($this->perPage);

        return view('livewire.sales.daily-sales-index', [
            'dailySales' => $dailySales,
        ])->layout('layouts.app')->title(__('Daily Sales History'));
    }
}
