<?php

namespace App\Http\Controllers\Api;

use App\Models\Akun;
use App\Models\DataNeraca;
use App\Models\JurnalTrans;
use App\Models\Kas;
use App\Models\Verbal;
use App\Services\JurnalService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Nette\NotImplementedException;

class JurnalController extends Controller
{
    protected $jurnalService;

    public function __construct(JurnalService $jurnalService)
    {
        $this->jurnalService = $jurnalService;
    }

    public function index()
    {
        //
    }

    public function create()
    {
        //
    }

    public function store(Request $request)
    {
        //
    }

    public function show(string $id)
    {
        return $this->jurnalService->findByTransId($id);
    }

    public function edit(string $id)
    {
        //
    }

    public function update(Request $request, string $id)
    {
        //
    }

    public function destroy(string $id)
    {
        //
    }

    public function saldoAkun(Request $request)
    {
        $id = $request->id;
        $tanggal = $request->input('tanggal', Carbon::now());
        return $this->jurnalService->saldoAkun($id, $tanggal);
    }

    public function getNeraca(Request $request)
    {
        $tanggal = $request->input('tanggal', Carbon::now());

        // $neraca = DataNeraca::where('tanggal', $tanggal)->get();

        // if ($neraca) {
        //     return response()->json($neraca);
        // } else {
        //     $neraca = DataNeraca::where('tanggal', $tanggal)->orderBy('tanggal', 'desc')->first();
        //     $jurnal = JurnalTrans::where('status', 1)
        //         ->leftJoin('akun', 'akun_jurnal', 'akun.kode_akun')
        //         ->whereIn('akun_jurnal', $neraca->pluck('akun'))
        //         ->where('trans_tglbuku', '>', $neraca->tanggal)
        //         ->select(
        //             'akun_jurnal',
        //             DB::raw("CASE WHEN akun.jurnal = 'D' THEN SUM(debet) - SUM(kredit) ELSE SUM(kredit) - SUM(debet) END as saldo")
        //         )
        //         ->groupBy('akun_jurnal', 'akun.jurnal')
        //         ->get();
        //     return response()->json($jurnal);
        // }
        $akun = Akun::all();
        $aktiva = $akun->where('kategori', 'AKTIVA')->values();
        $pasiva = $akun->where('kategori', 'PASIVA')->values();
        $laba = $akun->where('kategori', 'PENDAPATAN')->values();
        $rugi = $akun->where('kategori', 'BIAYA')->values();

        return response()->json([
            'aktiva' => $aktiva,
            'pasiva' => $pasiva,
            'laba' => $laba,
            'rugi' => $rugi
        ]);
    }

    public function getLabaRugi(Request $request)
    {
        $akun = Akun::all();
        $aktiva = $akun->where('kategori', 'AKTIVA')->values();
        $pasiva = $akun->where('kategori', 'PASIVA')->values();
        $laba = $akun->where('kategori', 'PENDAPATAN')->values();
        $rugi = $akun->where('kategori', 'BIAYA')->values();

        return response()->json([
            'aktiva' => $aktiva,
            'pasiva' => $pasiva,
            'laba' => $laba,
            'rugi' => $rugi
        ]);
    }

    public function tutupBukuHarian(Request $request) {}

    public function tutupBukuTahunan(Request $request) {}

    public function getVerbal(Request $request)
    {
        $tanggal = $request->input('tanggal', Carbon::now());

        $verbal = Verbal::where('tanggal', $tanggal)->first();
        if ($verbal) {
            // Convert to array to safely add custom fields
            $verbalArr = $verbal->toArray();
            $verbalArr['uangLogam'] = [];
            foreach ($verbal->getAttributes() as $key => $value) {
                if (strpos($key, 'ul') === 0) {
                    $verbalArr['uangLogam'][$key] = $value;
                }
            }
            $verbalArr['uangKertas'] = [];
            foreach ($verbal->getAttributes() as $key => $value) {
                if (strpos($key, 'uk') === 0) {
                    $verbalArr['uangKertas'][$key] = $value;
                }
            }
            $verbal = (object)$verbalArr;
        } else {
            $verbal = (object)[];
            $verbal->tanggal = $tanggal;
        }

        $kas = Kas::where('status', 1)->get();

        $neraca = DataNeraca::whereIn('akun', $kas->pluck('akun_kas'))
            ->select([DB::raw('sum(saldo) as saldo'), 'tanggal'])
            ->groupBy('tanggal')
            ->orderBy('tanggal', 'desc')
            ->first();

        $kas_awal = 0;

        if ($neraca) {
            $kas_awal = JurnalTrans::whereIn('akun_jurnal', $kas->pluck('akun_kas'))
                ->where('trans_tglbuku', '>', $neraca->tanggal)
                ->where('trans_tglbuku', '<=', $tanggal)
                ->select(DB::raw('sum(debet) - sum(kredit) as saldo'))
                ->where('status', 1)
                ->groupBy('akun_jurnal')
                ->first();
            $kas_awal = $kas_awal?->saldo + $neraca?->saldo;
        } else {
            $kas_awal = JurnalTrans::whereIn('akun_jurnal', $kas->pluck('akun_kas'))
                ->where('trans_tglbuku', '<=', Carbon::parse($tanggal)->subDay(1)->format('Y-m-d'))
                ->select(DB::raw('sum(debet) - sum(kredit) as saldo'))
                ->where('status', 1)
                ->groupBy('akun_jurnal')
                ->first();
            $kas_awal = $kas_awal?->saldo;
        }

        $masuk = 0;
        $keluar = 0;

        $masuk = JurnalTrans::whereIn('akun_jurnal', $kas->pluck('akun_kas'))
            ->where('trans_tglbuku', '=', $tanggal)
            ->select(DB::raw('sum(debet) as saldo'))
            ->where('status', 1)
            ->groupBy('akun_jurnal')
            ->first();
        $masuk = $masuk?->saldo;

        $keluar = JurnalTrans::whereIn('akun_jurnal', $kas->pluck('akun_kas'))
            ->where('trans_tglbuku', '=', $tanggal)
            ->select(DB::raw('sum(kredit) as saldo'))
            ->where('status', 1)
            ->groupBy('akun_jurnal')
            ->first();
        $keluar = $keluar?->saldo;

        $verbal->saldo_awal_kas = $kas_awal ?? 0;
        $verbal->masuk = $masuk ?? 0;
        $verbal->keluar = $keluar ?? 0;
        $verbal->saldo_akhir_kas = $kas_awal + $masuk - $keluar ?? 0;

        return response()->json($verbal);
    }

    public function simpanVerbal(Request $request)
    {
        $user =  Auth::user();

        $data = $request->all();
        $tanggal = $request->input('tanggal', Carbon::now());

        $verbal = Verbal::where('tanggal', $tanggal)->first();
        if ($verbal) {
            $verbal->update($data);
        } else {
            $data['user'] = $user->username;
            Verbal::create($data);
        }

        return response()->json(['message' => 'Berhasil simpan verbal']);
    }
}
