<?php

namespace App\Controllers;

class Apel extends BaseController
{
    protected $db;

    public function __construct() {
        $this->db = \Config\Database::connect();
        date_default_timezone_set('Asia/Jakarta');
    }

    public function index() {
        $level = session()->get('level');
        $builder = $this->db->table('apel');
        
        $perPage = 20;
        $currentPage = (int)($this->request->getVar('page_apel') ?? 1);
        $totalCount = $builder->countAllResults(false);

        $list_apel = $builder->orderBy('tanggal', 'DESC')
            ->limit($perPage, ($currentPage - 1) * $perPage)
            ->get()->getResultArray();

        $pager = service('pager');
        $pager_links = $pager->makeLinks($currentPage, $perPage, $totalCount, 'bootstrap_pagination', 0, 'apel');

        return view('admin/apel_index', [
            'list_apel' => $list_apel,
            'pager'     => $pager_links,
            'level'     => $level,
            'title'     => 'Manajemen Jadwal Apel'
        ]);
    }

    public function store() {
        if (!in_array(session()->get('level'), ['Superadmin', 'kabupaten'])) return redirect()->back();
        
        $this->db->table('apel')->insert([
            'nama_apel'  => $this->request->getPost('nama_apel'),
            'tanggal'    => $this->request->getPost('tanggal'),
            'jam_mulai'  => $this->request->getPost('jam_mulai'),
            'jam_akhir'  => $this->request->getPost('jam_akhir'),
            'latitude'   => $this->request->getPost('latitude'),
            'longitude'  => $this->request->getPost('longitude'),
            'radius'     => $this->request->getPost('radius'),
            'created_at' => date('Y-m-d H:i:s')
        ]);
        return redirect()->to(base_url('apel'))->with('success', 'Jadwal Apel Berhasil Diterbitkan!');
    }

    public function update($id) {
        if (!in_array(session()->get('level'), ['Superadmin', 'kabupaten'])) return redirect()->back();

        $this->db->table('apel')->where('id_apel', $id)->update([
            'nama_apel'  => $this->request->getPost('nama_apel'),
            'tanggal'    => $this->request->getPost('tanggal'),
            'jam_mulai'  => $this->request->getPost('jam_mulai'),
            'jam_akhir'  => $this->request->getPost('jam_akhir'),
            'latitude'   => $this->request->getPost('latitude'),
            'longitude'  => $this->request->getPost('longitude'),
            'radius'     => $this->request->getPost('radius')
        ]);
        return redirect()->to(base_url('apel'))->with('success', 'Jadwal Apel Berhasil Diperbarui!');
    }

    public function delete($id) {
        if (!in_array(session()->get('level'), ['Superadmin', 'kabupaten'])) return redirect()->back();

        $this->db->transStart();
        // Hapus utusan dulu agar tidak ada data sampah
        $this->db->table('apel_peserta')->where('id_apel', $id)->delete();
        // Hapus jadwal apel
        $this->db->table('apel')->where('id_apel', $id)->delete();
        $this->db->transComplete();

        return redirect()->to(base_url('apel'))->with('success', 'Jadwal Apel Berhasil Dihapus!');
    }

    public function kelola($id_apel) {
        $level = session()->get('level');
        $id_opd_admin = session()->get('id_opd');
        $apel = $this->db->table('apel')->where('id_apel', $id_apel)->get()->getRowArray();
        $builder_p = $this->db->table('pegawai');
        if (!in_array($level, ['Superadmin', 'kabupaten'])) $builder_p->where('id_opd', $id_opd_admin);
        $pegawai = $builder_p->orderBy('nama_lengkap', 'ASC')->get()->getResultArray();
        $utusan = $this->db->table('apel_peserta')->where('id_apel', $id_apel);
        if (!in_array($level, ['Superadmin', 'kabupaten'])) $utusan->where('id_opd', $id_opd_admin);
        $utusan_ids = array_column($utusan->get()->getResultArray(), 'id_pegawai');

        return view('admin/apel_kelola_peserta', [
            'apel'       => $apel,
            'pegawai'    => $pegawai,
            'utusan_ids' => $utusan_ids,
            'title'      => 'Kelola Utusan Apel'
        ]);
    }

    public function simpan_utusan() {
        $id_apel = $this->request->getPost('id_apel');
        $id_opd = session()->get('id_opd');
        $id_pegawai_pilihan = $this->request->getPost('id_pegawai');
        $this->db->transStart();
        $this->db->table('apel_peserta')->where(['id_apel' => $id_apel, 'id_opd' => $id_opd])->delete();
        if (!empty($id_pegawai_pilihan)) {
            $pegawai_data = $this->db->table('pegawai')->select('id_pegawai, nip')->whereIn('id_pegawai', $id_pegawai_pilihan)->get()->getResultArray();
            $map_nip = array_column($pegawai_data, 'nip', 'id_pegawai');
            foreach ($id_pegawai_pilihan as $idp) {
                $this->db->table('apel_peserta')->insert([
                    'id_apel'    => $id_apel,
                    'id_pegawai' => $idp,
                    'nip'        => $map_nip[$idp] ?? '',
                    'id_opd'     => $id_opd,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }
        }
        $this->db->transComplete();
        return redirect()->to(base_url('apel'))->with('success', 'Utusan Diperbarui!');
    }
}