<?php

namespace App\Repositories;

use App\Models\Akun;
use App\Models\JurnalTrans;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class JurnalRepository
{

    protected $jurnalTrans;

    public function __construct(JurnalTrans $jurnalTrans)
    {
        $this->jurnalTrans = $jurnalTrans;
    }

    public function findById($id): Collection
    {
        return $this->jurnalTrans->with('akun')->where('trans_id', $id)->get();
    }

    public function createJurnal(array $data): JurnalTrans
    {
        return $this->jurnalTrans->create($data);
    }

    public function deleteJurnal($id)
    {
        return $this->jurnalTrans->where('trans_id', $id)->delete();
    }

    public function saldoAkun($id, $tanggal)
    {
        $akun = Akun::where('kode_akun', $id)->first();
        $jurnal = JurnalTrans::where('akun_jurnal', $id)->where('trans_tglbuku', "<=", $tanggal)
            ->where('status', 1)
            ->select(DB::raw("sum(debet) - sum(kredit) as saldo"))->first();
        $saldo = $jurnal->saldo ?? 0;
        if ($akun->jurnal == 'K') {
            return $saldo * -1;
        }
        return $saldo;
    }
}
