<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Barryvdh\DomPDF\Facade\Pdf;
use App\Models\Member;


class Receipt extends Component
{
    public $records;

    public $filterStatus = '';
    public $hasFilter = false;
    public $filterFrom = '', $filterTo = '';
    public $filteredMemberId = '';
    public $members = [];

    public function mount()
    {
        // Load members for the dropdown
        $this->members = Member::orderBy('last_name')->orderBy('first_name')->get();
    }

    public function updatedFilterFrom()
    {
        $this->emit('destroy-data-table');
    }

    public function updatedFilterTo()
    {
        $this->emit('destroy-data-table');
    }

    public function render()
    {

        if ($this->hasFilter)
        {
            $r = \App\Models\Receipt::with('member');
            if ($this->filterStatus != '')
                $r = $r->where('status', $this->filterStatus);
            if ($this->filterFrom != '')
                $r = $r->where('date', '>=', $this->filterFrom);
            if ($this->filterTo != '')
                $r = $r->where('date', '<=', $this->filterTo);
            if ($this->filteredMemberId != '')
                $r = $r->where('member_id', $this->filteredMemberId);

            $this->records = $r->get();
        }
        else
        {
            $this->records = \App\Models\Receipt::with('member')->get();
        }

        $this->emit('load-data-table');

        return view('livewire.receipt');
    }

    public function printReceipt($id)
    {
        $this->emit('load-data-table');
        $receipt = \App\Models\Receipt::findOrFail($id);
        //$pdf = PDF::loadView('pdf/receipt', array('datas' => $datas, 'from' => $x, 'to' => $y, 'who' => '', 'matricola' => $matricola));
        $pdf = PDF::loadView('receipt', array('receipt' => $receipt));//->output();
        return $pdf->stream('aaa.pdf');

    }

    public function search()
    {
        $this->hasFilter = true;
    }

    public function disableSearch()
    {
        $this->filterStatus = "";
        $this->filterTo = '';
        $this->filterFrom = '';
        $this->filteredMemberId = '';
        $this->hasFilter = false;
    }

}
