<?php

namespace App\Controllers\User;

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

class Pengajuan extends BaseController
{
    public function index()
    {
        $pegawaiModel = new PegawaiModel();
        $data = [
            'title' => 'Ajukan Kenaikan Pangkat',
            'all_pegawai' => $pegawaiModel->findAll(),
        ];
        return view('user/pengajuan', $data);
    }

    public function process()
    {
        // This is now handled by Step 2 in the JS Wizard, 
        // but we keep a fallback or simplified logic if needed.
        return redirect()->to('/user/pengajuan');
    }

    public function submit()
    {
        error_log("SUBMIT HIT - BEGINNING"); // PHP direct log
        log_message('debug', 'SUBMIT METHOD START');

        // CI4 getMethod() returns 'POST' by default. Check case-insensitively.
        if (strtoupper($this->request->getMethod()) !== 'POST') {
            return redirect()->to('/user/pengajuan');
        }

        $session = session();
        $pengajuanModel = new PengajuanModel();
        $dokumenModel = new DokumenModel();

        // Data from Step 1, 2, 3
        $userId = $this->request->getPost('user_id');
        $userId = empty($userId) ? null : $userId;
        $targetNip = $this->request->getPost('target_nip');

        if (empty($targetNip)) {
            return redirect()->back()->withInput()->with('error', 'NIP Pegawai tidak ditemukan. Silakan cari/pilih pegawai kembali pada Langkah 2.');
        }

        $data = [
            'user_id' => $userId,
            'target_nip' => $this->request->getPost('target_nip'),
            'created_by' => session()->get('id'),
            'periode' => $this->request->getPost('periode'),
            'tahun' => $this->request->getPost('tahun'),
            'jenis_prosedur' => $this->request->getPost('jenis_prosedur'),
            'jenis_kp' => $this->request->getPost('jenis_kp'),
            'jenis_jabatan' => $this->request->getPost('jenis_jabatan'),
            'status' => 'PENDING',
            // Detailed fields from Step 3
            'tempat_lahir' => $this->request->getPost('tempat_lahir'),
            'tanggal_lahir' => $this->request->getPost('tanggal_lahir'),
            'pendidikan_lama' => $this->request->getPost('pendidikan_lama'),
            'tahun_lulus' => $this->request->getPost('tahun_lulus'),
            'gelar_depan' => $this->request->getPost('gelar_depan'),
            'gelar_belakang' => $this->request->getPost('gelar_belakang'),
            'unor' => $this->request->getPost('unor'),
            'unit_kerja_induk' => $this->request->getPost('unit_kerja_induk'),
            'jabatan_lama' => $this->request->getPost('jabatan_lama'),
            'jabatan_baru' => $this->request->getPost('jabatan_baru'),
            'lokasi_kerja' => $this->request->getPost('lokasi_kerja'),
            'instansi_kerja' => $this->request->getPost('instansi_kerja'),

            'gol_awal' => $this->request->getPost('gol_awal'),
            'tmt_golongan_lama' => $this->request->getPost('tmt_golongan_lama'),
            'mkt_lama' => $this->request->getPost('mkt_lama'),
            'mkb_lama' => $this->request->getPost('mkb_lama'),

            'mkt_baru' => $this->request->getPost('mkt_baru'),
            'mkb_baru' => $this->request->getPost('mkb_baru'),

            'tmt_jabatan_lama' => $this->request->getPost('tmt_jabatan_lama'),
            'gol_baru' => $this->request->getPost('gol_baru'),
            'tmt_gol_baru' => $this->request->getPost('tmt_gol_baru'),
            'atasan_nama' => $this->request->getPost('atasan_nama'),
            'atasan_nip' => $this->request->getPost('atasan_nip'),
            'atasan_jabatan' => $this->request->getPost('atasan_jabatan'),
            'atasan_gol' => $this->request->getPost('atasan_gol'),

            'angka_kredit_lama' => $this->request->getPost('angka_kredit_lama'),
            'angka_kredit_baru' => $this->request->getPost('angka_kredit_baru'),
            'keterangan_kp' => $this->request->getPost('keterangan_kp'),
        ];

        try {
            $pengajuanId = $pengajuanModel->insert($data);
        } catch (\Exception $e) {
            log_message('error', 'Insert Failed: ' . $e->getMessage());
            $pengajuanId = false;
        }

        if (!$pengajuanId) {
            log_message('error', 'Pengajuan Insert returned false. Data: ' . json_encode($data));
            $errors = $pengajuanModel->errors();
            if ($errors) {
                log_message('error', 'Model Errors: ' . json_encode($errors));
            }
        }


        if ($pengajuanId) {
            // Handle Multiple Files
            $files = $this->request->getFiles();
            log_message('debug', 'Files received: ' . count($files));

            if ($files && isset($files['dokumen'])) {
                foreach ($files['dokumen'] as $key => $file) {
                    if ($file->isValid() && !$file->hasMoved()) {
                        // Max Size 1MB (1,048,576 bytes)
                        if ($file->getSize() > (1024 * 1024)) {
                            $pengajuanModel->delete($pengajuanId); // Rollback insertion
                            return redirect()->back()->withInput()->with('error', "File " . strtoupper(str_replace('_', ' ', $key)) . " Terlalu Besar! Maksimal 1MB.");
                        }

                        $targetNip = $this->request->getPost('target_nip');
                        $docNameClean = str_replace(' ', '_', strtoupper($key));
                        $newName = $targetNip . '_' . $docNameClean . '.' . $file->getExtension();

                        if ($file->move(FCPATH . 'uploads/dokumen', $newName, true)) { // true to overwrite
                            $dokumenModel->insert([
                                'pengajuan_id' => $pengajuanId,
                                'nip' => $targetNip,
                                'nama_dokumen' => strtoupper(str_replace('_', ' ', $key)),
                                'file_path' => $newName,
                                'status_verifikasi' => 'WAITING',
                            ]);
                            log_message('debug', "File {$key} for NIP {$targetNip} uploaded: {$newName}");
                        } else {
                            log_message('error', "Failed to move file {$key}");
                        }
                    } else {
                        if ($file->getError() !== 4) { // 4 = no file uploaded
                            log_message('error', "File {$key} upload error: " . $file->getErrorString() . " (" . $file->getError() . ")");
                        }
                    }
                }
            }

            // Handle Reused Documents (Files not uploaded but existing in library)
            $reusedFiles = $this->request->getPost('reuse');
            $reusedNames = $this->request->getPost('reuse_name');
            if ($reusedFiles && is_array($reusedFiles)) {
                $targetNip = $this->request->getPost('target_nip');
                foreach ($reusedFiles as $slug => $filePath) {
                    // Check if a new file was NOT successfully uploaded for this slug
                    $newFileUploaded = false;
                    if (isset($files['dokumen'][$slug]) && $files['dokumen'][$slug]->isValid()) {
                        $newFileUploaded = true;
                    }

                    if (!$newFileUploaded) {
                        $dokumenModel->insert([
                            'pengajuan_id' => $pengajuanId,
                            'nip' => $targetNip,
                            'nama_dokumen' => $reusedNames[$slug] ?? strtoupper(str_replace('_', ' ', $slug)),
                            'file_path' => $filePath,
                            'status_verifikasi' => 'OK', // Mark as OK since it's from the verified library
                        ]);
                    }
                }
            }

            // Notification WhatsApp
            $userModel = new UserModel();
            $pegawaiModel = new PegawaiModel();
            $wa = new WhatsApp();

            $verifikators = $userModel->getUsersByRole('verifikator');
            $applicantName = session()->get('name') ?? 'ASN';

            // Get target pegawai details
            $targetNip = $this->request->getPost('target_nip');
            $targetPegawai = $pegawaiModel->where('nip_baru', $targetNip)->first();
            $targetName = $targetPegawai ? $targetPegawai['nama'] : $targetNip;

            $message = "🔔 *Usulan KP Baru: {$targetName}*\n\n";
            $message .= "Halo Verifikator, ada usulan Kenaikan Pangkat baru masuk ke sistem:\n";
            $message .= "• Diajukan Oleh: *$applicantName*\n";
            $message .= "• Subjek Pegawai: *$targetName* ($targetNip)\n";
            $message .= "• Jenis KP: " . $this->request->getPost('jenis_kp') . "\n";
            $message .= "• Periode: " . $this->request->getPost('periode') . " " . $this->request->getPost('tahun') . "\n\n";
            $message .= "Mohon segera login ke dashboard SIMKP untuk memverifikasi berkas tersebut. Terima kasih.";

            foreach ($verifikators as $v) {
                if (!empty($v['no_hp'])) {
                    $wa->sendMessage($v['no_hp'], $message);
                }
            }

            // Notification for Applicant (Current User)
            $applicantProfile = $pegawaiModel->where('user_id', session()->get('id'))->first();
            if ($applicantProfile && !empty($applicantProfile['no_hp'])) {
                $userMsg = "✅ *Pendaftaran Usul KP Berhasil*\n\n";
                $userMsg .= "Halo *{$applicantProfile['nama']}*,\n";
                $userMsg .= "Usulan Kenaikan Pangkat yang Anda peruntukan bagi *{$targetName}* telah berhasil didaftarkan ke sistem dengan status *PENDING*.\n\n";
                $userMsg .= "Silakan pantau perkembangan verifikasi berkas melalui menu Riwayat di link berikut:\n";
                $userMsg .= base_url("user/pengajuan/riwayat_detail/{$pengajuanId}");
                $wa->sendMessage($applicantProfile['no_hp'], $userMsg);
            }

            $session->setFlashdata('success', 'Usul Kenaikan Pangkat berhasil diajukan!');
            return redirect()->to('/user/dashboard');
        }

        return redirect()->back()->withInput();
    }

