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

class Kegiatan extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->library('session');
        if(!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
        $this->load->model('Kegiatan_model');
        $this->load->library('form_validation');
        $this->load->helper(array('form', 'url'));
    }

    private function _check_admin_access() {
        $role = $this->session->userdata('role');
        if($role != 'admin' && $role != 'rt') {
            $this->session->set_flashdata('error', 'Anda tidak memiliki akses untuk melakukan tindakan ini');
            redirect('kegiatan');
        }
    }

    // ─── INDEX ──────────────────────────────────────────────
    public function index() {
        $data['title']    = 'Kegiatan';
        $role             = $this->session->userdata('role');
        $data['is_admin'] = ($role == 'admin' || $role == 'rt');

        $kategori = $this->input->get('kategori');
        $bulan    = $this->input->get('bulan');
        $tahun    = $this->input->get('tahun');
        $cari     = $this->input->get('cari');

        if($data['is_admin']) {
            $data['kegiatan'] = $this->Kegiatan_model->get_all($kategori, $bulan, $tahun, $cari);
        } else {
            $data['kegiatan'] = $this->Kegiatan_model->get_published($kategori, $bulan, $tahun, $cari);
        }

        $data['kategori_filter'] = $kategori;
        $data['bulan_filter']    = $bulan;
        $data['tahun_filter']    = $tahun;
        $data['cari']            = $cari;
        $data['tahun_list']      = $this->Kegiatan_model->get_available_years();

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('kegiatan/index', $data);
        $this->load->view('templates/footer');
    }

    // ─── DETAIL ─────────────────────────────────────────────
    public function detail($id) {
        $data['title']    = 'Detail Kegiatan';
        $data['kegiatan'] = $this->Kegiatan_model->get_by_id($id);

        if(!$data['kegiatan']) { show_404(); }

        $role = $this->session->userdata('role');
        if($role == 'warga' && $data['kegiatan']->status != 'publish') {
            $this->session->set_flashdata('error', 'Kegiatan tidak tersedia');
            redirect('kegiatan');
        }

        $data['is_admin'] = ($role == 'admin' || $role == 'rt');
        $data['galeri']   = $this->Kegiatan_model->get_galeri($id);

        $this->load->view('templates/header', $data);
        $this->load->view('templates/sidebar', $data);
        $this->load->view('kegiatan/detail', $data);
        $this->load->view('templates/footer');
    }

    // ─── TAMBAH ─────────────────────────────────────────────
    public function tambah() {
        $this->_check_admin_access();
        $data['title'] = 'Tambah Kegiatan';

        $this->form_validation->set_rules('judul',          'Judul',          'required|max_length[200]');
        $this->form_validation->set_rules('isi',            'Isi / Artikel',  'required');
        $this->form_validation->set_rules('kategori',       'Kategori',       'required');
        $this->form_validation->set_rules('tanggal_mulai',  'Tanggal Mulai',  'required');

        if($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('kegiatan/tambah', $data);
            $this->load->view('templates/footer');
        } else {
            // Upload thumbnail
            $thumbnail = $this->_upload_thumbnail();
            if($thumbnail === false) {
                redirect('kegiatan/tambah');
                return;
            }

            $data_kegiatan = array(
                'judul'          => $this->input->post('judul'),
                'slug'           => $this->_make_slug($this->input->post('judul')),
                'isi'            => $this->input->post('isi'),
                'kategori'       => $this->input->post('kategori'),
                'lokasi'         => $this->input->post('lokasi'),
                'tanggal_mulai'  => $this->input->post('tanggal_mulai'),
                'tanggal_selesai'=> $this->input->post('tanggal_selesai') ?: null,
                'thumbnail'      => $thumbnail,
                'status'         => $this->input->post('status'),
                'dibuat_oleh'    => $this->session->userdata('user_id'),
                'created_at'     => date('Y-m-d H:i:s'),
            );

            $kegiatan_id = $this->Kegiatan_model->insert($data_kegiatan);

            // Upload galeri
            $this->_upload_galeri($kegiatan_id);

            $this->session->set_flashdata('success', 'Kegiatan berhasil ditambahkan');
            redirect('kegiatan');
        }
    }

    // ─── EDIT ───────────────────────────────────────────────
    public function edit($id) {
        $this->_check_admin_access();
        $data['title']    = 'Edit Kegiatan';
        $data['kegiatan'] = $this->Kegiatan_model->get_by_id($id);
        $data['galeri']   = $this->Kegiatan_model->get_galeri($id);

        if(!$data['kegiatan']) { show_404(); }

        $this->form_validation->set_rules('judul',    'Judul',    'required|max_length[200]');
        $this->form_validation->set_rules('isi',      'Isi',      'required');
        $this->form_validation->set_rules('kategori', 'Kategori', 'required');

        if($this->form_validation->run() == FALSE) {
            $this->load->view('templates/header', $data);
            $this->load->view('templates/sidebar', $data);
            $this->load->view('kegiatan/edit', $data);
            $this->load->view('templates/footer');
        } else {
            $data_kegiatan = array(
                'judul'          => $this->input->post('judul'),
                'isi'            => $this->input->post('isi'),
                'kategori'       => $this->input->post('kategori'),
                'lokasi'         => $this->input->post('lokasi'),
                'tanggal_mulai'  => $this->input->post('tanggal_mulai'),
                'tanggal_selesai'=> $this->input->post('tanggal_selesai') ?: null,
                'status'         => $this->input->post('status'),
                'updated_at'     => date('Y-m-d H:i:s'),
            );

            // Thumbnail baru
            $thumbnail = $this->_upload_thumbnail();
            if($thumbnail === false) {
                redirect('kegiatan/edit/'.$id);
                return;
            }
            if($thumbnail) {
                // Hapus thumbnail lama
                if($data['kegiatan']->thumbnail) {
                    @unlink('./uploads/kegiatan/'.$data['kegiatan']->thumbnail);
                }
                $data_kegiatan['thumbnail'] = $thumbnail;
            }

            $this->Kegiatan_model->update($id, $data_kegiatan);

            // Upload galeri baru jika ada
            $this->_upload_galeri($id);

            $this->session->set_flashdata('success', 'Kegiatan berhasil diupdate');
            redirect('kegiatan/detail/'.$id);
        }
    }

    // ─── HAPUS ──────────────────────────────────────────────
    public function hapus($id) {
        $this->_check_admin_access();
        $kegiatan = $this->Kegiatan_model->get_by_id($id);

        if($kegiatan) {
            // Hapus thumbnail
            if($kegiatan->thumbnail) {
                @unlink('./uploads/kegiatan/'.$kegiatan->thumbnail);
            }
            // Hapus semua foto galeri
            $galeri = $this->Kegiatan_model->get_galeri($id);
            foreach($galeri as $foto) {
                @unlink('./uploads/kegiatan/galeri/'.$foto->nama_file);
            }
            $this->Kegiatan_model->delete_galeri_by_kegiatan($id);
            $this->Kegiatan_model->delete($id);
        }

        $this->session->set_flashdata('success', 'Kegiatan berhasil dihapus');
        redirect('kegiatan');
    }

    // ─── HAPUS FOTO GALERI (AJAX/redirect) ──────────────────
    public function hapus_foto($galeri_id) {
        $this->_check_admin_access();
        $foto = $this->Kegiatan_model->get_galeri_by_id($galeri_id);

        if($foto) {
            @unlink('./uploads/kegiatan/galeri/'.$foto->nama_file);
            $kegiatan_id = $foto->kegiatan_id;
            $this->Kegiatan_model->delete_galeri($galeri_id);
            $this->session->set_flashdata('success', 'Foto berhasil dihapus');
            redirect('kegiatan/edit/'.$kegiatan_id);
        }
        redirect('kegiatan');
    }

    // ─── PRIVATE HELPERS ────────────────────────────────────
    private function _upload_thumbnail() {
        if(empty($_FILES['thumbnail']['name'])) return '';

        $upload_path = './uploads/kegiatan/';
        if(!is_dir($upload_path)) mkdir($upload_path, 0777, true);

        $config = array(
            'upload_path'   => $upload_path,
            'allowed_types' => 'jpg|jpeg|png|webp',
            'max_size'      => 3072,
            'file_name'     => 'thumb_'.time().'_'.uniqid(),
        );

        $this->load->library('upload', $config);
        if($this->upload->do_upload('thumbnail')) {
            return $this->upload->data('file_name');
        }
        $this->session->set_flashdata('error', 'Gagal upload thumbnail: '.$this->upload->display_errors('',''));
        return false;
    }

    private function _upload_galeri($kegiatan_id) {
        if(empty($_FILES['galeri']['name'][0])) return;

        $upload_path = './uploads/kegiatan/galeri/';
        if(!is_dir($upload_path)) mkdir($upload_path, 0777, true);

        $total_files = count($_FILES['galeri']['name']);
        for($i = 0; $i < $total_files; $i++) {
            if(empty($_FILES['galeri']['name'][$i])) continue;

            $_FILES['galeri_single'] = array(
                'name'     => $_FILES['galeri']['name'][$i],
                'type'     => $_FILES['galeri']['type'][$i],
                'tmp_name' => $_FILES['galeri']['tmp_name'][$i],
                'error'    => $_FILES['galeri']['error'][$i],
                'size'     => $_FILES['galeri']['size'][$i],
            );

            $config = array(
                'upload_path'   => $upload_path,
                'allowed_types' => 'jpg|jpeg|png|webp',
                'max_size'      => 5120,
                'file_name'     => 'foto_'.time().'_'.$i.'_'.uniqid(),
            );

            $this->load->library('upload', $config);
            $this->upload->initialize($config);

            if($this->upload->do_upload('galeri_single')) {
                $this->Kegiatan_model->insert_galeri(array(
                    'kegiatan_id' => $kegiatan_id,
                    'nama_file'   => $this->upload->data('file_name'),
                    'keterangan'  => (isset($_POST['keterangan_foto'][$i]) ? $_POST['keterangan_foto'][$i] : ''),
                    'urutan'      => $i + 1,
                    'created_at'  => date('Y-m-d H:i:s'),
                ));
            }
        }
    }

    private function _make_slug($text) {
        $text = strtolower($text);
        $text = preg_replace('/[^a-z0-9\s-]/', '', $text);
        $text = preg_replace('/[\s-]+/', '-', trim($text));
        return $text.'-'.time();
    }
}