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

class Admin extends CI_Controller {

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

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

        // 🎯 Role check — hanya admin & inspector
        $role = $this->session->userdata('role');
        if (!in_array($role, ['admin', 'inspector'])) {
            $this->session->set_flashdata('error', 'Akses ditolak!');
            redirect('auth');
        }

        // 📦 Load model
        $this->load->model('Form_model', 'form');
        $this->load->model('User_model', 'user');

        // 🔐 Flag: hanya admin yang boleh menulis
        $this->can_write = ($role === 'admin');
    }

    // 🔒 Helper guard untuk aksi yang hanya boleh dilakukan admin
    private function require_admin()
    {
        if ($this->session->userdata('role') !== 'admin') {
            show_error('Aksi ini hanya boleh dilakukan oleh admin.', 403);
        }
    }

    // ============================
    // 📊 DASHBOARD
    // ============================
    public function index()
    {
        // Total petugas (user biasa)
        $total_user = $this->db->where('role', 'user')->count_all_results('users');

        // Total form keseluruhan
        $total_form = $this->db->count_all_results('form_gesek');

        // Total input hari ini
        $today = date('Y-m-d');
        $this->db->where('DATE(created_at)', $today);
        $total_hari_ini = $this->db->count_all_results('form_gesek');

        // Total input bulan ini
        $bulan = date('m');
        $tahun = date('Y');
        $this->db->where('MONTH(created_at)', $bulan);
        $this->db->where('YEAR(created_at)', $tahun);
        $total_bulan_ini = $this->db->count_all_results('form_gesek');

        // Ambil 10 data terbaru
        $latest_forms = $this->form->getLatest(10);

        // Statistik per bulan
        $statistik = $this->db->query("
            SELECT MONTH(created_at) AS bulan, COUNT(*) AS total
            FROM form_gesek
            WHERE YEAR(created_at) = YEAR(CURDATE())
            GROUP BY MONTH(created_at)
        ")->result_array();

        $bulan_labels = [];
        $bulan_values = [];
        foreach ($statistik as $s) {
            $bulan_labels[] = date('M', mktime(0, 0, 0, $s['bulan'], 10));
            $bulan_values[] = $s['total'];
        }

         $data = [
        'title' => 'Dashboard Admin - NOKA NOSIN',
        'content' => 'admin/dashboard',
        'total_user' => $total_user,
        'total_form' => $total_form,
        'total_hari_ini' => $total_hari_ini,
        'total_bulan_ini' => $total_bulan_ini,
        'latest_forms' => $latest_forms,
        'bulan_labels' => json_encode($bulan_labels),
        'bulan_values' => json_encode($bulan_values),
        'can_write' => $this->can_write,
        'is_inspector' => ($this->session->userdata('role') === 'inspector')
    ];

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

    // ============================
    // 🧾 DATA GESEK (LIST)
    // ============================
    public function data_gesek()
    {
        $keyword = $this->input->get('keyword');
        $forms = $keyword ? $this->form->search($keyword) : $this->form->getAll();

         $data = [
        'title' => 'Manajemen Data Gesek - NOKA NOSIN',
        'content' => 'admin/data_gesek',
        'forms' => $forms,
        'keyword' => $keyword,
        'can_write' => $this->can_write,
        'is_inspector' => ($this->session->userdata('role') === 'inspector')
    ];

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

    // ============================
    // ✏️ EDIT FORM
    // ============================
    public function edit_form($id)
    {
        $this->require_admin(); // 🔐 hanya admin boleh edit

        $form = $this->form->getById($id);
        if (!$form) show_404();

        $data = [
            'title' => 'Edit Data Gesek - NOKA NOSIN',
            'content' => 'admin/form_edit',
            'form' => $form,
            'can_write' => $this->can_write
        ];

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

    public function update_form()
    {
        $this->require_admin(); // 🔐 hanya admin boleh update

        $id = $this->input->post('id');
        $form = $this->form->getById($id);
        if (!$form) show_404();

        // ====== Ambil data dasar ======
        $data = [
            'no_pol'           => strtoupper($this->input->post('no_pol')),
            'tipe_kendaraan'   => strtoupper($this->input->post('tipe_kendaraan')),
            'nama_pemilik'     => strtoupper($this->input->post('nama_pemilik')),
            'pool'             => strtoupper($this->input->post('pool')),
            'tgl_inpool'       => $this->input->post('tgl_inpool'),
            'tgl_gesek'        => $this->input->post('tgl_gesek'),
            'noka'             => strtoupper($this->input->post('noka')),
            'nosin'            => strtoupper($this->input->post('nosin')),
            'keterangan'       => strtoupper($this->input->post('keterangan')),
        ];

        // ====== Checkbox multi value ======
        $check = $this->input->post('keterangan_check');
        $data['keterangan_check'] = !empty($check) ? implode(', ', $check) : NULL;

        // ====== Upload handling ======
        $upload_path = './assets/uploads/';
        if (!is_dir($upload_path)) mkdir($upload_path, 0777, true);
        $this->load->library('upload');

        $files = [
            'foto_noka_nosin' => $_FILES['foto_noka_nosin'] ?? null,
            'foto_noka'       => $_FILES['foto_noka'] ?? null,
            'foto_nosin'      => $_FILES['foto_nosin'] ?? null
        ];

        foreach ($files as $key => $file) {
            if (!empty($file['name'])) {
                $_FILES['current_file'] = $file;

                $config = [
                    'upload_path'   => $upload_path,
                    'allowed_types' => 'jpg|jpeg|png',
                    'file_name'     => $key . '_' . time(),
                    'overwrite'     => true,
                ];
                $this->upload->initialize($config);

                if ($this->upload->do_upload('current_file')) {
                    // hapus file lama
                    if (!empty($form[$key]) && file_exists($upload_path . $form[$key])) {
                        unlink($upload_path . $form[$key]);
                    }
                    $data[$key] = $this->upload->data('file_name');
                } else {
                    $data[$key] = $form[$key];
                }
            } else {
                $data[$key] = $form[$key];
            }
        }

        $update = $this->form->update($id, $data);
        $this->session->set_flashdata(
            $update ? 'success' : 'error',
            $update ? 'Data & foto berhasil diperbarui.' : 'Gagal memperbarui data.'
        );

        redirect('admin/data_gesek');
    }

    // ============================
    // 👁 VIEW DETAIL
    // ============================
    public function form_detail($id)
    {
        $form = $this->form->getById($id);
        if (!$form) show_404();

        $data = [
        'title' => 'Detail Form Gesek - NOKA NOSIN',
        'content' => 'admin/form_detail',
        'form' => $form,
        'can_write' => $this->can_write,
        'is_inspector' => ($this->session->userdata('role') === 'inspector')
    ];
        $this->load->view('template', $data);
    }

    // ============================
    // 🗑 HAPUS DATA
    // ============================
    public function delete_form($id)
    {
        $this->require_admin(); // 🔐 hanya admin boleh hapus

        $form = $this->form->getById($id);
        if (!$form) show_404();

        $upload_path = './assets/uploads/';
        foreach (['foto_noka_nosin','foto_noka','foto_nosin'] as $fkey) {
            if (!empty($form[$fkey]) && file_exists($upload_path.$form[$fkey])) {
                @unlink($upload_path.$form[$fkey]);
            }
        }

        $this->form->delete($id)
            ? $this->session->set_flashdata('success', 'Data berhasil dihapus.')
            : $this->session->set_flashdata('error', 'Gagal menghapus data.');

        redirect('admin/data_gesek');
    }

    // ============================
    // 📥 DOWNLOAD PDF
    // ============================
    public function download_pdf($id)
    {
        $form = $this->form->getById($id);
        if (!$form) show_404();

        $data['form'] = $form;
        $this->load->library('pdf');
        $this->pdf->load_view('form/pdf_view', $data);

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

        $this->pdf->stream($filename, ['Attachment' => 1]);
    }

    // ============================
    // 👤 MANAJEMEN USER
    // ============================
    public function users()
{
    // admin & inspector bisa lihat list user
     $data = [
        'title' => 'Manajemen User',
        'content' => 'admin/users',
        'users' => $this->user->getAll(),
        'can_write' => $this->can_write,
        'is_inspector' => ($this->session->userdata('role') === 'inspector')
    ];

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

    // ============================
// ➕ TAMBAH USER
// ============================
public function user_add()
{
    if ($this->session->userdata('role') !== 'admin') {
        show_error('Akses ditolak.', 403);
    }

    // kalau form dikirim
    if ($this->input->method() === 'post') {
        $name     = trim($this->input->post('name', TRUE));
        $email    = trim($this->input->post('email', TRUE));
        $password = trim($this->input->post('password', TRUE));
        $role     = trim($this->input->post('role', TRUE));
        $status   = (int)$this->input->post('status', TRUE);

        // validasi wajib isi
        if (empty($name) || empty($email) || empty($password) || empty($role)) {
            $this->session->set_flashdata('error', 'Semua field wajib diisi!');
            redirect('admin/user_add');
            return;
        }

        // cek duplikasi email
        $exist = $this->db->get_where('users', ['email' => $email])->row_array();
        if ($exist) {
            $this->session->set_flashdata('error', 'Email sudah terdaftar.');
            redirect('admin/user_add');
            return;
        }

        // simpan
        $data = [
            'name'       => strtoupper($name),
            'email'      => strtolower($email),
            'password'   => $password,  // ⛔ plain text
            'role'       => $role,
            'status'     => $status,
            'created_at' => date('Y-m-d H:i:s')
        ];

        $this->user->insert($data);
        $this->session->set_flashdata('success', 'User baru berhasil ditambahkan.');
        redirect('admin/users');
    }

    // tampilan form
    $data = [
        'title'   => 'Tambah User Baru - NOKA NOSIN',
        'content' => 'admin/user_add'
    ];
    $this->load->view('template', $data);
}



// ============================
// ✏️ EDIT USER
// ============================
public function user_edit($id)
{
    if ($this->session->userdata('role') !== 'admin') {
        show_error('Akses ditolak.', 403);
    }

    $user = $this->user->getById($id);
    if (!$user) {
        $this->session->set_flashdata('error', 'User tidak ditemukan.');
        redirect('admin/users');
        return;
    }

    $data = [
        'title'   => 'Edit Data User - NOKA NOSIN',
        'content' => 'admin/user_edit',
        'user'    => $user
    ];
    $this->load->view('template', $data);
}



// ============================
// 💾 UPDATE USER
// ============================
public function user_update($id)
{
    if ($this->session->userdata('role') !== 'admin') {
        show_error('Akses ditolak.', 403);
    }

    $name     = trim($this->input->post('name', TRUE));
    $email    = trim($this->input->post('email', TRUE));
    $role     = trim($this->input->post('role', TRUE));
    $status   = (int)$this->input->post('status', TRUE);
    $password = trim($this->input->post('password', TRUE));

    if (empty($name) || empty($email) || empty($role)) {
        $this->session->set_flashdata('error', 'Nama, email, dan role wajib diisi!');
        redirect('admin/user_edit/' . $id);
        return;
    }

    $update = [
        'name'   => strtoupper($name),
        'email'  => strtolower($email),
        'role'   => $role,
        'status' => $status
    ];

    // update password kalau diisi
    if (!empty($password)) {
        $update['password'] = $password; // ⛔ plain text
    }

    $this->user->update($id, $update);
    $this->session->set_flashdata('success', 'Data user berhasil diperbarui.');
    redirect('admin/users');
}

    public function user_delete($id)
    {
        $this->require_admin(); // hanya admin
        $this->user->delete($id);
        redirect('admin/users');
    }
}
