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

class Form extends CI_Controller {

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

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

        $this->load->model('Form_model', 'form');

        // Simpan role biar gampang
        $this->role = $this->session->userdata('role');
    }

    // 🔒 Helper untuk batasi aksi CRUD
    private function require_not_inspector()
    {
        if ($this->role === 'inspector') {
            show_error('Akses ditolak! Inspector tidak memiliki izin untuk menulis data.', 403);
        }
    }

    // =============================
    // 📋 LIST DATA FORM
    // =============================
    public function index()
    {
        $q = $this->input->get('q');

        if ($q) {
            $this->db->like('no_pol', $q);
            $this->db->or_like('nama_pemilik', $q);
            $this->db->or_like('tipe_kendaraan', $q);
            $this->db->or_like('noka', $q);
            $this->db->or_like('nosin', $q);
        }

        $data['forms'] = $this->db->get('form_gesek')->result_array();
        $data['title'] = 'Data Form Gesek - NOKA NOSIN';
        $data['content'] = 'user/form_list';
        $data['can_write'] = ($this->role !== 'inspector'); // Inspector read-only

        $this->load->view('template', $data);
    }

    // =============================
    // ➕ TAMBAH FORM (form_add)
    // =============================
    public function add()
    {
        $this->require_not_inspector(); // hanya admin & petugas

        $data['title'] = 'Tambah Form Gesek';
        $data['content'] = 'user/form_add';
        $this->load->view('template', $data);
    }

    // =============================
    // 💾 SIMPAN DATA BARU
    // =============================
    public function save()
    {
        $this->require_not_inspector(); // hanya admin & petugas

        $post = $this->input->post(NULL, TRUE);

        // ubah ke huruf besar semua (kecuali field tanggal & checkbox)
        foreach ($post as $key => $val) {
            if (!in_array($key, ['tgl_inpool', 'tgl_gesek', 'keterangan_check'])) {
                $post[$key] = strtoupper($val);
            }
        }

        // Cek duplikasi no_pol
        if ($this->form->existsNoPol($post['no_pol'])) {
            $this->session->set_flashdata('error', 'Nomor polisi sudah terdaftar!');
            redirect('form/add');
            return;
        }

        // Gabung checkbox keterangan
        $keterangan_check = !empty($post['keterangan_check'])
            ? implode(', ', $post['keterangan_check'])
            : NULL;

        // Upload foto (opsional)
        $upload_path = './assets/uploads/';
        if (!is_dir($upload_path)) mkdir($upload_path, 0777, true);

        $this->load->library('upload');
        $files = ['foto_noka_nosin', 'foto_noka', 'foto_nosin'];

        foreach ($files as $file) {
            if (!empty($_FILES[$file]['name'])) {
                $config = [
                    'upload_path'   => $upload_path,
                    'allowed_types' => 'jpg|jpeg|png',
                    'file_name'     => $file.'_'.time()
                ];
                $this->upload->initialize($config);

                if ($this->upload->do_upload($file)) {
                    $post[$file] = $this->upload->data('file_name');
                } else {
                    $post[$file] = NULL;
                }
            }
        }

        $data = [
            'no_pol'           => $post['no_pol'],
            'tipe_kendaraan'   => $post['tipe_kendaraan'],
            'nama_pemilik'     => $post['nama_pemilik'],
            'pool'             => $post['pool'],
            'tgl_inpool'       => $post['tgl_inpool'],
            'tgl_gesek'        => $post['tgl_gesek'],
            'noka'             => $post['noka'],
            'nosin'            => $post['nosin'],
            'keterangan_check' => $keterangan_check,
            'keterangan'       => $post['keterangan'],
            'foto_noka_nosin'  => $post['foto_noka_nosin'] ?? NULL,
            'foto_noka'        => $post['foto_noka'] ?? NULL,
            'foto_nosin'       => $post['foto_nosin'] ?? NULL,
            'petugas'          => strtoupper($this->session->userdata('name'))
        ];

        $this->form->insert($data);
        $this->session->set_flashdata('success', 'Data form gesek berhasil disimpan.');
        redirect('form');
    }

    // =============================
    // 👁 DETAIL DATA
    // =============================
    public function detail($id)
    {
        $form = $this->form->getById($id);
        if (!$form) {
            $this->session->set_flashdata('error', 'Data tidak ditemukan.');
            redirect('form');
        }

        $data = [
            'title'   => 'Detail Form Gesek',
            'form'    => $form,
            'content' => 'user/form_detail'
        ];

        $this->load->view('template', $data);
    }

    // =============================
    // 🖨 PRINT FORM
    // =============================
    public function print($id)
    {
        $form = $this->form->getById($id);
        if (empty($form)) {
            show_404();
        }

        $this->load->library('pdf');
        $filename = 'FormGesek_' . strtoupper($form['no_pol']) . '_' . date('Ymd', strtotime($form['created_at'])) . '.pdf';

        $data['form'] = $form;
        $this->pdf->load_view('form/pdf_view', $data);
        $this->pdf->stream($filename, ['Attachment' => 0]); // tampil di browser
    }
}
