<?php

namespace App\Repositories;

use App\Models\Kas;
use Illuminate\Database\Eloquent\Collection;

class KasRepository
{
    protected $kas;

    public function __construct(Kas $kas)
    {
        $this->kas = $kas;
    }

    public function getAll(): Collection
    {
        return $this->kas->with('jurnal')->get();
    }

    public function findById(string $id): ?Kas
    {
        return $this->kas->with('jurnal')->find($id);
    }

    public function findByNama(string $nama): ?Kas
    {
        return $this->kas->where('nama', $nama)->first();
    }

    public function create(array $data): Kas
    {
        return $this->kas->create($data);
    }

    public function update(string $id, array $data): ?Kas
    {
        $kas = $this->findById($id);
        if (isset($data['is_default']) && $data['is_default'] == 1) {
            Kas::where('id', '!=', $id)->update([
                'is_default' => 0
            ]);
        }
        if ($kas) {
            $kas->update($data);
        }
        return $kas;
    }

    public function getLastest()
    {
        return $this->kas->latest()->first();
    }
    public function count()
    {
        return $this->kas->all()->count();
    }

    public function delete(string $id): bool
    {
        $kas = $this->findById($id);
        $kas->status = 9;
        $kas->save();
        return false;
    }
}