    public function search_pegawai($nip)
    {
        try {
            $pegawaiModel = new PegawaiModel();
            $pegawai = $pegawaiModel->where('nip_baru', $nip)->first();

            if ($pegawai) {
                return $this->response->setJSON([
                    'success' => true,
                    'pegawai' => $pegawai
                ]);
            }

            return $this->response->setJSON(['success' => false, 'message' => 'Data Pegawai tidak ditemukan.']);
        } catch (\Exception $e) {
            return $this->response->setStatusCode(500)->setJSON([
                'success' => false,
                'message' => 'Gagal mengambil data database: ' . $e->getMessage()
            ]);
        }
    }

    public function check_existing_docs($nip)
    {
        try {
            $dokumenModel = new DokumenModel();
            $nip = trim($nip);

            // 1. DATABASE SEARCH
            $documents = $dokumenModel->where('nip', $nip)
                ->orderBy('id', 'DESC')
                ->findAll();

            $existing = [];

            // Process Database Results
            foreach ($documents as $doc) {
                $rawName = strtoupper($doc['nama_dokumen'] ?? '');
                $docData = ['file_path' => $doc['file_path'], 'original_name' => $doc['nama_dokumen']];

                $cleanKey = preg_replace('/[^A-Z0-9]/', '', $rawName);
                if (!empty($cleanKey)) $existing[$cleanKey] = $docData;

                // Fuzzy Mapping
                if (strpos($rawName, 'SKP') !== false) {
                    if (strpos($rawName, '2025') !== false || strpos($rawName, 'PERTAMA') !== false) $existing['FUZZY_SKP1'] = $docData;
                    if (strpos($rawName, '2024') !== false || strpos($rawName, 'KEDUA') !== false) $existing['FUZZY_SKP2'] = $docData;
                }
                if (strpos($rawName, 'SK') !== false && (strpos($rawName, 'KP') !== false || strpos($rawName, 'PANGKAT') !== false)) $existing['FUZZY_SKKP'] = $docData;
                if (strpos($rawName, 'PNS') !== false && strpos($rawName, 'CPNS') === false) $existing['FUZZY_SKPNS'] = $docData;
                if (strpos($rawName, 'CPNS') !== false) $existing['FUZZY_SKCPNS'] = $docData;
                if (strpos($rawName, 'UJIAN') !== false) $existing['FUZZY_UJIAN_DINAS'] = $docData;
                if (strpos($rawName, 'JABATAN') !== false) {
                    if (strpos($rawName, 'ATASAN') !== false) $existing['FUZZY_SK_JABATAN_ATASAN'] = $docData;
                    else $existing['FUZZY_SK_JABATAN_TERAKHIR'] = $docData;
                }
                if (strpos($rawName, 'PELANTIKAN') !== false) $existing['FUZZY_PELANTIKAN'] = $docData;
                if (strpos($rawName, 'IJAZAH') !== false) $existing['FUZZY_IJAZAH'] = $docData;
                if (strpos($rawName, 'TRANSKRIP') !== false) $existing['FUZZY_TRANSKRIP'] = $docData;
                if (strpos($rawName, 'GELAR') !== false) $existing['FUZZY_GELAR'] = $docData;
                if (strpos($rawName, 'PEMBERHENTIAN') !== false) $existing['FUZZY_PEMBERHENTIAN'] = $docData;
                if (strpos($rawName, 'MUTASI') !== false || strpos($rawName, 'PINDAH') !== false) $existing['FUZZY_MUTASI'] = $docData;
            }

            // 2. PHYSICAL FILE SYSTEM SEARCH (Fallback)
            $possiblePaths = [
                FCPATH . 'uploads/dokumen/',
                ROOTPATH . 'public/uploads/dokumen/',
                './public/uploads/dokumen/',
                './uploads/dokumen/'
            ];

            $year1 = date('Y');
            $year2 = $year1 - 1;

            foreach ($possiblePaths as $path) {
                if (is_dir($path)) {
                    $files = scandir($path);
                    foreach ($files as $file) {
                        if (strpos($file, $nip) === 0) {
                            $fUpper = strtoupper($file);
                            $fileData = ['file_path' => $file, 'original_name' => 'FileSystem: ' . $file];

                            // Dynamic Key generation for non-fuzzy matching
                            $cleanFileKey = preg_replace('/[^A-Z0-9]/', '', substr($fUpper, strlen($nip)));
                            $cleanFileKey = preg_replace('/PDF$/', '', $cleanFileKey); // Remove extension
                            if (!empty($cleanFileKey)) $existing[$cleanFileKey] = $fileData;

                            if (strpos($fUpper, 'SKP') !== false) {
                                if (strpos($fUpper, (string) $year1) !== false || strpos($fUpper, 'PERTAMA') !== false) $existing['FUZZY_SKP1'] = $fileData;
                                if (strpos($fUpper, (string) $year2) !== false || strpos($fUpper, 'KEDUA') !== false) $existing['FUZZY_SKP2'] = $fileData;
                            }
                            if (strpos($fUpper, 'SK_KP') !== false || (strpos($fUpper, 'SK') !== false && strpos($fUpper, 'KP') !== false)) $existing['FUZZY_SKKP'] = $fileData;
                            if (strpos($fUpper, 'SK_PNS') !== false || (strpos($fUpper, 'PNS') !== false && strpos($fUpper, 'CPNS') === false)) $existing['FUZZY_SKPNS'] = $fileData;
                            if (strpos($fUpper, 'SK_CPNS') !== false || strpos($fUpper, 'CPNS') !== false) $existing['FUZZY_SKCPNS'] = $fileData;
                            if (strpos($fUpper, 'UJIAN_DINAS') !== false) $existing['FUZZY_UJIAN_DINAS'] = $fileData;
                            if (strpos($fUpper, 'JABATAN_ATASAN') !== false) $existing['FUZZY_SK_JABATAN_ATASAN'] = $fileData;
                            else if (strpos($fUpper, 'JABATAN_TERAKHIR') !== false) $existing['FUZZY_SK_JABATAN_TERAKHIR'] = $fileData;
                            if (strpos($fUpper, 'PELANTIKAN') !== false) $existing['FUZZY_PELANTIKAN'] = $fileData;
                            if (strpos($fUpper, 'IJAZAH') !== false) $existing['FUZZY_IJAZAH'] = $fileData;
                            if (strpos($fUpper, 'TRANSKRIP') !== false) $existing['FUZZY_TRANSKRIP'] = $fileData;
                            if (strpos($fUpper, 'GELAR') !== false) $existing['FUZZY_GELAR'] = $fileData;
                            if (strpos($fUpper, 'PEMBERHENTIAN') !== false) $existing['FUZZY_PEMBERHENTIAN'] = $fileData;
                            if (strpos($fUpper, 'MUTASI') !== false || strpos($fUpper, 'PINDAH') !== false) $existing['FUZZY_MUTASI'] = $fileData;
                        }
                    }
                    // Break if path found and processed (avoid duplicate results from different paths)
                    if (count($existing) > 0) break;
                }
            }

            log_message('debug', "CheckExistingDocs for NIP $nip found " . count($existing) . " files.");

            return $this->response->setJSON([
                'success' => true,
                'count' => count($existing),
                'nip_searched' => $nip,
                'documents' => (object)$existing // Ensure it's an object/assoc array in JSON
            ]);
        } catch (\Exception $e) {
            log_message('error', "CheckExistingDocs Error: " . $e->getMessage());
            return $this->response->setStatusCode(500)->setJSON([
                'success' => false,
                'message' => $e->getMessage()
            ]);
        }
    }

