<?php

namespace App\Controllers\Verifikator;

use App\Controllers\BaseController;
use App\Models\PengajuanModel;
use App\Models\DokumenModel;
use App\Libraries\WhatsApp;

class Dashboard extends BaseController
{
    public function index()
    {
        $pengajuanModel = new PengajuanModel();

        $data = [
            'pending_list' => $pengajuanModel->where('status', 'PENDING')->getWithPegawai(),
            'history_list' => $pengajuanModel->where('status !=', 'PENDING')->getWithPegawai(),
        ];

        return view('verifikator/dashboard', $data);
    }

    public function detail($id)
    {
        $pengajuanModel = new PengajuanModel();
        $dokumenModel = new DokumenModel();

        $data = [
            'pengajuan' => $pengajuanModel->select('pengajuan.*, pegawai.nama as pegawai_name, pegawai.nip_baru as pegawai_nip')
                ->join('pegawai', 'pegawai.nip_baru = pengajuan.target_nip', 'left')
                ->where('pengajuan.id', $id)
                ->first(),
            'dokumen' => $dokumenModel->where('pengajuan_id', $id)->findAll(),
        ];

        return view('verifikator/detail', $data);
    }

    public function updateStatus($id)
    {
        $pengajuanModel = new PengajuanModel();
        $dokumenModel = new DokumenModel();

        // Fetch application details, CREATOR (applicant), and TARGET for notification and file naming
        $pengajuan = $pengajuanModel->select('pengajuan.id, pengajuan.target_nip, pengajuan.jenis_kp, creator.nama as creator_name, creator.no_hp as creator_hp, target.nama as target_name')
            ->join('pegawai as creator', 'creator.user_id = pengajuan.created_by', 'left')
            ->join('pegawai as target', 'target.nip_baru = pengajuan.target_nip', 'left')
            ->where('pengajuan.id', $id)
            ->first();

        $status = $this->request->getPost('status');
        $catatan = $this->request->getPost('catatan');

        $updateData = [
            'status' => $status,
            'catatan_revisi' => $catatan,
        ];

        // Handle SK TTE Upload with NIP-based naming
        $skTteFile = $this->request->getFile('sk_tte');
        if ($skTteFile && $skTteFile->isValid() && !$skTteFile->hasMoved()) {
            $nip = $pengajuan['target_nip'] ?? 'NONIP';
            // Format: NIP_SK_TTE_20240321_123045.pdf
            $newName = $nip . '_SK_TTE_' . date('Ymd_His') . '.' . $skTteFile->getExtension();
            $skTteFile->move(FCPATH . 'uploads/sk_tte', $newName);
            $updateData['sk_tte'] = $newName;
        }

        // Update Application Status
        $pengajuanModel->update($id, $updateData);

        // Update Individual Documents Status & Comments
        $docStatuses = $this->request->getPost('doc_status');
        $docCatatans = $this->request->getPost('doc_catatan');

        if (!empty($docStatuses)) {
            foreach ($docStatuses as $docId => $docStatus) {
                $dokumenModel->update($docId, [
                    'status_verifikasi' => $docStatus,
                    'catatan' => $docCatatans[$docId] ?? ''
                ]);
            }
        }

        if ($pengajuan && !empty($pengajuan['creator_hp'])) {
            $wa = new WhatsApp();

            // Map status to Indonesian labels
            $statusLabels = [
                'PENDING' => 'DITINJAU VERIFIKATOR',
                'VERIFIED' => 'Verifikasi OK',
                'REJECTED' => 'Tolak / Tidak Valid',
                'REVISION' => 'Minta Revisi',
                'APPROVED' => 'Approve (Tim Penilai)',
                'PROSES_BKN' => 'Proses BKN',
                'PERTEK_BKN' => 'Pertek BKN',
                'TOLAK_BKN' => 'Tolak BKN',
                'WAITING_SK' => 'Menunggu Penerbitan SK',
                'SK_FINISH' => 'SK Telah selesai di cetak',
            ];
            $statusLabel = $statusLabels[$status] ?? $status;

            $message = "Halo *{$pengajuan['creator_name']}*,\n";
            $message .= "Status usulan Kenaikan Pangkat Anda (Subjek Usulan: *{$pengajuan['target_name']}*) telah diperbarui:\n\n";
            $message .= "📊 Status: *$statusLabel*\n\n";

            if (!empty($catatan)) {
                $message .= "📝 *Catatan Verifikator:*\n";
                $message .= "{$catatan}\n\n";
            }

            if ($status === 'REVISION') {
                $message .= "Silakan login ke SIMKP ASN untuk melakukan perbaikan sesuai catatan di atas.\n\n";
            }

            $message .= "Terima kasih,\n*BKPSDM Support Bot*";

            $wa->sendMessage($pengajuan['creator_hp'], $message);
        }

        return redirect()->to('/verifikator/dashboard')->with('success', 'Status pengajuan berhasil diperbarui.');
    }
}
