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

class Generateneracasaldo 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');
    }

    // =========================
    // AMBIL DATA NERACA SALDO
    // DIPAKAI OLEH AJAX & PDF
    // =========================
    private function get_neracasaldo_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');

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

        $total_debit  = 0;
        $total_kredit = 0;

        foreach($rows as $row){

            $row->debit  = (float)$row->debit;
            $row->kredit = (float)$row->kredit;

            $total_debit  += $row->debit;
            $total_kredit += $row->kredit;
        }

        return [
            'tanggal_awal'  => $tanggal_awal,
            'tanggal_akhir' => $tanggal_akhir,
            'rows'          => $rows,
            'total_debit'   => $total_debit,
            'total_kredit'  => $total_kredit
        ];
    }

    public function get_data()
    {
        $result = $this->get_neracasaldo_data();

        echo json_encode($result['rows']);
    }

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

        if (ob_get_length()) {
            ob_end_clean();
        }

        // ==========================================
        // DATA
        // ==========================================
        $neracasaldo = $this->get_neracasaldo_data();

        // ==========================================
        // PERUSAHAAN
        // ==========================================
        $company = $this->db->get('pengaturan')->row();

        // ==========================================
        // PERIODE
        // ==========================================
        if(!empty($neracasaldo['tanggal_awal']) && !empty($neracasaldo['tanggal_akhir'])){

            $periodeStr = 'Periode : '
                . date('d-m-Y',strtotime($neracasaldo['tanggal_awal']))
                .' s/d '
                . date('d-m-Y',strtotime($neracasaldo['tanggal_akhir']));

        }else{

            $periodeStr = 'Seluruh Periode';

        }

        // ==========================================
        // PDF
        // ==========================================
        require_once(APPPATH.'third_party/fpdf/fpdf.php');
        require_once(APPPATH.'libraries/PDF_Neracasaldo.php');

        $pdf = new PDF('P','mm','A4');
        $pdf->SetMargins(10,10,10);

        $pdf->setHeaderData(
            $company->nama_perusahaan,
            $company->alamat_perusahaan,
            FCPATH.'uploads/img/logo-ljn.png'
        );

        $pdf->setInfoLaporan($periodeStr);

        $pdf->AddPage();

        $pdf->NeracaSaldoTable(
            $neracasaldo['rows'],
            $neracasaldo['total_debit'],
            $neracasaldo['total_kredit']
        );

        $pdf->NeracaSaldoRingkasan(
            $neracasaldo['total_debit'],
            $neracasaldo['total_kredit']
        );

        $pdf->Pembuat(
            $this->session->userdata('nama') ?: 'Administrator',
            'Finance Department'
        );

        $filename = 'Neraca_Saldo_'.date('YmdHis').'.pdf';

        $pdf->Output('I',$filename);
        exit;
    }
}