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

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

    // =========================
    // AMBIL DATA LABA RUGI (DIPAKAI BERSAMA OLEH get_data() & generatepdf())
    // =========================
    private function get_labarugi_data($tanggal_dari = null, $tanggal_sampai = null)
    {
        $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();

        $pendapatan = [];
        $beban      = [];

        $revenue = 0;
        $expense = 0;

        foreach ($rows as $r) {

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

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

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

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

        return [
            'data'            => $rows,
            'pendapatan'      => $pendapatan,
            'beban'           => $beban,
            'revenue'         => $revenue,
            'expense'         => $expense,
            'total_pendapatan'=> $revenue,
            'total_beban'     => $expense,
            'laba'            => $revenue - $expense
        ];
    }

    // =========================
    // GET DATA LABA RUGI (JSON, untuk AJAX/datatable)
    // =========================
    public function get_data()
    {
        $tanggal_dari   = $this->input->get('tanggal_dari');
        $tanggal_sampai = $this->input->get('tanggal_sampai');

        $result = $this->get_labarugi_data($tanggal_dari, $tanggal_sampai);

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

    // =========================
    // PDF GENERATE — LABA RUGI
    // =========================
    public function generatepdf($start = null, $end = null)
    {
        if ($this->session->userdata('role') != 'Admin') {
            show_error('Akses ditolak', 403);
        }

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

        // Normalisasi parameter URL (0000-00-00 dianggap kosong)
        $tanggal_dari   = (!empty($start) && $start != '0000-00-00') ? $start : null;
        $tanggal_sampai = (!empty($end)   && $end   != '0000-00-00') ? $end   : null;

        // =============================================================
        // AMBIL DATA
        // =============================================================
        $labarugi = $this->get_labarugi_data($tanggal_dari, $tanggal_sampai);

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

        // =============================================================
        // BUILD STRING PERIODE
        // =============================================================
        $periodeStr = (!empty($tanggal_dari) && !empty($tanggal_sampai))
            ? 'Periode : ' . date('d-m-Y', strtotime($tanggal_dari))
              . ' s/d ' . date('d-m-Y', strtotime($tanggal_sampai))
            : ((!empty($tanggal_sampai))
                ? 'Per Tanggal : ' . date('d-m-Y', strtotime($tanggal_sampai))
                : 'Per Tanggal : ' . date('d-m-Y'));

        // =============================================================
        // LOAD LIBRARY PDF
        // =============================================================
        require_once(APPPATH . 'third_party/fpdf/fpdf.php');
        require_once(APPPATH . 'libraries/PDF_Labarugi.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('P', 'A4');
        $pdf->LabaRugiTable(
            $labarugi['pendapatan'],
            $labarugi['beban'],
            $labarugi['total_pendapatan'],
            $labarugi['total_beban']
        );
        $pdf->LabaRugiRingkasan($labarugi['laba']);
        $pdf->Pembuat('Tito Ngudiana', 'Finance Department');

        // =============================================================
        // OUTPUT
        // =============================================================
        $filename = 'Laba_Rugi_' . date('YmdHis') . '.pdf';
        $pdf->Output('D', $filename);
        exit;
    }
}