<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\WaLogModel;
use App\Libraries\WhatsApp;

class Chatbot extends BaseController
{
    public function index()
    {
        $logModel = new WaLogModel();

        $data = [
            'title' => 'Monitoring Chatbot WA',
            'logs' => $logModel->orderBy('created_at', 'DESC')->findAll(100), // Get latest 100
        ];

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

    public function test()
    {
        $settingModel = new \App\Models\SettingModel();
        $target = $this->request->getPost('target') ?? $settingModel->getValue('wa_test_number', '');

        if (empty($target)) {
            if ($this->request->isAJAX()) {
                return $this->response->setJSON(['success' => false, 'message' => 'Nomor Test belum diatur di Pengaturan Umum.']);
            }
            return redirect()->back()->with('error', 'Nomor Test tidak ditemukan.');
        }

        $wa = new WhatsApp();
        $message = "Halo! Ini adalah pesan TEST dari Sistem SIMKP ASN. Jika Anda menerima ini, berarti konfigurasi WhatsApp (Kirimi.id) sudah BERHASIL.";

        $response = $wa->sendMessage($target, $message);

        if ($this->request->isAJAX() || $this->request->getPost('type') === 'connection_test') {
            return $this->response->setJSON([
                'success' => $response,
                'message' => $response ? 'Pesan berhasil dikirim!' : 'Gagal mengirim pesan. Periksa Secret Key / User Code Anda.'
            ]);
        }

        if ($response) {
            return redirect()->back()->with('success', 'Pesan percobaan berhasil dikirim.');
        } else {
            return redirect()->back()->with('error', 'Gagal mengirim pesan.');
        }
    }

    public function delete($id)
    {
        $logModel = new WaLogModel();
        if ($logModel->delete($id)) {
            return redirect()->back()->with('success', 'Riwayat notifikasi berhasil dihapus.');
        }
        return redirect()->back()->with('error', 'Gagal menghapus riwayat.');
    }

    public function clear()
    {
        $logModel = new WaLogModel();
        $db = \Config\Database::connect();
        $db->table('wa_logs')->truncate();
        return redirect()->back()->with('success', 'Semua riwayat notifikasi telah dibersihkan.');
    }
}
