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

class Umkm extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('Umkm_model', 'umkm_model');
        $this->load->library(['session', 'form_validation', 'upload']);
        $this->load->helper(['url', 'form', 'file']);
        if (!$this->session->userdata('user_id')) redirect('auth/login');
    }

    private function _is_admin() {
        return $this->session->userdata('role') === 'admin';
    }

    private function _render($view, $data = []) {
        $data['is_admin']            = $this->_is_admin();
        $data['count_polling_aktif'] = $this->db->where('status','aktif')->count_all_results('polling');
        $this->load->view('templates/header', $data);
        $this->load->view($view, $data);
        $this->load->view('templates/footer', $data);
    }

    // ─── INDEX — Direktori UMKM ───────────────────────────────
    // Semua warga terdaftar bisa lihat (publik sesama warga RT)
    public function index() {
        $kat    = $this->input->get('kat');
        $q      = $this->input->get('q');
        $status = $this->_is_admin() ? null : 'aktif'; // Warga hanya lihat yang aktif

        $umkm = $this->umkm_model->get_all($kat, $status, $q);

        $data = [
            'umkm'           => $umkm,
            'total_umkm'     => $this->umkm_model->count_by_status('aktif'),
            'total_aktif'    => $this->umkm_model->count_by_status('aktif'),
            'total_pending'  => $this->umkm_model->count_by_status('pending'),
            'total_kategori' => $this->umkm_model->count_kategori(),
            'title'          => 'Direktori UMKM Warga',
        ];
        $this->_render('umkm/index', $data);
    }

    // ─── FORM DAFTAR (oleh warga sendiri) ─────────────────────
    public function daftar() {
        $this->_render('umkm/form', ['mode' => 'daftar']);
    }

    // ─── SIMPAN DAFTAR (warga) ────────────────────────────────
    public function simpan_daftar() {
        $this->form_validation->set_rules('nama_usaha', 'Nama Usaha', 'required|trim|max_length[150]');
        $this->form_validation->set_rules('kategori',   'Kategori',  'required|in_list[kuliner,fashion,jasa,pertanian,kerajinan,teknologi,kesehatan,pendidikan,lainnya]');
        $this->form_validation->set_rules('deskripsi',  'Deskripsi', 'required|trim|min_length[20]|max_length[500]');

        if (!$this->form_validation->run()) {
            return $this->daftar();
        }

        $foto = $this->_upload_foto();
        $data = $this->_build_data($foto);
        $data['user_id']  = (int)$this->session->userdata('user_id');
        $data['warga_id'] = (int)($this->session->userdata('warga_id') ?: 0) ?: null;
        $data['status']   = 'pending'; // Warga daftar sendiri → pending

        $this->umkm_model->insert($data);
        $this->session->set_flashdata('success', 'Usaha Anda berhasil didaftarkan! Menunggu verifikasi admin RT.');
        redirect('umkm');
    }

    // ─── TAMBAH (admin) ───────────────────────────────────────
    public function tambah() {
        if (!$this->_is_admin()) show_error('Akses ditolak.', 403);
        $this->_render('umkm/form', ['mode' => 'tambah']);
    }

    // ─── SIMPAN (admin) ───────────────────────────────────────
    public function simpan() {
        if (!$this->_is_admin()) show_error('Akses ditolak.', 403);

        $this->form_validation->set_rules('nama_usaha', 'Nama Usaha', 'required|trim|max_length[150]');
        $this->form_validation->set_rules('kategori',   'Kategori',  'required');
        $this->form_validation->set_rules('deskripsi',  'Deskripsi', 'required|trim');

        if (!$this->form_validation->run()) {
            return $this->tambah();
        }

        $foto = $this->_upload_foto();
        $data = $this->_build_data($foto);
        $data['warga_id']      = $this->input->post('warga_id')     ? (int)$this->input->post('warga_id') : null;
        $data['user_id']       = $this->input->post('user_id_owner') ? (int)$this->input->post('user_id_owner') : null;
        $data['status']        = $this->input->post('status') ?: 'aktif';

        $this->umkm_model->insert($data);
        $this->session->set_flashdata('success', 'Data UMKM berhasil ditambahkan.');
        redirect('umkm');
    }

    // ─── EDIT ─────────────────────────────────────────────────
    public function edit($id = null) {
        if (!$id) redirect('umkm');
        $item = $this->umkm_model->get_by_id($id);
        if (!$item) show_404();

        // Cek akses: admin atau pemilik
        $uid = $this->session->userdata('user_id');
        if (!$this->_is_admin() && $item->user_id != $uid) {
            show_error('Akses ditolak. Anda bukan pemilik usaha ini.', 403);
        }

        $this->_render('umkm/form', ['mode' => 'edit', 'item' => $item]);
    }

    // ─── UPDATE ───────────────────────────────────────────────
    public function update($id = null) {
        if (!$id) redirect('umkm');
        $item = $this->umkm_model->get_by_id($id);
        if (!$item) show_404();

        $uid = $this->session->userdata('user_id');
        if (!$this->_is_admin() && $item->user_id != $uid) {
            show_error('Akses ditolak.', 403);
        }

        $this->form_validation->set_rules('nama_usaha', 'Nama Usaha', 'required|trim|max_length[150]');
        $this->form_validation->set_rules('kategori',   'Kategori',  'required');
        $this->form_validation->set_rules('deskripsi',  'Deskripsi', 'required|trim');

        if (!$this->form_validation->run()) {
            return $this->edit($id);
        }

        $foto = $this->_upload_foto();
        $data = $this->_build_data($foto);

        // Pertahankan foto lama jika tidak upload baru
        if (empty($foto) && !empty($item->foto)) {
            unset($data['foto']); // jangan timpa foto lama
        }

        // Admin bisa ubah status, warga tidak
        if ($this->_is_admin()) {
            $data['status'] = $this->input->post('status') ?: $item->status;
        } else {
            // Jika warga edit → kembali ke pending untuk re-verifikasi
            $data['status'] = 'pending';
        }

        $this->umkm_model->update($id, $data);
        $this->session->set_flashdata('success', 'Data UMKM berhasil diperbarui.');
        redirect('umkm');
    }

    // ─── APPROVE (admin) ──────────────────────────────────────
    public function approve($id = null) {
        if (!$this->_is_admin()) show_error('Akses ditolak.', 403);
        if (!$id) redirect('umkm');

        $item = $this->umkm_model->get_by_id($id);
        if (!$item) show_404();

        $this->umkm_model->update($id, ['status' => 'aktif']);
        $this->session->set_flashdata('success', 'UMKM "'.$item->nama_usaha.'" telah disetujui dan ditampilkan di direktori.');
        redirect('umkm');
    }

    // ─── NONAKTIFKAN (admin) ──────────────────────────────────
    public function nonaktifkan($id = null) {
        if (!$this->_is_admin()) show_error('Akses ditolak.', 403);
        if (!$id) redirect('umkm');

        $this->umkm_model->update($id, ['status' => 'nonaktif']);
        $this->session->set_flashdata('success', 'UMKM berhasil dinonaktifkan.');
        redirect('umkm');
    }

    // ─── HAPUS (admin) ────────────────────────────────────────
    public function hapus($id = null) {
        if (!$this->_is_admin()) show_error('Akses ditolak.', 403);
        if (!$id) redirect('umkm');

        $item = $this->umkm_model->get_by_id($id);
        if (!$item) show_404();

        // Hapus foto jika ada
        if (!empty($item->foto)) {
            $foto_path = FCPATH.'assets/uploads/umkm/'.$item->foto;
            if (file_exists($foto_path)) @unlink($foto_path);
        }

        $this->umkm_model->delete($id);
        $this->session->set_flashdata('success', 'UMKM "'.$item->nama_usaha.'" berhasil dihapus.');
        redirect('umkm');
    }

    // ─── AJAX: CARI WARGA (autocomplete) ─────────────────────
    public function cari_warga() {
        if (!$this->_is_admin()) { echo json_encode([]); return; }

        $q = $this->input->get('q', true);
        if (strlen($q) < 2) { echo json_encode([]); return; }

        $results = $this->db
            ->select('w.id, w.nama_lengkap, w.nik, u.id as user_id')
            ->from('warga w')
            ->join('users u', 'u.warga_id = w.id', 'left')
            ->like('w.nama_lengkap', $q)
            ->or_like('w.nik', $q)
            ->limit(10)
            ->get()
            ->result();

        $this->output->set_content_type('application/json');
        echo json_encode($results);
    }

    // ─── HELPER: Upload foto ──────────────────────────────────
    private function _upload_foto() {
        if (empty($_FILES['foto']['name'])) return null;

        $upload_path = FCPATH.'assets/uploads/umkm/';
        if (!is_dir($upload_path)) mkdir($upload_path, 0755, true);

        $this->load->library('upload', [
            'upload_path'   => $upload_path,
            'allowed_types' => 'jpg|jpeg|png|webp',
            'max_size'      => 2048,
            'file_name'     => 'umkm_'.time().'_'.uniqid(),
            'overwrite'     => false,
        ]);

        if ($this->upload->do_upload('foto')) {
            return $this->upload->data('file_name');
        }

        return null;
    }

    // ─── HELPER: Build data array dari POST ──────────────────
    private function _build_data($foto = null) {
        $data = [
            'nama_usaha'      => $this->input->post('nama_usaha', true),
            'kategori'        => $this->input->post('kategori'),
            'deskripsi'       => $this->input->post('deskripsi', true),
            'produk_layanan'  => $this->input->post('produk_layanan', true),
            'alamat'          => $this->input->post('alamat', true),
            'jam_operasional' => $this->input->post('jam_operasional', true),
            'no_telp'         => $this->input->post('no_telp', true),
            'whatsapp'        => $this->input->post('whatsapp', true),
            'instagram'       => ltrim($this->input->post('instagram', true) ?? '', '@'),
        ];
        if ($foto) $data['foto'] = $foto;
        return $data;
    }
}