<?php

namespace App\Libraries;

use App\Models\SettingModel;
use App\Models\WaLogModel;

class WhatsApp
{
    protected $userCode;
    protected $secretKey;
    protected $deviceId;
    protected $apiUrl = 'https://api.kirimi.id/v1/send-message';

    public function __construct()
    {
        $settingModel = new SettingModel();
        $this->userCode = $settingModel->getValue('wa_user_code', '');
        $this->secretKey = $settingModel->getValue('wa_secret_key', '');
        $this->deviceId = $settingModel->getValue('wa_device_id', '');
    }

    public function sendMessage(string $target, string $message)
    {
        if (empty($this->userCode) || empty($this->secretKey)) {
            log_message('error', 'WhatsApp Credentials (User Code/Secret Key) are not set.');
            return false;
        }

        // Clean phone number
        $target = preg_replace('/[^0-9]/', '', $target);
        if (substr($target, 0, 1) === '0') {
            $target = '62' . substr($target, 1);
        } else if (substr($target, 0, 1) === '8') {
            $target = '62' . $target;
        }

        $curl = curl_init();
        $payload = [
            'user_code' => $this->userCode,
            'secret' => $this->secretKey,
            'device_id' => $this->deviceId,
            'phone' => $target,
            'message' => $message
        ];

        curl_setopt_array($curl, array(
            CURLOPT_URL => $this->apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json'
            ),
        ));

        $response = curl_exec($curl);
        curl_close($curl);

        $resData = json_decode($response, true);

        // Success check based on Kirimi.id response
        $isSuccess = ($resData && (
            (isset($resData['success']) && ($resData['success'] === true || $resData['success'] === 'success')) ||
            (isset($resData['status']) && ($resData['status'] === true || $resData['status'] === 'success')) ||
            (isset($resData['code']) && ($resData['code'] == 200)) ||
            isset($resData['msg_id']) ||
            isset($resData['id'])
        ));

        $logModel = new WaLogModel();
        $logModel->insert([
            'target' => $target,
            'message' => $message,
            'status' => $isSuccess ? 'SUCCESS' : 'FAILED',
            'response' => $response,
            'created_at' => date('Y-m-d H:i:s')
        ]);

        return $isSuccess;
    }
}
