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

class Laporan extends CI_Controller {

    public function __construct()
    {
        parent::__construct();

        // 🔐 Pastikan user login
        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }

        // Load model, helper, database
        $this->load->model('Form_model', 'form');
        $this->load->helper(['url', 'download']);
        $this->load->database();
    }

    // ========================================================
    // 📊 INDEX / FILTER LAPORAN
    // ========================================================
    public function index()
    {
        // Ambil input GET, pastikan string (bukan null)
        $start = (string) $this->input->get('start_date', TRUE);
        $end   = (string) $this->input->get('end_date', TRUE);

        // Setup variabel untuk dikirim ke view
        $data = [
            'title'       => 'Laporan Form Gesek - NOKA NOSIN',
            'result'      => [],
            'start_date'  => $start,
            'end_date'    => $end,
        ];

        // 🔍 Cek filter GET
        if (!empty($start) && !empty($end)) {
            $start_sql = $this->_normalize_date($start);
            $end_sql   = $this->_normalize_date($end);

            log_message('debug', "=== FILTER LAPORAN (GET) === Start: {$start_sql}, End: {$end_sql}");

            // 🔧 Ambil data via Model
            $data['result'] = $this->form->get_by_date($start_sql, $end_sql);

            log_message('debug', 'Jumlah hasil query dari Form_model: ' . count($data['result']));
        }

        // ✅ Load tampilan
        $data['content'] = 'laporan/index';
        $this->load->view('template', $data);
    }

    // ========================================================
    // 🔧 FUNGSI PRIVATE: Normalisasi Format Tanggal
    // ========================================================
    private function _normalize_date($date)
    {
        if (empty($date)) return null;

        // Format mm/dd/yyyy (browser regional US)
        if (preg_match('#^\d{2}/\d{2}/\d{4}$#', $date)) {
            return date('Y-m-d', strtotime(str_replace('/', '-', $date)));
        }

        // Format yyyy-mm-dd (default input type="date")
        if (preg_match('#^\d{4}-\d{2}-\d{2}$#', $date)) {
            return $date;
        }

        // fallback
        return date('Y-m-d', strtotime($date));
    }

    // ========================================================
    // 📁 EXPORT CSV (format baru untuk Excel)
    // ========================================================
    public function export()
    {
        $start = (string) $this->input->get('start', TRUE);
        $end   = (string) $this->input->get('end', TRUE);

        if (empty($start) || empty($end)) {
            show_error('Tanggal tidak valid untuk export.', 400);
        }

        // Normalisasi jika user kirim format lain
        $start_sql = $this->_normalize_date($start);
        $end_sql   = $this->_normalize_date($end);

        $rows = $this->form->get_by_date($start_sql, $end_sql);

        // ================= Headers CSV =================
        $filename = 'laporan_form_gesek_' . date('Ymd') . '.csv';

        // Bersihkan buffer agar file tidak korup
        if (ob_get_length()) { @ob_end_clean(); }

        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="'.$filename.'"');
        header('Pragma: no-cache');
        header('Expires: 0');

        // Output ke php://output
        $out = fopen('php://output', 'w');

        // BOM UTF-8 supaya Excel Windows membaca UTF-8 dengan benar
        fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));

        // Header kolom (No + 10 field sesuai DB tanpa ID + kolom 11: keterangan)
        $header = [
            'No',
            'No Polisi',
            'Tipe Kendaraan',
            'Nama Pemilik',
            'Pool',
            'Tgl Inpool',
            'Tgl Gesek',
            'NOKA',
            'NOSIN',
            'Keterangan Check',
            'Keterangan'
        ];
        fputcsv($out, $header);

        // Helper format
        $fmtDate = function($d) {
            if (empty($d)) return '';
            $ts = strtotime($d);
            return $ts ? date('d/m/Y', $ts) : '';
        };
        $safe = function($v, $upper = false) {
            $v = (string)($v ?? '');
            // Hilangkan CR/LF di dalam cell biar tidak pecah baris
            $v = str_replace(["\r", "\n"], ' ', $v);
            return $upper ? strtoupper($v) : $v;
        };

        // Tulis baris
        $no = 1;
        foreach ($rows as $r) {
            $line = [
                $no++,
                $safe($r['no_pol'] ?? '', true),
                $safe($r['tipe_kendaraan'] ?? '', true),
                $safe($r['nama_pemilik'] ?? '', true),
                $safe($r['pool'] ?? '', true),
                $fmtDate($r['tgl_inpool'] ?? ''),
                $fmtDate($r['tgl_gesek'] ?? ''),
                $safe($r['noka'] ?? '', true),
                $safe($r['nosin'] ?? '', true),
                $safe($r['keterangan_check'] ?? ''),
                $safe($r['keterangan'] ?? ''),
            ];
            fputcsv($out, $line);
        }

        fclose($out);
        exit;
    }

