<?php

namespace App\Livewire\Reports;

use App\Models\PosSession;
use App\Models\CashDrawerTransaction;
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 SessionReport extends Component
{
    use WithPagination;

    public string $dateFrom = '';
    public string $dateTo = '';
    public string $userFilter = '';
    public string $statusFilter = '';
    public int $perPage = 20;

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

    public function getTotalsProperty()
    {
        $query = PosSession::query()
            ->when($this->dateFrom, fn($q) => $q->whereDate('opened_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn($q) => $q->whereDate('opened_at', '<=', $this->dateTo))
            ->when($this->userFilter, fn($q) => $q->where('user_id', $this->userFilter))
            ->when($this->statusFilter, fn($q) => $q->where('status', $this->statusFilter));

        return [
            'total_sessions' => (clone $query)->count(),
            'total_sales' => (clone $query)->sum('total_sales'),
            'total_cash_sales' => (clone $query)->sum('cash_sales'),
            'short_over' => (clone $query)->sum(DB::raw('actual_closing_cash - expected_closing_cash')),
        ];
    }

    protected function getFilteredQuery()
    {
        return PosSession::query()
            ->with(['user', 'branch'])
            ->when($this->dateFrom, fn($q) => $q->whereDate('opened_at', '>=', $this->dateFrom))
            ->when($this->dateTo, fn($q) => $q->whereDate('opened_at', '<=', $this->dateTo))
            ->when($this->userFilter, fn($q) => $q->where('user_id', $this->userFilter))
            ->when($this->statusFilter, fn($q) => $q->where('status', $this->statusFilter));
    }

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

        return Excel::download(new GenericExport(
            $sessions,
            ['Opened At', 'Closed At', 'User', 'Branch', 'Sales', 'Opening Cash', 'Actual Cash', 'Short/Over'],
            function ($row) {
                return [
                    $row->opened_at->format('Y-m-d H:i'),
                    $row->closed_at ? $row->closed_at->format('Y-m-d H:i') : '-',
                    $row->user?->name ?? 'N/A',
                    $row->branch?->name ?? 'Main',
                    number_format($row->total_sales, 2),
                    number_format($row->opening_cash, 2),
                    number_format($row->actual_closing_cash, 2),
                    number_format($row->actual_closing_cash - $row->expected_closing_cash, 2),
                ];
            },
            'POS_Sessions_Report_' . now()->format('Y-m-d')
        ), 'pos_sessions_' . now()->format('YmdHis') . '.xlsx');
    }

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

        $users = \App\Models\User::all();

        return view('livewire.reports.sessions', [
            'sessions' => $sessions,
            'totals' => $this->totals,
            'users' => $users,
            'currency' => Setting::get('default_currency', 'EGP'),
        ]);
    }
}
