<?php

namespace App\Controllers;

class Approval extends BaseController
{
    protected $db;

    public function __construct()
    {
        $this->db = \Config\Database::connect();
    }

    public function index()
{
    $level = session()->get('level');
    $id_opd_admin = session()->get('id_opd');
    $filter_opd = $this->request->getGet('id_opd');
    $search = $this->request->getGet('keyword');

    $builder = $this->db->table('presensi')
        ->select('presensi.*, pegawai.nama_lengkap, pegawai.nip as nip_pegawai, opd.nama_opd')
        ->join('pegawai', 'presensi.nip = pegawai.nip', 'left')
        ->join('opd', 'pegawai.id_opd = opd.id_opd', 'left');

    // 1. SYARAT WAJIB: Ada file bukti
    $builder->where('presensi.file_bukti !=', null)
        ->where('presensi.file_bukti !=', '');

    // 2. KUNCI ANTREAN: Belum diproses (statusijin kosong)
    $builder->groupStart()
        ->where('presensi.statusijin', null)
        ->orWhere('presensi.statusijin', '')
        ->groupEnd();

    // 3. FILTER HAK AKSES & OPD
    if (in_array($level, ['Superadmin', 'kabupaten'])) {
        if ($filter_opd) {
            $builder->where('pegawai.id_opd', $filter_opd);
        }
    } else {
        $builder->where('pegawai.id_opd', $id_opd_admin);
    }

    // 4. FILTER PENCARIAN
    if ($search) {
        $builder->groupStart()
            ->like('pegawai.nama_lengkap', $search)
            ->orLike('pegawai.nip', $search)
            ->groupEnd();
    }

    // 5. PAGINASI - Tingkatkan ke 50 atau 100 agar Bapak tidak capek klik per halaman
    $perPage = 50; 
    $currentPage = (int)($this->request->getVar('page_presensi') ?? 1);

    // Ambil total data untuk pager sebelum di-limit
    $totalCount = $builder->countAllResults(false);

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

    $pager = service('pager');
    
    /** * FIX TYPE ERROR: 
     * Argumen ke-5 adalah 'segment' (int). Isikan 0 untuk query string.
     * Argumen ke-6 adalah 'group'. Jika diisi 'presensi', maka pager mencari variabel 'page_presensi'.
     */
    $pager_links = $pager->makeLinks($currentPage, $perPage, $totalCount, 'bootstrap_pagination', 0, 'presensi');

    $data = [
        'pengajuan'    => $pengajuan,
        'list_opd'     => $this->db->table('opd')->orderBy('nama_opd', 'ASC')->get()->getResultArray(),
        'pager'        => $pager_links,
        'level'        => $level,
        'keyword'      => $search,
        'selected_opd' => $filter_opd,
        'title'        => 'Antrean Approval Izin & Sakit'
    ];

    return view('admin/approval_izin', $data);
}

    public function proses()
    {
        $id_presensi = $this->request->getPost('id_presensi');
        $aksi        = $this->request->getPost('aksi');
        $kategori    = $this->request->getPost('kategori');
        $catatan     = $this->request->getPost('catatan');

        $update = [
            'statusijin'    => ($aksi == 'setuju') ? $kategori : 'Ditolak',
            'status_masuk'  => ($aksi == 'setuju') ? $kategori : 'Alpa',
            'status_pulang' => ($aksi == 'setuju') ? $kategori : 'Alpa',
            'deskripsi'     => ($aksi == 'setuju')
                ? $kategori . ": " . $catatan . " (Disetujui Admin)"
                : "Ditolak: " . $catatan
        ];

        $this->db->table('presensi')->where('id_presensi', $id_presensi)->update($update);
        return redirect()->to(base_url('approval'))->with('success', 'Data berhasil diproses.');
    }

