<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Waha_lib — Library integrasi WAHA (WhatsApp HTTP API)
 *
 * Cara pakai di controller:
 *   $this->load->library('waha_lib');
 *   $result = $this->waha_lib->send($no_hp, "Pesan WA");
 */
class Waha_lib {

    private $CI;
    private $base_url   = '';
    private $api_key    = '';
    private $session    = 'default';
    private $enabled    = false;

    public function __construct() {
        $this->CI =& get_instance();
        $this->_load_config();
    }

    // ================================================================
    // Load konfigurasi dari DB pengaturan
    // ================================================================
    private function _load_config() {
        $this->CI->load->model('Pengaturan_model');
        $p = $this->CI->Pengaturan_model->get();

        if ($p && !empty($p->waha_base_url) && !empty($p->waha_api_key)) {
            $this->base_url = rtrim($p->waha_base_url, '/');
            $this->api_key  = $p->waha_api_key;
            $this->session  = !empty($p->waha_session) ? $p->waha_session : 'default';
            $this->enabled  = (isset($p->waha_enabled) && $p->waha_enabled == 1);
        }
    }

    // ================================================================
    // Cek apakah WAHA aktif dan terkonfigurasi
    // ================================================================
    public function is_enabled() {
        return $this->enabled && !empty($this->base_url) && !empty($this->api_key);
    }

    // ================================================================
    // Format nomor HP ke chatId WA: 6281xxx@c.us
    // ================================================================
    public function format_number($no_hp) {
        $no = preg_replace('/[^0-9]/', '', $no_hp);
        if (substr($no, 0, 1) === '0') {
            $no = '62' . substr($no, 1);
        }
        return $no . '@c.us';
    }

    // ================================================================
    // Kirim pesan teks ke satu nomor
    // Return: ['success' => bool, 'message' => string, 'data' => array]
    // ================================================================
    public function send($no_hp, $text) {
        if (!$this->is_enabled()) {
            return [
                'success' => false,
                'message' => 'WAHA belum diaktifkan atau belum dikonfigurasi.'
            ];
        }

        $chat_id = $this->format_number($no_hp);
        $endpoint = $this->base_url . '/api/sendText';

        $payload = json_encode([
            'session' => $this->session,
            'chatId'  => $chat_id,
            'text'    => $text,
        ]);

        $ch = curl_init($endpoint);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $payload,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/json',
                'X-Api-Key: ' . $this->api_key,
            ],
            CURLOPT_SSL_VERIFYPEER => false,
        ]);

        $response = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_err  = curl_error($ch);
        if (version_compare(PHP_VERSION, '8.0.0', '<')) {
            curl_close($ch);
        }

        if ($curl_err) {
            return ['success' => false, 'message' => 'cURL Error: ' . $curl_err];
        }

        $resp = json_decode($response, true);
        $is_valid_json = is_array($resp);

        if ($http_code >= 200 && $http_code < 300) {
            return ['success' => true, 'message' => 'Pesan berhasil dikirim.', 'data' => $resp];
        }

        $err_msg = ($is_valid_json && isset($resp['message'])) ? $resp['message'] : ('HTTP ' . $http_code . ': ' . $response);
        return ['success' => false, 'message' => $err_msg];
    }

    // ================================================================
    // Test koneksi ke WAHA — cek status session
    // ================================================================
    public function test_connection() {
        if (empty($this->base_url) || empty($this->api_key)) {
            return ['success' => false, 'message' => 'Base URL atau API Key belum diisi.'];
        }

        $endpoint = $this->base_url . '/api/sessions/' . $this->session;

        $ch = curl_init($endpoint);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 10,
            CURLOPT_HTTPHEADER     => [
                'X-Api-Key: ' . $this->api_key,
            ],
            CURLOPT_SSL_VERIFYPEER => false,
        ]);

        $response  = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curl_err  = curl_error($ch);
        if (version_compare(PHP_VERSION, '8.0.0', '<')) {
            curl_close($ch);
        }

        if ($curl_err) {
            return ['success' => false, 'message' => 'cURL Error: ' . $curl_err];
        }

        $resp = json_decode($response, true);
        $is_valid_json = is_array($resp);

        if ($http_code === 200 || $http_code === 201) {
            $status = ($is_valid_json && isset($resp['status'])) ? $resp['status'] : 'UNKNOWN';
            if (in_array($status, ['WORKING', 'CONNECTED'])) {
                return ['success' => true, 'message' => 'Terhubung ✓ Session: ' . $this->session . ' (' . $status . ')', 'data' => $resp];
            }
            return ['success' => false, 'message' => 'Session ' . $this->session . ' status: ' . $status . '. Pastikan WA sudah di-scan.', 'data' => $resp];
        }

        if ($http_code === 404) {
            return ['success' => false, 'message' => 'Session "' . $this->session . '" tidak ditemukan di WAHA. Buat session terlebih dahulu.'];
        }

        $err_msg = isset($resp['message']) ? $resp['message'] : ('HTTP ' . $http_code . ': ' . $response);
        return ['success' => false, 'message' => $err_msg];
    }
}