    public function riwayat()
    {
        $pengajuanModel = new PengajuanModel();
        $userId = session()->get('id');

        $history = $pengajuanModel->select('pengajuan.*, pegawai.nama as target_nama, pegawai.nip_baru as target_nip')
            ->join('pegawai', 'pegawai.nip_baru = pengajuan.target_nip', 'left')
            ->groupStart()
            ->where('pengajuan.user_id', $userId)
            ->orWhere('pengajuan.created_by', $userId)
            ->groupEnd()
            ->orderBy('pengajuan.created_at', 'DESC')
            ->findAll();

        $data = [
            'title' => 'Riwayat Usul KP',
            'history_pengajuan' => $history,
        ];
        return view('user/riwayat', $data);
    }
    public function riwayat_detail($id)
    {
        $pengajuanModel = new PengajuanModel();
        $dokumenModel = new DokumenModel();
        $userId = session()->get('id');

        $pengajuan = $pengajuanModel->select('pengajuan.*, target.nama as target_nama, target.nip_baru as target_nip')
            ->join('pegawai as target', 'target.nip_baru = pengajuan.target_nip', 'left')
            ->where('pengajuan.id', $id)
            ->groupStart()
            ->where('pengajuan.user_id', $userId)
            ->orWhere('pengajuan.created_by', $userId)
            ->groupEnd()
            ->first();

        if (!$pengajuan) {
            return redirect()->to('/user/riwayat')->with('error', 'Data tidak ditemukan atau Anda tidak memiliki akses.');
        }

        $data = [
            'title' => 'Detail Usulan #' . $id,
            'pengajuan' => $pengajuan,
            'dokumen' => $dokumenModel->where('pengajuan_id', $id)->findAll(),
        ];

        return view('user/riwayat_detail', $data);
    }