    public function riwayat()
{
    $level = session()->get('level');
    $id_opd_admin = session()->get('id_opd');
    $filter_opd = $this->request->getGet('id_opd');
    $search = $this->request->getGet('keyword');

    $builder = $this->db->table('presensi')
        ->select('presensi.*, pegawai.nama_lengkap, pegawai.nip as nip_pegawai, opd.nama_opd')
        ->join('pegawai', 'presensi.nip = pegawai.nip', 'left')
        ->join('opd', 'pegawai.id_opd = opd.id_opd', 'left');

    // 1. FILTER RIWAYAT: Hanya ambil yang SUDAH diproses (statusijin tidak kosong)
    $builder->where('presensi.statusijin IS NOT NULL')
            ->where('presensi.statusijin !=', '');

    // 2. FILTER HAK AKSES & OPD
    if (in_array($level, ['Superadmin', 'kabupaten'])) {
        if ($filter_opd) {
            $builder->where('pegawai.id_opd', $filter_opd);
        }
    } else {
        $builder->where('pegawai.id_opd', $id_opd_admin);
    }

    // 3. FILTER PENCARIAN
    if ($search) {
        $builder->groupStart()
                ->like('pegawai.nama_lengkap', $search)
                ->orLike('pegawai.nip', $search)
            ->groupEnd();
    }

    // 4. SETTING PAGINASI (Samakan dengan Index agar efisien)
    $perPage = 50; 
    $currentPage = (int)($this->request->getVar('page_riwayat') ?? 1);

    // Ambil total data sebelum di-limit untuk keperluan Pager
    $totalCount = $builder->countAllResults(false); 

    // Urutkan berdasarkan updated_at (Waktu saat Admin memproses) agar yang baru diapprove muncul paling atas
    $riwayat = $builder->orderBy('presensi.updated_at', 'DESC') 
                       ->limit($perPage, ($currentPage - 1) * $perPage)
                       ->get()->getResultArray();

    // 5. GENERATE PAGER LINKS
    $pager = service('pager');
    $pager_links = $pager->makeLinks($currentPage, $perPage, $totalCount, 'bootstrap_pagination', 0, 'riwayat');

    $data = [
        'riwayat'      => $riwayat,
        'list_opd'     => $this->db->table('opd')->orderBy('nama_opd', 'ASC')->get()->getResultArray(),
        'keyword'      => $search,
        'selected_opd' => $filter_opd,
        'pager'        => $pager_links, // Link navigasi halaman
        'level'        => $level,
        'title'        => 'Riwayat Approval Selesai'
    ];

    // Pastikan nama file view sesuai dengan yang Bapak buat (admin/riwayat_approval atau admin/approval_riwayat)
    return view('admin/approval_riwayat', $data);
}
    public function proses_massal()
    {
        $ids = json_decode($this->request->getPost('ids'));
        $aksi = $this->request->getPost('aksi');

        if (empty($ids)) {
            return redirect()->back()->with('error', 'Tidak ada data yang dipilih.');
        }

        foreach ($ids as $id) {
            // Ambil kategori asli tiap data agar status_masuk-nya benar
            $presensi = $this->db->table('presensi')->where('id_presensi', $id)->get()->getRow();

            if ($presensi) {
                $update = [
                    'statusijin'    => ($aksi == 'setuju') ? $presensi->kategori : 'Ditolak',
                    'status_masuk'  => ($aksi == 'setuju') ? $presensi->kategori : 'Alpa',
                    'status_pulang' => ($aksi == 'setuju') ? $presensi->kategori : 'Alpa',
                    'deskripsi'     => ($aksi == 'setuju')
                        ? $presensi->kategori . " (Disetujui Massal oleh Admin)"
                        : "Ditolak Massal oleh Admin",
                    'updated_at'    => date('Y-m-d H:i:s')
                ];

                $this->db->table('presensi')->where('id_presensi', $id)->update($update);
            }
        }

        return redirect()->to(base_url('approval'))->with('success', count($ids) . ' data berhasil diproses sekaligus.');
    }
}