// ========================================================
// 🖨️ CETAK PDF (Dompdf, stabil: header di THEAD, footer via canvas)
// ========================================================
public function cetak()
{
    $start = (string) $this->input->get('start', TRUE);
    $end   = (string) $this->input->get('end', TRUE);

    if (empty($start) || empty($end)) {
        show_error('Tanggal tidak valid untuk cetak PDF.', 400);
    }

    // --- Normalisasi & jaga urutan tanggal ---
    $start_sql = $this->_normalize_date($start);
    $end_sql   = $this->_normalize_date($end);
    if (!$start_sql || !$end_sql) {
        show_error('Format tanggal tidak valid.', 400);
    }
    if (strtotime($start_sql) > strtotime($end_sql)) {
        [$start_sql, $end_sql] = [$end_sql, $start_sql];
    }

    // --- Ambil data ---
    $data = [
        'result' => $this->form->get_by_date($start_sql, $end_sql),
        'start'  => $start_sql,
        'end'    => $end_sql,
        'title'  => 'Laporan Form Gesek',
    ];

    // --- Render view menjadi HTML string (jangan echo langsung) ---
    $html = $this->load->view('laporan/pdf_view', $data, TRUE);

    // --- Auto-detect Dompdf autoload path ---
    $autoload_candidates = [
        FCPATH . 'vendor/autoload.php',
        APPPATH . 'libraries/dompdf/vendor/autoload.php',
        APPPATH . 'libraries/dompdf/autoload.inc.php',
    ];
    $autoload_loaded = false;
    foreach ($autoload_candidates as $auto) {
        if (is_file($auto)) { require_once $auto; $autoload_loaded = true; break; }
    }

    if (!$autoload_loaded || !class_exists('\\Dompdf\\Dompdf')) {
        // Fallback: tampilkan HTML mentah agar mudah debug di server yang belum ada Dompdf
        if (ob_get_length()) { @ob_end_clean(); }
        header('Content-Type: text/html; charset=UTF-8');
        echo '<pre style="color:#a00">Dompdf tidak ditemukan. Pastikan salah satu autoload berikut ada:</pre><ul>';
        foreach ($autoload_candidates as $a) echo '<li>'.htmlspecialchars($a).'</li>';
        echo '</ul>';
        echo $html;
        return;
    }

    // --- Bersihkan buffer untuk menghindari header korup atau halaman kosong ---
    if (ob_get_length()) { @ob_end_clean(); }
    $html = ltrim($html);

    // --- Opsi Dompdf (aman untuk data banyak) ---
    $options = new \Dompdf\Options();
    $options->set('isHtml5ParserEnabled', true);
    $options->set('isRemoteEnabled', true);
    $options->set('defaultFont', 'DejaVu Sans');
    $options->set('isPhpEnabled', false);
    // Ringankan memory ketika data besar
    @ini_set('memory_limit', '512M');
    @set_time_limit(90);

    $dompdf = new \Dompdf\Dompdf($options);
    // Base path opsional, membantu kalau di view ada relative asset
    $dompdf->setBasePath(FCPATH);

    $dompdf->loadHtml($html, 'UTF-8');
    $dompdf->setPaper('A4', 'landscape'); // sinkron dengan @page di view
    $dompdf->render();

    // --- Footer: tanggal cetak & nomor halaman via canvas (lebih stabil dibanding CSS fixed) ---
    $canvas = $dompdf->getCanvas();
    $w = $canvas->get_width();
    $h = $canvas->get_height();
    $canvas->page_text(28,      $h - 22, "Dicetak: ".date('d/m/Y H:i'), "helvetica", 8, [0,0,0]);
    $canvas->page_text($w-120,  $h - 22, "Hal. {PAGE_NUM} / {PAGE_COUNT}", "helvetica", 8, [0,0,0]);

    // --- Stream inline ke browser ---
    $filename = 'laporan_form_gesek_' . date('Ymd') . '.pdf';
    $dompdf->stream($filename, ['Attachment' => 0]);
}


}
