<?php

namespace App\Services;

use App\Models\Kas;
use App\Repositories\PenempatanBankRepository;
use App\Repositories\transaksiKasRepository;
use App\Repositories\TransaksiPenempatanRepository;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\DB;

class TransaksiKasService
{
    protected $transaksiKasRepository;
    protected $transaksiPenempatanRepository;
    protected $transaksiPenempatanService;
    protected $penempatanBankRepository;
    protected $jurnalService;

    public function __construct(transaksiKasRepository $transaksiKasRepository, PenempatanBankRepository $penempatanBankRepository,  TransaksiPenempatanRepository $transaksiPenempatanRepository, JurnalService $jurnalService, TransaksiPenempatanService $transaksiPenempatanService)
    {
        $this->transaksiKasRepository = $transaksiKasRepository;
        $this->transaksiPenempatanRepository = $transaksiPenempatanRepository;
        $this->penempatanBankRepository = $penempatanBankRepository;
        $this->jurnalService = $jurnalService;
        $this->transaksiPenempatanService = $transaksiPenempatanService;
    }
    public function getAllTransaksiKas($tgl_awal, $tgl_akhir, $id)
    {
        return $this->transaksiKasRepository->getAllTransaksiKas($tgl_awal, $tgl_akhir, $id);
    }

    public function getAll($tgl_awal, $tgl_akhir)
    {
        return $this->transaksiKasRepository->getAllTransaksi($tgl_awal, $tgl_akhir);
    }

    public function findTransaksiById($id)
    {
        return $this->transaksiKasRepository->findTransaksiById($id);
    }

    public function createTransaksi(array $data)
    {
        try {
            DB::transaction(function () use ($data) {
                $latest_transaksi = $this->transaksiKasRepository->getLastTransaksi($data);
                if ($data['sumber_kas'] == '2') {
                    $latest_transaksi = $this->transaksiPenempatanRepository->getLastTransaksi($data);
                }

                if ($latest_transaksi && preg_match('/(\d{5})$/', $latest_transaksi->trans_id, $matches)) {
                    $latest_id = (int)$matches[1];
                } else {
                    $latest_id = 0;
                }

                // Hapus strip dari trans_tglbuku dan ambil angkanya saja
                $tglbuku_numeric = preg_replace('/\D/', '', $data['trans_tglbuku']);

                $transaksi = [];

                $transaksi['trans_id'] = $data['trans_kode'] . "." . $tglbuku_numeric . "." . str_pad($latest_id + 1, 5, "0", STR_PAD_LEFT);

                $transaksi['trans_date'] = Carbon::now();
                $transaksi['trans_kode'] = $data['trans_kode'];
                $transaksi['keterangan'] = $data['keterangan'] ?? "";
                $transaksi['trans_tglbuku'] = $data['trans_tglbuku'];

                // kas tunai
                // if ($data['sumber_kas'] == '1') {
                $kas = Kas::find($data['kas_id']);
                if (!$kas) {
                    throw new \Exception('Kas tidak ditemukan');
                }

                // kas masuk
                $akun_kas = $kas->akun_kas;
                $transaksi['kas_id'] = $kas->id;

                if ($data['trans_kode'] == '11') {
                    $transaksi['masuk'] = $data['nominal'];
                    $transaksi['kode_akun'] = $data['kode_akun'];
                    $transaksi['keluar'] = 0;

                    $this->jurnalService->createJurnal([
                        'trans_id' => $transaksi['trans_id'],
                        'trans_kode' => $transaksi['trans_kode'],
                        'akun_jurnal' => $akun_kas,
                        'debet' => $data['nominal'],
                        'kredit' => 0,
                        'keterangan' => $transaksi['keterangan'],
                        'trans_tglbuku' => $transaksi['trans_tglbuku'],
                        'trans_date' => $transaksi['trans_date']
                    ]);
                    $this->jurnalService->createJurnal([
                        'trans_id' => $transaksi['trans_id'],
                        'trans_kode' => $transaksi['trans_kode'],
                        'akun_jurnal' => $transaksi['kode_akun'],
                        'debet' => 0,
                        'kredit' => $data['nominal'],
                        'keterangan' => $transaksi['keterangan'],
                        'trans_tglbuku' => $transaksi['trans_tglbuku'],
                        'trans_date' => $transaksi['trans_date']
                    ]);
                }
                // kas keluar
                if ($data['trans_kode'] == '12') {
                    $transaksi['kode_akun'] = $data['kode_akun'];
                    $transaksi['masuk'] = 0;
                    $transaksi['keluar'] = $data['nominal'];

                    $this->jurnalService->createJurnal([
                        'trans_id' => $transaksi['trans_id'],
                        'trans_kode' => $transaksi['trans_kode'],
                        'akun_jurnal' => $akun_kas,
                        'debet' => 0,
                        'kredit' => $data['nominal'],
                        'keterangan' => $transaksi['keterangan'],
                        'trans_tglbuku' => $transaksi['trans_tglbuku'],
                        'trans_date' => $transaksi['trans_date']
                    ]);
                    $this->jurnalService->createJurnal([
                        'trans_id' => $transaksi['trans_id'],
                        'trans_kode' => $transaksi['trans_kode'],
                        'akun_jurnal' => $transaksi['kode_akun'],
                        'debet' => $data['nominal'],
                        'kredit' => 0,
                        'keterangan' => $transaksi['keterangan'],
                        'trans_tglbuku' => $transaksi['trans_tglbuku'],
                        'trans_date' => $transaksi['trans_date']
                    ]);
                }
                return $this->transaksiKasRepository->createTransaksi($transaksi);
            });
        } catch (Exception $error) {
            throw new Exception($error->getMessage());
        }
    }

    public function validasiTransaksi($id)
    {
        $transaksi = $this->transaksiKasRepository->findTransaksiById($id);
        if (!$transaksi) {
            throw new Exception('Transaksi tidak ditemukan');
        }

        return $this->transaksiKasRepository->validasiTransaksi($id);
    }

    public function deleteTransaksi(string $id)
    {
        $transaksi_kas = $this->transaksiKasRepository->findTransaksiById($id);
        $transaksi_penempatan = $this->transaksiPenempatanRepository->findTransaksiById($id);
        if (!$transaksi_kas && !$transaksi_penempatan) {
            throw new Exception('Transaksi tidak ditemukan');
        }
        if ($transaksi_kas) {
            return $this->transaksiKasRepository->deleteTransaksi($id);
        }
        if ($transaksi_penempatan) {
            return $this->transaksiPenempatanRepository->deleteTransaksi($id);
        }
    }
}
