<?php

namespace App\Livewire\Pos\Opname;

use App\Exports\SOExport;
use App\Models\Opname;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\On;
use Livewire\Component;
use Maatwebsite\Excel\Facades\Excel;


class OpnameResult extends Component
{
    public $opnames;
    public $opnameh;

    public function mount()
    {
        $this->opnames = Opname::where('id_user', Auth::user()->id)->get();
        $this->opnameh = Opname::where('id_user', Auth::user()->id)->first();
        $this->dispatch('refreshJs');
    }

    
    #[On('refreshJs')]
    public function refreshJs()
    {
        $this->dispatch('refreshDatatable');
    }

    public function render()
    {
        return view('livewire.pos.opname.opname-result');
    }

    public function export()
    {
        $opnames = Opname::where('id_user', Auth::user()->id)
        ->where('difference', '>', 0)
        ->get();
        $currentDate = Carbon::now();
        $now = $currentDate->format('d-m-Y');
        $filename = "SO Report Difference - {$now}.xlsx";
        return Excel::download(new SOExport($opnames), $filename);
    }

    public function exportNoDiff()
    {
        $opnames = Opname::where('id_user', Auth::user()->id)
        ->where('difference', '=', 0)
        ->get();
        $currentDate = Carbon::now();
        $now = $currentDate->format('d-m-Y');
        $filename = "SO Report - {$now}.xlsx";
        return Excel::download(new SOExport($opnames), $filename);
    }
    public function close()
    {
        return $this->redirect('/opname');
    }
}
