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

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

    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,
            COALESCE(SUM(jd.debit),0) as debit,
            COALESCE(SUM(jd.kredit),0) as kredit
        ');
        $this->db->from('accounts a');

        // ================= JOIN
        $this->db->join('journal_details jd','a.id = jd.account_id','LEFT');
        $this->db->join('journals j','j.id = jd.journal_id','LEFT');

        // ================= FILTER AKUN
        $this->db->where('a.kategori','laba_rugi');
        $this->db->where('a.is_active',1);

        // ================= FILTER TANGGAL (AMAN)
        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();

        $revenue = 0;
        $expense = 0;

        foreach ($rows as $r) {

            if ($r->tipe == 'revenue') {
                $saldo = $r->kredit - $r->debit;
                $revenue += $saldo;
            }

            if ($r->tipe == 'expense') {
                $saldo = $r->debit - $r->kredit;
                $expense += $saldo;
            }
        }

        echo json_encode([
            'data' => $rows,
            'revenue' => $revenue,
            'expense' => $expense,
            'laba' => $revenue - $expense
        ]);
    }
}