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

class Neracasaldo 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_saldo"];
        $this->load->view('partials/header', $data);
        $this->load->view('laporan/neraca_saldo');
        $this->load->view('partials/footer');
    }

    public function get_data()
    {
        $tanggal_awal  = $this->input->get('tanggal_awal');
        $tanggal_akhir = $this->input->get('tanggal_akhir');

        $this->db->select("
            accounts.id,
            accounts.kode_akun,
            accounts.nama_akun,
            accounts.kategori,
            accounts.tipe,
            COALESCE(SUM(journal_details.debit),0) AS debit,
            COALESCE(SUM(journal_details.kredit),0) AS kredit
        ");

        $this->db->from('accounts');

        if (!empty($tanggal_awal) && !empty($tanggal_akhir)) {

            $this->db->join(
                "(SELECT jd.*
                    FROM journal_details jd
                    JOIN journals j ON j.id = jd.journal_id
                    WHERE j.tanggal BETWEEN ".$this->db->escape($tanggal_awal)."
                    AND ".$this->db->escape($tanggal_akhir)."
                ) journal_details",
                "journal_details.account_id = accounts.id",
                "left",
                false
            );

        } else {

            $this->db->join(
                'journal_details',
                'journal_details.account_id = accounts.id',
                'left'
            );

        }

        $rows = $this->db
            ->where('accounts.is_active', 1)
            ->group_by('accounts.id')
            ->order_by('accounts.kode_akun', 'ASC')
            ->get()
            ->result();

        echo json_encode($rows);
    }
}