<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Neraca extends CI_Controller {
    
    public function __construct()
    {
        parent::__construct();
        $this->load->model('DynamicModel', 'dm');

        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
    }

    public function index()
    {
        if($this->session->userdata('role') != 'Admin'){
            show_error('Akses ditolak', 403);
        }

        $data = ["active_menu" => "neraca"];
        $this->load->view('partials/header', $data);
        $this->load->view('laporan/neraca');
        $this->load->view('partials/footer');
    }

    // =========================
    // LABA BERJALAN (PAKAI TANGGAL JOURNAL)
    // =========================
    private function get_laba_berjalan($tanggal_dari = null, $tanggal_sampai = null)
    {
        $this->db->select('
            accounts.tipe,
            COALESCE(SUM(jd.debit),0) as debit,
            COALESCE(SUM(jd.kredit),0) as kredit
        ');
        $this->db->from('accounts');
        $this->db->join('journal_details jd','jd.account_id = accounts.id','LEFT');
        $this->db->join('journals j','j.id = jd.journal_id','LEFT');

        $this->db->where_in('accounts.tipe',['revenue','expense']);

        // ================= FILTER TANGGAL
        if($tanggal_dari){
            $this->db->where('(j.tanggal >= "'.$tanggal_dari.'" OR j.tanggal IS NULL)');
        }

        if($tanggal_sampai){
            $this->db->where('(j.tanggal <= "'.$tanggal_sampai.'" OR j.tanggal IS NULL)');
        }

        $rows = $this->db->get()->result();

        $revenue = 0;
        $expense = 0;

        foreach ($rows as $r) {
            if ($r->tipe == 'revenue') {
                $revenue += ($r->kredit - $r->debit);
            } else {
                $expense += ($r->debit - $r->kredit);
            }
        }

        return $revenue - $expense;
    }

    // =========================
    // GET DATA NERACA
    // =========================
    public function get_data()
    {
        $tanggal_dari   = $this->input->get('tanggal_dari');
        $tanggal_sampai = $this->input->get('tanggal_sampai');

        $this->db->select('
            a.id,
            a.kode_akun,
            a.nama_akun,
            a.tipe,
            a.posisi,
            a.is_kontra,
            COALESCE(SUM(jd.debit),0) as debit,
            COALESCE(SUM(jd.kredit),0) as kredit
        ');
        $this->db->from('accounts a');
        $this->db->join('journal_details jd','jd.account_id = a.id','LEFT');
        $this->db->join('journals j','j.id = jd.journal_id','LEFT');

        $this->db->where('a.kategori','neraca');

        // ================= FILTER TANGGAL
        if($tanggal_dari){
            $this->db->where('(j.tanggal >= "'.$tanggal_dari.'" OR j.tanggal IS NULL)');
        }

        if($tanggal_sampai){
            $this->db->where('(j.tanggal <= "'.$tanggal_sampai.'" OR j.tanggal IS NULL)');
        }

        $this->db->group_by('a.id');
        $this->db->order_by('a.kode_akun','ASC');

        $rows = $this->db->get()->result();

        $activa = [];
        $pasiva = [];

        $total_activa = 0;
        $total_pasiva = 0;

        // ================= LABA BERJALAN
        $laba = $this->get_laba_berjalan($tanggal_dari, $tanggal_sampai);

        foreach ($rows as $r) {

            // ================= SALDO NORMAL
            if ($r->posisi == 'debit') {
                $saldo = $r->debit - $r->kredit;
            } else {
                $saldo = $r->kredit - $r->debit;
            }

            // ================= KONTRA ACCOUNT
            if ($r->is_kontra == 1) {
                $saldo = -$saldo;
            }

            // ================= LABA BERJALAN
            if ($r->kode_akun == '302') {
                $saldo = $laba;
            }

            // ================= ACTIVA
            if ($r->tipe == 'asset') {

                $activa[] = [
                    'kode' => $r->kode_akun,
                    'nama' => $r->nama_akun,
                    'saldo' => $saldo
                ];

                $total_activa += $saldo;
            }

            // ================= PASIVA
            if (in_array($r->tipe, ['liability','equity'])) {

                $pasiva[] = [
                    'kode' => $r->kode_akun,
                    'nama' => $r->nama_akun,
                    'saldo' => $saldo
                ];

                $total_pasiva += $saldo;
            }
        }

        echo json_encode([
            'activa' => $activa,
            'pasiva' => $pasiva,
            'total_activa' => $total_activa,
            'total_pasiva' => $total_pasiva,
            'laba' => $laba,
            'selisih' => $total_activa - $total_pasiva
        ]);
    }
}