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

class Grafik extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        cek_session_login();

        $this->load->model('model_konsumen', 'konsumen');

        // === [BARU] pastikan model_data tersedia,
        // karena omset(), omset_produk(), dll. pakai $this->model_data
        if (!isset($this->model_data)) {
            $this->load->model('model_data', 'model_data');
        }

        $this->perPage = 10;
        $this->title   = info()['title'];
    }

    public function index($id = null)
    {
        cek_menu_akses();

        $data['title'] = "Grafik | " . $this->title;
        $data['filter_bahan_produk'] = $this->db
            ->select('id, title')
            ->from('bahan')
            ->order_by('title', 'ASC')
            ->get()
            ->result();
        $data['filter_kategori_produk'] = $this->db
            ->select('id_jenis, jenis_cetakan')
            ->from('jenis_cetakan')
            ->order_by('jenis_cetakan', 'ASC')
            ->get()
            ->result();
        $data['filter_produk'] = $this->db
            ->select('id, title, id_jenis')
            ->from('produk')
            ->order_by('title', 'ASC')
            ->get()
            ->result();
        $this->template->load('main/themes', 'penjualan/grafik', $data);
    }

    /**
     * ===========================
     * 1. OMSET BULANAN (per hari)
     * dipakai oleh load_chart_omset(bulan)
     *
     * OUTPUT:
     * {
     *   "bulan":"Oktober",
     *   "omset":[
     *     {"total":12345,"tanggal":"TGL.1"},
     *     {"total":67890,"tanggal":"TGL.2"},
     *     ...
     *   ]
     * }
     * ===========================
     */
    public function omset()
    {
        $page = $this->input->post('bulan');
        $tahunReq = $this->input->post('tahun', TRUE);
        // bulan yg dipilih, fallback ke bulan berjalan
        $bulan = !empty($page) ? (int) $page : (int) date("m");
        $bulan = max(1, min(12, $bulan));
        $tahun = !empty($tahunReq) ? (int)$tahunReq : (int)date("Y");

        // data harian via model_data existing
        $totalRec = $this->model_data->grafik_omset($bulan, $tahun);

        $mapHarian = array();
        if (!empty($totalRec)) {
            foreach ($totalRec as $row) {
                $hari = (int) $row->hari;
                if (!isset($mapHarian[$hari])) {
                    $mapHarian[$hari] = 0;
                }
                $mapHarian[$hari] += (float) $row->Total;
            }
        }

        $hasil = array('omset' => array());
        $jumlahHari = cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun);
        for ($hari = 1; $hari <= $jumlahHari; $hari++) {
            $hasil['omset'][] = array(
                'total'   => isset($mapHarian[$hari]) ? $mapHarian[$hari] : 0,
                'tanggal' => 'TGL.' . $hari
            );
        }

        // label bulan untuk header card & badge
        $bulanLabel = array('bulan' => getBulan($bulan), 'tahun' => (string)$tahun);

        $array_merge = array_merge($hasil, $bulanLabel);
        print json_encode($array_merge);
    }

    /**
     * ===========================
     * 2. OMSET PER PRODUK (bulanan)
     * dipakai oleh load_chart_omset_produk(bulan)
     *
     * OUTPUT:
     * {
     *   "bulan":"Oktober",
     *   "omset":[
     *     {"title":"Print A3","harga":2302100},
     *     {"title":"Nota NCR","harga":850000},
     *     ...
     *   ]
     * }
     * ===========================
     */
    public function omset_produk()
    {
        $page = $this->input->post('bulan');
        $tahunReq = $this->input->post('tahun', TRUE);
        $idBahan = (int)$this->input->post('id_bahan', TRUE);
        $idKategori = (int)$this->input->post('id_kategori', TRUE);
        $idProduk = (int)$this->input->post('id_produk', TRUE);
        $groupBy = strtolower((string)$this->input->post('group_by', TRUE));
        $groupBy = in_array($groupBy, array('kategori', 'produk', 'bahan'), TRUE) ? $groupBy : 'produk';
        $hari = date("d");

        $bulan = !empty($page) ? $page : date("m");
        $tahun = !empty($tahunReq) ? (int)$tahunReq : (int)date("Y");

        $totalRec = $this->model_data->grafik_omset_produk($bulan, $tahun, $idBahan, $idKategori, $idProduk, $groupBy);

        $hasil = array();
        if (!empty($totalRec)) {
            foreach ($totalRec as $row) {
                $hasil['omset'][] = array(
                    'title' => $row->title,
                    'harga' => (float)$row->Total
                );
            }
        } else {
            // fallback diperbaiki
            $hasil['omset'][] = array(
                'title' => "TGL." . $hari,
                'harga' => 0
            );
        }

        $bulanLabel = array('bulan' => getBulan($bulan), 'tahun' => (string)$tahun);
        $array_merge = array_merge($hasil, $bulanLabel);
        print json_encode($array_merge);
    }

    /**
     * ===========================
     * 3. OMSET TAHUNAN (per bulan)
     * dipakai oleh load_chart_omset_tahun(tahun)
     *
     * OUTPUT:
     * {
     *   "tahun":"2025",
     *   "omset":[
     *     {"bulan":"Januari","total":12345678},
     *     {"bulan":"Februari","total":9876543},
     *     ...
     *   ]
     * }
     * ===========================
     */
    public function omset_tahunan()
    {
        $tahunReq = $this->input->post('tahun', TRUE);
        $tahun    = !empty($tahunReq) ? $tahunReq : date("Y");
        $tahun    = (int)$tahun;

        $hasil          = array();
        $hasil['omset'] = array();

        // loop 12 bulan (1..12), totalin per bulan
        for ($m = 1; $m <= 12; $m++) {
            $bulanStr   = str_pad($m, 2, "0", STR_PAD_LEFT);
            $monthlyRows = $this->model_data->grafik_omset($bulanStr, $tahun);

            $totalBulan = 0;
            if (!empty($monthlyRows)) {
                foreach ($monthlyRows as $row) {
                    // di omset() bulanan kamu pakai $row->Total sebagai nominal per hari
                    $totalBulan += (float)$row->Total;
                }
            }

            $hasil['omset'][] = array(
                'bulan' => getBulan($bulanStr), // "Januari", ...
                'total' => $totalBulan
            );
        }

        $hasil['tahun'] = (string)$tahun;
        print json_encode($hasil);
    }

    /**
     * ===========================
     * 4. OMSET PRODUK TAHUNAN
     * dipakai oleh load_chart_omset_produk_tahun(tahun)
     *
     * OUTPUT:
     * {
     *   "tahun":"2025",
     *   "omset":[
     *     {"title":"Print A3","harga":15000000},
     *     {"title":"Nota NCR","harga":4800000},
     *     ...
     *   ]
     * }
     * ===========================
     */
    public function omset_produk_tahunan()
    {
        $tahunReq = $this->input->post('tahun', TRUE);
        $idBahan  = (int)$this->input->post('id_bahan', TRUE);
        $idKategori = (int)$this->input->post('id_kategori', TRUE);
        $idProduk = (int)$this->input->post('id_produk', TRUE);
        $groupBy = strtolower((string)$this->input->post('group_by', TRUE));
        $groupBy = in_array($groupBy, array('kategori', 'produk', 'bahan'), TRUE) ? $groupBy : 'produk';
        $tahun    = !empty($tahunReq) ? $tahunReq : date("Y");
        $tahun    = (int)$tahun;

        // akumulasi total per produk sepanjang tahun
        $akumulasiProduk = array();

        for ($m = 1; $m <= 12; $m++) {
            $bulanStr   = str_pad($m, 2, "0", STR_PAD_LEFT);
            $monthlyRows = $this->model_data->grafik_omset_produk($bulanStr, $tahun, $idBahan, $idKategori, $idProduk, $groupBy);

            if (!empty($monthlyRows)) {
                foreach ($monthlyRows as $row) {
                    $namaProduk = $row->title;
                    $nominal    = (float)$row->Total;

                    if (!isset($akumulasiProduk[$namaProduk])) {
                        $akumulasiProduk[$namaProduk] = 0;
                    }
                    $akumulasiProduk[$namaProduk] += $nominal;
                }
            }
        }

        // urutkan produk terbesar -> kecil
        arsort($akumulasiProduk);

        $finalList = array();
        foreach ($akumulasiProduk as $produkNama => $totalNominal) {
            $finalList['omset'][] = array(
                'title' => $produkNama,
                'harga' => $totalNominal
            );
        }

        if (empty($finalList)) {
            $hari = date("d");
            $finalList['omset'][] = array(
                'title' => "TGL." . $hari,
                'harga' => 0
            );
        }

        $finalList['tahun'] = (string)$tahun;
        print json_encode($finalList);
    }

    /**
     * ===========================
     * 5. perbulan() & pertahun() (FITUR LAIN)
     * Bagian original untuk buyer baru/lama, tetap dipertahankan.
     * ===========================
     */
    public function perbulan()
    {
        $data['title'] = "Grafik Perbulan | " . $this->title;
        $month = $this->input->get('month') ?? date('m'); // Default to current month
        $year  = $this->input->get('year') ?? date('Y');  // Default to current year

        $data['bulan']        = getBulan($month) . ' ' . $year;
        $data['buyers_data']  = $this->konsumen->get_daily_buyers_data($month, $year);

        // siapkan array buyer baru vs lama
        $new_buyers = [];
        $old_buyers = [];

        foreach ($data['buyers_data'] as $key => &$row) {
            // format tanggal jadi "01 Januari 2023"
            $row['transaction_date'] = date("d F Y", strtotime($row['transaction_date']));
            $new_buyers[] = $row['new_buyers'];
            $old_buyers[] = $row['old_buyers'];
        }

        // filter untuk dropdown
        $data['months'] = range(1, 12);
        $data['years']  = range(date('Y') - 2, date('Y'));

        $data['baru'] = array_sum($new_buyers);
        $data['lama'] = array_sum($old_buyers);

        $this->template->load('main/themes', 'grafik/grafik_perbulan', $data);
    }

    public function pertahun()
    {
        $data['title'] = "Grafik Pertahun | " . $this->title;
        $year = $this->input->get('year') ?? date('Y'); // Default to current year

        $data['buyers_data'] = $this->konsumen->get_monthly_buyers_data($year);

        // nama bulan Indonesia
        $month_names = [
            1  => 'Januari',   2 => 'Februari', 3 => 'Maret',
            4  => 'April',     5 => 'Mei',      6 => 'Juni',
            7  => 'Juli',      8 => 'Agustus',  9 => 'September',
            10 => 'Oktober',  11 => 'November', 12 => 'Desember'
        ];

        $data['tahun']       = $year;
        $data['labels']      = [];
        $data['new_buyers']  = [];
        $data['old_buyers']  = [];

        foreach ($data['buyers_data'] as $row) {
            $data['labels'][]      = $month_names[$row['month']];
            $data['new_buyers'][]  = $row['new_buyers'];
            $data['old_buyers'][]  = $row['old_buyers'];
        }

        $data['baru'] = array_sum($data['new_buyers']);
        $data['lama'] = array_sum($data['old_buyers']);

        // tahun dropdown: 5 tahun terakhir
        $data['years'] = range(date('Y') - 5, date('Y'));

        $this->template->load('main/themes', 'grafik/grafik_pertahun', $data);
    }

    /**
     * =========================================================
     * 6. PENGELUARAN (KAS KELUAR) — BULANAN
     * Digunakan oleh load_pengeluaran_bulan()
     * return: {
     *   pengeluaran: [{tanggal:'TGL.01', total:12345}, ...],
     *   bulan: 'Januari',
     *   kpi_total: 999999
     * }
     * =========================================================
     */
    public function pengeluaran()
    {
        $bulanReq = $this->input->post('bulan', TRUE);
        $tahunReq = $this->input->post('tahun', TRUE);

        $bulan = !empty($bulanReq) ? (int)$bulanReq : (int)date('m');
        $bulan = max(1, min(12, $bulan));
        $tahun = !empty($tahunReq) ? (int)$tahunReq : (int)date('Y');

        // agregasi harian
        $rows = $this->db
            ->select('DATE(kk.tanggal) AS tgl, SUM(kk.jumlah) AS total', false)
            ->from('kas_keluar kk')
            ->where('MONTH(kk.tanggal)', (int)$bulan)
            ->where('YEAR(kk.tanggal)', (int)$tahun)
            ->group_by('DATE(kk.tanggal)')
            ->order_by('tgl','ASC')
            ->get()->result();

        $mapHarian = [];
        foreach ($rows as $r) {
            $hari = (int)date('j', strtotime($r->tgl));
            $mapHarian[$hari] = (float)$r->total;
        }

        $hasil = ['pengeluaran' => []];
        $kpi = 0;
        $jumlahHari = cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun);
        for ($hari = 1; $hari <= $jumlahHari; $hari++) {
            $total = isset($mapHarian[$hari]) ? $mapHarian[$hari] : 0;
            $hasil['pengeluaran'][] = [
                'total' => $total,
                'tanggal' => 'TGL.'.$hari,
            ];
            $kpi += $total;
        }

        $hasil['bulan']     = getBulan($bulan);
        $hasil['tahun']     = (string)$tahun;
        $hasil['kpi_total'] = $kpi;

        print json_encode($hasil);
    }

    /**
     * =========================================================
     * 7. PENGELUARAN — TAHUNAN
     * Digunakan oleh load_pengeluaran_tahun()
     * return:
     * {
     *   pengeluaran:[{bulan:'Januari', total:...}, ... 12x ],
     *   tahun:2025,
     *   kpi_total:...
     * }
     * =========================================================
     */
    public function pengeluaran_tahun()
    {
        $tahunReq = $this->input->post('tahun', TRUE);
        $tahun    = !empty($tahunReq) ? (int)$tahunReq : (int)date('Y');

        $rows = $this->db
            ->select('MONTH(kk.tanggal) AS bln, SUM(kk.jumlah) AS total', false)
            ->from('kas_keluar kk')
            ->where('YEAR(kk.tanggal)', $tahun)
            ->group_by('MONTH(kk.tanggal)')
            ->order_by('bln','ASC')
            ->get()->result();

        $hasil = ['pengeluaran'=>[]];
        $kpi   = 0;
        for ($m=1; $m<=12; $m++) {
            $found = 0;
            if (!empty($rows)) {
                foreach ($rows as $r) {
                    if ((int)$r->bln === $m) {
                        $found = (float)$r->total; break;
                    }
                }
            }
            $hasil['pengeluaran'][] = [
                'bulan' => getBulan(str_pad($m,2,'0',STR_PAD_LEFT)),
                'total' => $found
            ];
            $kpi += $found;
        }

        $hasil['tahun']     = $tahun;
        $hasil['kpi_total'] = $kpi;

        print json_encode($hasil);
    }

    /**
     * =========================================================
     * 8. PEMBELIAN — BULANAN
     * Digunakan oleh load_pembelian_bulan()
     * return:
     * {
     *   pembelian:[{tanggal:'TGL.01', total:...}, ...],
     *   bulan:'Januari',
     *   kpi_total:...
     * }
     * =========================================================
     */
    public function pembelian()
    {
        $bulanReq = $this->input->post('bulan', TRUE);
        $tahunReq = $this->input->post('tahun', TRUE);

        $bulan = !empty($bulanReq) ? (int)$bulanReq : (int)date('m');
        $bulan = max(1, min(12, $bulan));
        $tahun = !empty($tahunReq) ? (int)$tahunReq : (int)date('Y');

        $rows = $this->db
            ->select('DATE(p.tgl_pembelian) AS tgl, SUM(pd.jumlah * pd.harga) AS total', false)
            ->from('pembelian_detail pd')
            ->join('pembelian p','pd.id_pembelian = p.id_pembelian')
            ->where('MONTH(p.tgl_pembelian)', (int)$bulan)
            ->where('YEAR(p.tgl_pembelian)', (int)$tahun)
            ->group_by('DATE(p.tgl_pembelian)')
            ->order_by('tgl','ASC')
            ->get()->result();

        $mapHarian = [];
        foreach ($rows as $r) {
            $hari = (int)date('j', strtotime($r->tgl));
            $mapHarian[$hari] = (float)$r->total;
        }

        $hasil = ['pembelian'=>[]];
        $kpi = 0;
        $jumlahHari = cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun);
        for ($hari = 1; $hari <= $jumlahHari; $hari++) {
            $total = isset($mapHarian[$hari]) ? $mapHarian[$hari] : 0;
            $hasil['pembelian'][] = [
                'total' => $total,
                'tanggal' => 'TGL.'.$hari,
            ];
            $kpi += $total;
        }

        $hasil['bulan']     = getBulan($bulan);
        $hasil['tahun']     = (string)$tahun;
        $hasil['kpi_total'] = $kpi;

        print json_encode($hasil);
    }

    /**
     * =========================================================
     * 9. PEMBELIAN — TAHUNAN
     * Digunakan oleh load_pembelian_tahun()
     * return:
     * {
     *   pembelian:[{bulan:'Januari', total:...}, ...],
     *   tahun:2025,
     *   kpi_total:...
     * }
     * =========================================================
     */
    public function pembelian_tahun()
    {
        $tahunReq = $this->input->post('tahun', TRUE);
        $tahun    = !empty($tahunReq) ? (int)$tahunReq : (int)date('Y');

        $rows = $this->db
            ->select('MONTH(p.tgl_pembelian) AS bln, SUM(pd.jumlah * pd.harga) AS total', false)
            ->from('pembelian_detail pd')
            ->join('pembelian p','pd.id_pembelian = p.id_pembelian')
            ->where('YEAR(p.tgl_pembelian)', $tahun)
            ->group_by('MONTH(p.tgl_pembelian)')
            ->order_by('bln','ASC')
            ->get()->result();

        $hasil = ['pembelian'=>[]];
        $kpi   = 0;
        for ($m=1; $m<=12; $m++) {
            $found = 0;
            if (!empty($rows)) {
                foreach ($rows as $r) {
                    if ((int)$r->bln === $m) { $found = (float)$r->total; break; }
                }
            }
            $hasil['pembelian'][] = [
                'bulan' => getBulan(str_pad($m,2,'0',STR_PAD_LEFT)),
                'total' => $found
            ];
            $kpi += $found;
        }

        $hasil['tahun']     = $tahun;
        $hasil['kpi_total'] = $kpi;

        print json_encode($hasil);
    }

    /**
     * =========================================================
     * 10. PENDAPATAN — TAHUNAN
     * Digunakan oleh load_chart_pendapatan_tahun()
     * return:
     * {
     *   "tahun": 2025,
     *   "kpi_total": 12345678,
     *   "pendapatan": [
     *      {"bulan":"Januari","total":1000000},
     *      {"bulan":"Februari","total":2000000},
     *      ... sampai Desember
     *   ]
     * }
     * =========================================================
     */
    public function pendapatan_tahun()
    {
        $tahunReq = $this->input->post('tahun', TRUE);
        $tahun    = !empty($tahunReq) ? (int)$tahunReq : (int)date('Y');

        // total bayar (jml_bayar) per bulan dari tabel bayar_invoice_detail
        $rows = $this->db
            ->select('MONTH(b.tgl_bayar) AS bln, SUM(b.jml_bayar) AS total', false)
            ->from('bayar_invoice_detail b')
            ->where('YEAR(b.tgl_bayar)', $tahun)
            ->group_by('MONTH(b.tgl_bayar)')
            ->order_by('bln','ASC')
            ->get()->result();

        $hasil = ['pendapatan'=>[]];
        $kpi   = 0;

        // loop 12 bulan supaya urut Jan..Des dan tetap muncul meskipun 0
        for ($m=1; $m<=12; $m++) {
            $found = 0;
            if (!empty($rows)) {
                foreach ($rows as $r) {
                    if ((int)$r->bln === $m) {
                        $found = (float)$r->total;
                        break;
                    }
                }
            }

            $hasil['pendapatan'][] = [
                'bulan' => getBulan(str_pad($m,2,'0',STR_PAD_LEFT)),
                'total' => $found
            ];
            $kpi += $found;
        }

        $hasil['tahun']     = $tahun;
        $hasil['kpi_total'] = $kpi;

        print json_encode($hasil);
    }

    /**
     * =========================================================
     * 11. KOMPARASI BULANAN (BARU)
     * Digunakan oleh load_komparasi_bulan(bulan) di view dashboard.
     *
     * Kita ambil 4 metrik dalam 1 bulan tertentu (per hari):
     *  - pendapatan  : total bayar (bayar_invoice_detail)
     *  - omset       : total nilai order (model_data->grafik_omset)
     *  - pengeluaran : kas keluar (kas_keluar)
     *  - pembelian   : pembelian bahan (pembelian_detail * harga)
     *
     * Output:
     * {
     *   "periode":"Oktober",
     *   "labels":["TGL.01","TGL.02",...],
     *   "pendapatan":[10000,20000,...],
     *   "omset":[...],
     *   "pengeluaran":[...],
     *   "pembelian":[...]
     * }
     * =========================================================
     */
    public function komparasi()
    {
        $bulanReq = $this->input->post('bulan', TRUE);
        $tahunReq = $this->input->post('tahun', TRUE);

        $bulan = !empty($bulanReq) ? $bulanReq : date('m');
        $tahun = !empty($tahunReq) ? $tahunReq : date('Y');

        $bulanInt = (int)$bulan;
        $tahunInt = (int)$tahun;

        // --- 11a. PENDAPATAN (bayar_invoice_detail) per hari
        $rowsPendapatan = $this->db
            ->select('DAY(b.tgl_bayar) AS hari, SUM(b.jml_bayar) AS total', false)
            ->from('bayar_invoice_detail b')
            ->where('MONTH(b.tgl_bayar)', $bulanInt)
            ->where('YEAR(b.tgl_bayar)',  $tahunInt)
            ->group_by('DAY(b.tgl_bayar)')
            ->order_by('hari','ASC')
            ->get()->result();

        $mapPendapatan = [];
        foreach ($rowsPendapatan as $r) {
            $mapPendapatan[(int)$r->hari] = (float)$r->total;
        }

        // --- 11b. OMSET (model_data->grafik_omset) per hari
        $rowsOmset = $this->model_data->grafik_omset(str_pad($bulanInt,2,"0",STR_PAD_LEFT), $tahunInt);
        $mapOmset  = [];
        if (!empty($rowsOmset)) {
            foreach ($rowsOmset as $r) {
                // $r->hari, $r->Total
                $mapOmset[(int)$r->hari] = (float)$r->Total;
            }
        }

        // --- 11c. PENGELUARAN (kas_keluar) per hari
        $rowsPengeluaran = $this->db
            ->select('DAY(kk.tanggal) AS hari, SUM(kk.jumlah) AS total', false)
            ->from('kas_keluar kk')
            ->where('MONTH(kk.tanggal)', $bulanInt)
            ->where('YEAR(kk.tanggal)',  $tahunInt)
            ->group_by('DAY(kk.tanggal)')
            ->order_by('hari','ASC')
            ->get()->result();

        $mapPengeluaran = [];
        foreach ($rowsPengeluaran as $r) {
            $mapPengeluaran[(int)$r->hari] = (float)$r->total;
        }

        // --- 11d. PEMBELIAN (pembelian_detail * harga) per hari
        $rowsPembelian = $this->db
            ->select('DAY(p.tgl_pembelian) AS hari, SUM(pd.jumlah * pd.harga) AS total', false)
            ->from('pembelian_detail pd')
            ->join('pembelian p','pd.id_pembelian = p.id_pembelian')
            ->where('MONTH(p.tgl_pembelian)', $bulanInt)
            ->where('YEAR(p.tgl_pembelian)',  $tahunInt)
            ->group_by('DAY(p.tgl_pembelian)')
            ->order_by('hari','ASC')
            ->get()->result();

        $mapPembelian = [];
        foreach ($rowsPembelian as $r) {
            $mapPembelian[(int)$r->hari] = (float)$r->total;
        }

        // --- 11e. Bentuk labels harian konsisten 1..akhir bulan
        $lastDay = cal_days_in_month(CAL_GREGORIAN, $bulanInt, $tahunInt);

        $labels        = [];
        $pendapatanArr = [];
        $omsetArr      = [];
        $pengeluaranArr= [];
        $pembelianArr  = [];

        for ($d=1; $d<=$lastDay; $d++) {
            $labels[]         = 'TGL.'.str_pad($d,2,'0',STR_PAD_LEFT);
            $pendapatanArr[]  = isset($mapPendapatan[$d])  ? $mapPendapatan[$d]  : 0;
            $omsetArr[]       = isset($mapOmset[$d])       ? $mapOmset[$d]       : 0;
            $pengeluaranArr[] = isset($mapPengeluaran[$d]) ? $mapPengeluaran[$d] : 0;
            $pembelianArr[]   = isset($mapPembelian[$d])   ? $mapPembelian[$d]   : 0;
        }

        $out = [
            'periode'     => getBulan(str_pad($bulanInt,2,'0',STR_PAD_LEFT)),
            'tahun'       => (string)$tahunInt,
            'labels'      => $labels,
            'pendapatan'  => $pendapatanArr,
            'omset'       => $omsetArr,
            'pengeluaran' => $pengeluaranArr,
            'pembelian'   => $pembelianArr
        ];

        print json_encode($out);
    }

    /**
     * =========================================================
     * 12. KOMPARASI TAHUNAN (BARU)
     * Digunakan oleh load_komparasi_tahun(tahun) di view dashboard.
     *
     * Kita ambil 4 metrik yang sama tapi agregat per BULAN (Jan..Des):
     *  - pendapatan (bayar_invoice_detail)
     *  - omset (model_data->grafik_omset)
     *  - pengeluaran (kas_keluar)
     *  - pembelian (pembelian_detail * harga)
     *
     * Output:
     * {
     *   "periode":"2025",
     *   "labels":["Januari","Februari",...],
     *   "pendapatan":[...12 angka...],
     *   "omset":[...12 angka...],
     *   "pengeluaran":[...12 angka...],
     *   "pembelian":[...12 angka...]
     * }
     * =========================================================
     */
    public function komparasi_tahun()
    {
        $tahunReq = $this->input->post('tahun', TRUE);
        $tahun    = !empty($tahunReq) ? (int)$tahunReq : (int)date('Y');

        // --- 12a. Pendapatan per bulan
        $rowsPendapatan = $this->db
            ->select('MONTH(b.tgl_bayar) AS bln, SUM(b.jml_bayar) AS total', false)
            ->from('bayar_invoice_detail b')
            ->where('YEAR(b.tgl_bayar)', $tahun)
            ->group_by('MONTH(b.tgl_bayar)')
            ->order_by('bln','ASC')
            ->get()->result();
        $mapPendapatan = [];
        foreach ($rowsPendapatan as $r) {
            $mapPendapatan[(int)$r->bln] = (float)$r->total;
        }

        // --- 12b. Omset per bulan
        // kita reuse logika omset_tahunan() tapi langsung hitung di sini
        $mapOmset = [];
        for ($m=1; $m<=12; $m++) {
            $bulanStr   = str_pad($m, 2, "0", STR_PAD_LEFT);
            $monthlyRows = $this->model_data->grafik_omset($bulanStr, $tahun);

            $totalBulan = 0;
            if (!empty($monthlyRows)) {
                foreach ($monthlyRows as $row) {
                    $totalBulan += (float)$row->Total;
                }
            }
            $mapOmset[$m] = $totalBulan;
        }

        // --- 12c. Pengeluaran per bulan
        $rowsPengeluaran = $this->db
            ->select('MONTH(kk.tanggal) AS bln, SUM(kk.jumlah) AS total', false)
            ->from('kas_keluar kk')
            ->where('YEAR(kk.tanggal)', $tahun)
            ->group_by('MONTH(kk.tanggal)')
            ->order_by('bln','ASC')
            ->get()->result();
        $mapPengeluaran = [];
        foreach ($rowsPengeluaran as $r) {
            $mapPengeluaran[(int)$r->bln] = (float)$r->total;
        }

        // --- 12d. Pembelian per bulan
        $rowsPembelian = $this->db
            ->select('MONTH(p.tgl_pembelian) AS bln, SUM(pd.jumlah * pd.harga) AS total', false)
            ->from('pembelian_detail pd')
            ->join('pembelian p','pd.id_pembelian = p.id_pembelian')
            ->where('YEAR(p.tgl_pembelian)', $tahun)
            ->group_by('MONTH(p.tgl_pembelian)')
            ->order_by('bln','ASC')
            ->get()->result();
        $mapPembelian = [];
        foreach ($rowsPembelian as $r) {
            $mapPembelian[(int)$r->bln] = (float)$r->total;
        }

        // --- 12e. susun final arrays Jan..Des
        $labels        = [];
        $pendapatanArr = [];
        $omsetArr      = [];
        $pengeluaranArr= [];
        $pembelianArr  = [];

        for ($m=1; $m<=12; $m++) {
            $labels[]         = getBulan(str_pad($m,2,'0',STR_PAD_LEFT));
            $pendapatanArr[]  = isset($mapPendapatan[$m])  ? $mapPendapatan[$m]  : 0;
            $omsetArr[]       = isset($mapOmset[$m])       ? $mapOmset[$m]       : 0;
            $pengeluaranArr[] = isset($mapPengeluaran[$m]) ? $mapPengeluaran[$m] : 0;
            $pembelianArr[]   = isset($mapPembelian[$m])   ? $mapPembelian[$m]   : 0;
        }

        $out = [
            'periode'     => (string)$tahun,
            'labels'      => $labels,
            'pendapatan'  => $pendapatanArr,
            'omset'       => $omsetArr,
            'pengeluaran' => $pengeluaranArr,
            'pembelian'   => $pembelianArr
        ];

        print json_encode($out);
    }

    /**
     * Data seluruh kartu untuk periode lustrum (5 tahun) atau dekade (10 tahun).
     * Setiap titik mewakili total satu tahun agar perbandingan jangka panjang tetap ringkas.
     */
    public function periode_jangka()
    {
        $tahunAkhir = (int) $this->input->post('tahun', TRUE);
        $tahunAkhir = $tahunAkhir > 0 ? $tahunAkhir : (int) date('Y');
        $rentang = (int) $this->input->post('rentang', TRUE);
        $rentang = $rentang === 10 ? 10 : 5;
        $tahunAwal = $tahunAkhir - $rentang + 1;
        $tanggalAwal = $tahunAwal.'-01-01';
        $tanggalAkhir = $tahunAkhir.'-12-31 23:59:59';

        $toMap = static function ($rows) {
            $map = [];
            foreach ($rows as $row) {
                $map[(string) $row->periode_key] = (float) $row->total;
            }
            return $map;
        };

        $pendapatan = $toMap($this->db
            ->select('YEAR(b.tgl_bayar) AS periode_key, SUM(b.jml_bayar) AS total', false)
            ->from('bayar_invoice_detail b')
            ->where('b.tgl_bayar >=', $tanggalAwal)
            ->where('b.tgl_bayar <=', $tanggalAkhir)
            ->group_by('YEAR(b.tgl_bayar)')
            ->get()->result());

        $omset = $toMap($this->db
            ->select('YEAR(i.tgl_trx) AS periode_key, SUM(d.jumlah * d.harga) AS total', false)
            ->from('invoice_detail d')
            ->join('invoice i', 'd.id_invoice = i.id_invoice')
            ->where('i.tgl_trx >=', $tanggalAwal)
            ->where('i.tgl_trx <=', $tanggalAkhir)
            ->where('i.status !=', 'baru')
            ->where('i.status !=', 'batal')
            ->group_by('YEAR(i.tgl_trx)')
            ->get()->result());

        $pengeluaran = $toMap($this->db
            ->select('YEAR(k.tanggal) AS periode_key, SUM(k.jumlah) AS total', false)
            ->from('kas_keluar k')
            ->where('k.tanggal >=', $tanggalAwal)
            ->where('k.tanggal <=', $tanggalAkhir)
            ->group_by('YEAR(k.tanggal)')
            ->get()->result());

        $pembelian = $toMap($this->db
            ->select('YEAR(p.tgl_pembelian) AS periode_key, SUM(pd.jumlah * pd.harga) AS total', false)
            ->from('pembelian_detail pd')
            ->join('pembelian p', 'pd.id_pembelian = p.id_pembelian')
            ->where('p.tgl_pembelian >=', $tanggalAwal)
            ->where('p.tgl_pembelian <=', $tanggalAkhir)
            ->group_by('YEAR(p.tgl_pembelian)')
            ->get()->result());

        $produkRows = $this->db
            ->select('produk.title, SUM(d.jumlah * d.harga) AS total', false)
            ->from('produk')
            ->join('invoice_detail d', 'produk.id = d.id_produk')
            ->join('invoice i', 'd.id_invoice = i.id_invoice')
            ->where('i.tgl_trx >=', $tanggalAwal)
            ->where('i.tgl_trx <=', $tanggalAkhir)
            ->where('i.status !=', 'baru')
            ->where('i.status !=', 'batal')
            ->group_by('produk.title')
            ->order_by('total', 'DESC')
            ->get()->result();

        $out = [
            'periode' => ($rentang === 10 ? 'Dekade ' : 'Lustrum ').$tahunAwal.' - '.$tahunAkhir,
            'tahun_awal' => $tahunAwal,
            'tahun_akhir' => $tahunAkhir,
            'rentang' => $rentang,
            'labels' => [],
            'pendapatan' => [],
            'omset' => [],
            'pengeluaran' => [],
            'pembelian' => [],
            'produk' => [],
        ];

        for ($tahun = $tahunAwal; $tahun <= $tahunAkhir; $tahun++) {
            $key = (string) $tahun;
            $out['labels'][] = $key;
            $out['pendapatan'][] = $pendapatan[$key] ?? 0;
            $out['omset'][] = $omset[$key] ?? 0;
            $out['pengeluaran'][] = $pengeluaran[$key] ?? 0;
            $out['pembelian'][] = $pembelian[$key] ?? 0;
        }

        foreach ($produkRows as $row) {
            $out['produk'][] = ['title' => (string) $row->title, 'total' => (float) $row->total];
        }
        $out['total_pengeluaran'] = array_sum($out['pengeluaran']);
        $out['total_pembelian'] = array_sum($out['pembelian']);

        $this->output
            ->set_content_type('application/json')
            ->set_output(json_encode($out));
    }

}