    public function edit($id)
    {
        $pengajuanModel = new PengajuanModel();
        $dokumenModel = new DokumenModel();
        $pegawaiModel = new PegawaiModel();
        $userId = session()->get('id');

        $pengajuan = $pengajuanModel->select('pengajuan.*, target.nama as target_nama, target.nip_baru as target_nip')
            ->join('pegawai as target', 'target.nip_baru = pengajuan.target_nip', 'left')
            ->where('pengajuan.id', $id)
            ->groupStart()
            ->where('pengajuan.user_id', $userId)
            ->orWhere('pengajuan.created_by', $userId)
            ->groupEnd()
            ->first();

        if (!$pengajuan || $pengajuan['status'] !== 'REVISION') {
            return redirect()->to('/user/riwayat')->with('error', 'Tidak dapat mengedit. Berkas tidak dalam status REVISION.');
        }

        $data = [
            'title' => 'Perbaiki Pengajuan #' . $id,
            'pengajuan' => $pengajuan,
            'dokumen' => $dokumenModel->where('pengajuan_id', $id)->findAll(),
            'all_pegawai' => $pegawaiModel->findAll(),
        ];

        return view('user/pengajuan_edit', $data);
    }

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

        $pengajuan = $pengajuanModel->find($id);
        if (!$pengajuan || $pengajuan['status'] !== 'REVISION') {
            return redirect()->to('/user/riwayat')->with('error', 'Akses ditolak.');
        }

