<?php

namespace App\Livewire;

use App\Models\Pengembalian;
use App\Models\Pinjam;
use DateTime;
use Livewire\Component;
use Livewire\WithoutUrlPagination;
use Livewire\WithPagination;

class KembaliComponent extends Component
{
    use WithPagination, WithoutUrlPagination;
    protected $paginationTheme = 'bootstrap';
    public $id, $judul, $member, $tgl_kembali, $selisih, $status, $lama;
    public function render()
    {
        $layout['title'] = 'Pengembalian Buku';
        $data['pinjam'] = Pinjam::where('status', 'pinjam')->paginate(10);
        $data['pengembalian'] = Pengembalian::paginate(10);
        return view('livewire.kembali-component', $data)->layoutData($layout);
    }

    public function pilih($id)
{
    $pinjam = Pinjam::find($id);
    $this->judul = $pinjam->buku->judul;
    $this->member = $pinjam->user->nama;
    $this->tgl_kembali = $pinjam->tgl_kembali;
    $this->id = $pinjam->id;

    $today = new DateTime(); // Hari ini
    $tgl_kembali = new DateTime($this->tgl_kembali); // Tanggal jatuh tempo

    if ($today > $tgl_kembali) {
        // Sudah lewat tanggal kembali → terlambat
        $this->status = true;
        $selisih = $tgl_kembali->diff($today);
        $this->lama = $selisih->days;
    } else {
        // Belum jatuh tempo → tidak telat
        $this->status = false;
        $this->lama = 0;
    }
}

public function store()
{
    if ($this->status == true){
        $denda = $this->lama * 1000;
    } else {
        $denda = 0;
    }
    $pinjam = Pinjam::find($this->id);
    Pengembalian::create([
        'pinjam_id' => $this->id,
        'tgl_kembali'=>date('Y-m-d'),
        'denda' => $denda
    ]);

    $pinjam->update([
        'status' => 'kembali'
    ]);
    $this->reset();
    session()->flash('success', 'Berhasil Memproses Data !');
    return redirect()->route('kembali');
}
}

