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

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class Transaksi extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        // cek_tabel();
        cek_session_login();
        $this->load->model('model_transaksi');
        $this->load->model('model_app'); // dipakai di index() & cetak_*
        $this->info    = info();
        $this->iduser  = $this->session->idu;
        $this->perPage = 10;
        $this->title   = info()['title'];
        $this->level   = $this->session->level;
    }

    /**
     * index
     */
    public function index()
    {
        cek_menu_akses();
        $data['title']   = 'Laporan Transaksi Penjualan | ' . info()['title'];

        $data['tanggal'] = tgl_sampai_slash(); // default "dd/mm/yyyy - dd/mm/yyyy" (hari ini)
        $data['periode'] = date('M Y');
        $data['pilihan'] = $this->model_app->view('tb_users');
        $data['level']   = $this->level;
        $this->template->load('main/themes', 'transaksi/view_index', $data);
    }

    /**
     * load_data
     */
    public function load_data()
    {
        $jenis = $this->input->post('jenis');
        if ($jenis == 1) {
            $this->harian();
        } else {
            $this->perbulan();
        }
    }

    /**
     * Parse "dd/mm/yyyy - dd/mm/yyyy" atau single "dd/mm/yyyy" ke [Y-m-d, Y-m-d]
     */
    private function _parseRange($rangeStr)
    {
        $toYmd = function ($s) {
            $s = trim((string)$s);
            if ($s === '') return '';
            $dmy = DateTime::createFromFormat('d/m/Y', $s);
            if ($dmy && $dmy->format('d/m/Y') === $s) return $dmy->format('Y-m-d');
            $ymd = DateTime::createFromFormat('Y-m-d', $s);
            if ($ymd && $ymd->format('Y-m-d') === $s) return $s;
            $ts = strtotime($s);
            return $ts ? date('Y-m-d', $ts) : '';
        };

        $start = $end = '';
        $rangeStr = trim((string)$rangeStr);

        if ($rangeStr === '') {
            $today = date('Y-m-d');
            return [$today, $today];
        }

        if (strpos($rangeStr, ' - ') !== false) {
            list($dari, $sampai) = explode(' - ', $rangeStr, 2);
            $start = $toYmd($dari);
            $end   = $toYmd($sampai);
        } else {
            $start = $toYmd($rangeStr);
            $end   = $start;
        }

        if ($start !== '' && $end !== '' && strtotime($start) > strtotime($end)) {
            $tmp = $start; $start = $end; $end = $tmp;
        }
        if ($start === '' && $end === '') {
            $today = date('Y-m-d');
            return [$today, $today];
        }
        if ($start !== '' && $end === '') $end = $start;
        if ($start === '' && $end !== '') $start = $end;

        return [$start, $end];
    }

    /**
     * harian (mendukung rentang tanggal)
     */
    public function harian()
    {
        cek_nput_post('GET');

        $tanggal = $this->input->post('tanggal'); // "dd/mm/yyyy" atau "dd/mm/yyyy - dd/mm/yyyy"
        $user    = $this->input->post('user');    // id user kasir (0 = semua)

        list($startDate, $endDate) = $this->_parseRange($tanggal);

        // Ambil data sesuai range
        $masuk  = ['masuk'  => $this->model_transaksi->getLaporanHarian($startDate, $endDate, $user)];
        $keluar = ['keluar' => $this->model_transaksi->getPengeluaranHarian($startDate, $endDate, $user)];
        $beli   = ['beli'   => $this->model_transaksi->getPembelianHarian($startDate, $endDate, $user)];

        $data['result'] = array_merge($masuk, $keluar, $beli);
        $this->load->view('transaksi/laporan-harian', $data, false);
    }

    /**
     * perbulan
     */
    public function perbulan()
    {
        cek_nput_post('GET');
        $periode = $this->input->post('periode');

        // 🔽 tambahkan ini: ambil user terpilih (id kasir)
        $user = $this->input->post('user'); // pastikan name="user" di form

        $bulan = periode($periode)['bulan'];
        $tahun = periode($periode)['tahun'];

        $date = new DateTime("{$tahun}-{$bulan}-01");

        $data['total_hari'] = $date->format('t');

        // 🔽 jika view kamu butuh list detail bulanan, siapkan di sini (opsional):
        // $data['penjualan']  = $this->model_transaksi->getLaporanBulanan($bulan, $tahun, $user);
        // $data['pengeluaran'] = $this->model_transaksi->getPengeluaranBulanan($bulan, $tahun, $user);
        // $data['pembelian']   = $this->model_transaksi->getPembelianBulanan($bulan, $tahun, $user);

        // 🔽 rekap untuk grafik / ringkasan (SUDAH difilter user)
        $data['laporan']    = $this->model_transaksi->get_laporan($bulan, $tahun, $user);

        // aman saat kosong
        if (!empty($data['laporan'])) {
            $harga_array = array_map(function ($item) {
                return isset($item->TOTAL) ? (float)$item->TOTAL : 0;
            }, $data['laporan']);
            $data['harga_tertinggi'] = !empty($harga_array) ? max($harga_array) : 0;
            $data['harga_terendah']  = !empty($harga_array) ? min($harga_array) : 0;
        } else {
            $data['harga_tertinggi'] = 0;
            $data['harga_terendah']  = 0;
        }

        $this->load->view('transaksi/laporan-bulanan', $data, false);
    }


    /**
     * cetak_pdf (router)
     */
    public function cetak_pdf()
    {
        $jenis = ($this->input->post('jenis'));
        if ($jenis == 1) {
            $this->cetak_harian();
        } else {
            $this->cetak_perbulan();
        }
    }

    /**
     * cetak_harian (ikut rentang tanggal)
     */
    private function cetak_harian()
    {
        $tglStamp        = date("Y_m_d_H_i_s");
        $data['logo']    = FCPATH . 'uploads/' . info()['logo'];
        $data['logop']   = base_url() . 'uploads/' . info()['logo'];
        $data['info']    = info();
        $data['tgl']     = date('d/m/Y');

        $user_trx  = $this->input->post('user_trx');      // id user kasir
        $rangeText = $this->input->post('tanggal');       // "dd/mm/yyyy - dd/mm/yyyy"

        list($startDate, $endDate) = $this->_parseRange($rangeText);

        // User login yang mencetak
        $_user = $this->model_app->view_where('tb_users', ['id_user' => $this->iduser])->row();
        $data['user'] = $_user ? $_user->nama_lengkap : '-';

        $data['periode_name'] = ($startDate === $endDate) ? 'TANGGAL TRANSAKSI' : 'PERIODE TRANSAKSI';
        $data['periode']      = $rangeText;

        // Data
        $masuk  = ['masuk'  => $this->model_transaksi->getLaporanHarian($startDate, $endDate, $user_trx)];
        $keluar = ['keluar' => $this->model_transaksi->getPengeluaranHarian($startDate, $endDate, $user_trx)];
        $beli   = ['beli'   => $this->model_transaksi->getPembelianHarian($startDate, $endDate, $user_trx)];

        $data['result'] = array_merge($masuk, $keluar, $beli);

        $this->load->library('pdf');
        $this->pdf->setPaper('A4', 'potrait');
        $this->pdf->filename = "LAPORAN_TRANSAKSI_" . $tglStamp;
        $this->pdf->load_view('transaksi/cetak_transaksi', $data);
        // $this->load->view('transaksi/cetak_transaksi',$data);
    }

    /**
     * cetak_perbulan
     */
    private function cetak_perbulan()
    {
        $tglStamp      = date("Y_m_d_H_i_s");
        $data['logo']  = FCPATH . 'uploads/' . info()['logo'];
        $data['logop'] = base_url() . 'uploads/' . info()['logo'];
        $data['info']  = info();
        $data['tgl']   = date('d/m/Y');

        $periode = $this->input->post('periode');

        $bulan = periode($periode)['bulan'];
        $tahun = periode($periode)['tahun'];

        // user login yang mencetak
        $_user        = $this->model_app->view_where('tb_users', ['id_user' => $this->iduser])->row();
        $data['user'] = $_user ? $_user->nama_lengkap : '-';

        $data['periode_name'] = 'PERIODE TRANSAKSI';
        $data['periode']      = getBulan($bulan) . ' ' . $tahun;

        $date = new DateTime("{$tahun}-{$bulan}-01");
        $data['total_hari'] = $date->format('t');
        $data['result']     = $this->model_transaksi->get_laporan($bulan, $tahun);

        $this->load->library('pdf');
        $this->pdf->setPaper('A4', 'potrait');
        $this->pdf->filename = "LAPORAN_TRANSAKSI_" . $tglStamp;
        $this->pdf->load_view('transaksi/cetak_transaksi_perbulan', $data);
        // $this->load->view('transaksi/cetak_transaksi_perbulan',$data);
    }

    /**
     * Export Excel (ikut rentang tanggal yang dipilih)
     * Arahkan tombol submit ke: transaksi/export_excel
     */
    public function export_excel()
    {
        // Ambil input
        $user_trx  = $this->input->post('user_trx');   // id kasir
        $rangeText = $this->input->post('tanggal');    // "dd/mm/yyyy - dd/mm/yyyy"
        list($startDate, $endDate) = $this->_parseRange($rangeText);

        // Ambil data (sama persis dengan tampilan layar & PDF)
        $masuk  = $this->model_transaksi->getLaporanHarian($startDate, $endDate, $user_trx);
        $keluar = $this->model_transaksi->getPengeluaranHarian($startDate, $endDate, $user_trx);
        $beli   = $this->model_transaksi->getPembelianHarian($startDate, $endDate, $user_trx);

        // Buat Excel sederhana: 3 sheet (Penjualan, Pengeluaran, Pembelian)
        $spreadsheet = new Spreadsheet();

        // Sheet 1: Penjualan
        $sheet1 = $spreadsheet->getActiveSheet();
        $sheet1->setTitle('Penjualan');
        $sheet1->fromArray(['NO','NO_ORDER','PEMESAN','TGL_ORDER/TGL_TRX','TGL_BAYAR','KASIR','JENIS BAYAR','MASUK'], NULL, 'A1');

        $row = 2; $no = 1; $totalMasuk = 0;
        foreach ($masuk as $m) {
            $sheet1->setCellValue("A{$row}", $no++);
            $sheet1->setCellValue("B{$row}", isset($m['id']) ? $m['id'] : '');
            $sheet1->setCellValue("C{$row}", isset($m['id_konsumen']) ? $m['id_konsumen'] : '');
            $sheet1->setCellValue("D{$row}", isset($m['tgl_trx']) ? $m['tgl_trx'] : '');
            $sheet1->setCellValue("E{$row}", isset($m['tgl_bayar']) ? $m['tgl_bayar'] : '');
            $sheet1->setCellValue("F{$row}", isset($m['fo']) ? $m['fo'] : '');
            $sheet1->setCellValue("G{$row}", isset($m['id_sub_bayar']) ? $m['id_sub_bayar'] : '');
            $sheet1->setCellValue("H{$row}", isset($m['jml_bayar']) ? $m['jml_bayar'] : 0);
            $totalMasuk += (float)($m['jml_bayar'] ?? 0);
            $row++;
        }
        $sheet1->setCellValue("G{$row}", 'Total Penjualan');
        $sheet1->setCellValue("H{$row}", $totalMasuk);

        // Sheet 2: Pengeluaran
        $sheet2 = $spreadsheet->createSheet();
        $sheet2->setTitle('Pengeluaran');
        $sheet2->fromArray(['NO','NO_ORDER','TGL_BAYAR','KASIR','ID AKUN','AKUN (opsional)','KETERANGAN','KELUAR'], NULL, 'A1');

        $row = 2; $no = 1; $totalKeluar = 0;
        foreach ($keluar as $k) {
            $sheet2->setCellValue("A{$row}", $no++);
            $sheet2->setCellValue("B{$row}", isset($k['id']) ? $k['id'] : '');
            $sheet2->setCellValue("C{$row}", isset($k['tgl_bayar']) ? $k['tgl_bayar'] : '');
            $sheet2->setCellValue("D{$row}", isset($k['fo']) ? $k['fo'] : '');
            $sheet2->setCellValue("E{$row}", isset($k['id_bayar']) ? $k['id_bayar'] : '');
            $sheet2->setCellValue("F{$row}", ''); // jika butuh nama akun, isi via helper di sisi view
            $sheet2->setCellValue("G{$row}", isset($k['keterangan']) ? $k['keterangan'] : '');
            $sheet2->setCellValue("H{$row}", isset($k['jml_bayar']) ? $k['jml_bayar'] : 0);
            $totalKeluar += (float)($k['jml_bayar'] ?? 0);
            $row++;
        }
        $sheet2->setCellValue("G{$row}", 'Total Pengeluaran');
        $sheet2->setCellValue("H{$row}", $totalKeluar);

        // Sheet 3: Pembelian
        $sheet3 = $spreadsheet->createSheet();
        $sheet3->setTitle('Pembelian');
        $sheet3->fromArray(['NO','NO_ORDER','TGL_BAYAR','KASIR','ID BAYAR','AKUN (opsional)','KETERANGAN','KELUAR'], NULL, 'A1');

        $row = 2; $no = 1; $totalBeli = 0;
        foreach ($beli as $b) {
            $sheet3->setCellValue("A{$row}", $no++);
            $sheet3->setCellValue("B{$row}", isset($b['id']) ? $b['id'] : '');
            $sheet3->setCellValue("C{$row}", isset($b['tgl_bayar']) ? $b['tgl_bayar'] : '');
            $sheet3->setCellValue("D{$row}", isset($b['fo']) ? $b['fo'] : '');
            $sheet3->setCellValue("E{$row}", isset($b['id_bayar']) ? $b['id_bayar'] : '');
            $sheet3->setCellValue("F{$row}", '');
            $sheet3->setCellValue("G{$row}", isset($b['keterangan']) ? $b['keterangan'] : '');
            $sheet3->setCellValue("H{$row}", isset($b['jml_bayar']) ? $b['jml_bayar'] : 0);
            $totalBeli += (float)($b['jml_bayar'] ?? 0);
            $row++;
        }
        $sheet3->setCellValue("G{$row}", 'Total Pembelian');
        $sheet3->setCellValue("H{$row}", $totalBeli);

        // Output
        $filename = 'LAPORAN_TRANSAKSI_' . date('Y_m_d_H_i_s') . '.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');
        exit;
    }
}