        // Update basic data
        $postData = $this->request->getPost();
        unset($postData['target_nip']); // Don't change target
        unset($postData['user_id']);

        // Set status back to PENDING for re-verification
        $postData['status'] = 'PENDING';

        $pengajuanModel->update($id, $postData);

        // Handle uploaded files
        $files = $this->request->getFiles();
        if ($files) {
            foreach ($files['dokumen'] as $docId => $file) {
                if ($file->isValid() && !$file->hasMoved()) {
                    // Check size 1MB
                    if ($file->getSize() > 1024 * 1024) {
                        continue; // Skip or handle error
                    }

                    $targetNip = $pengajuan['target_nip'];
                    $docNameClean = str_replace(' ', '_', strtoupper($docId)); // docId might not be human name here
                    // Better get the doc name from the model
                    $oldDoc = $dokumenModel->find($docId);
                    $docName = $oldDoc ? str_replace(' ', '_', strtoupper($oldDoc['nama_dokumen'])) : 'DOC_' . $docId;

                    $newName = $targetNip . '_' . $docName . '.' . $file->getExtension();
                    $file->move(FCPATH . 'uploads/dokumen', $newName, true); // true to overwrite

                    // Update existing document record
                    $dokumenModel->update($docId, [
                        'nip' => $targetNip,
                        'file_path' => $newName,
                        'status_verifikasi' => 'PENDING',
                        'catatan' => null
                    ]);
                }
            }
        }

        // Notify Verifikators about revision fix
        $wa = new WhatsApp();
        $userModel = new UserModel();
        $verifikators = $userModel->getUsersByRole('verifikator');

        $message = "📝 *Revisi Masuk: #{$id}*\n\n";
        $message .= "Halo Verifikator, user telah memperbaiki berkas pengajuan #{$id} ({$pengajuan['target_nip']}).\n";
        $message .= "Mohon lakukan verifikasi ulang. Terima kasih.";

        foreach ($verifikators as $v) {
            if (!empty($v['no_hp'])) {
                $wa->sendMessage($v['no_hp'], $message);
            }
        }

        return redirect()->to('/user/riwayat')->with('success', 'Perbaikan berhasil dikirim. Menunggu verifikasi ulang.');
    }
}
