<?php
require_once __DIR__ . '/../includes/db.php';

class Wablas {
    private $token;
    private $baseUrl;
    public $lastError = '';
    public $lastResponse = null;

    public function __construct() {
        // Load config dari database
        $db = db();
        try {
            $stmt = $db->prepare("SELECT setting_value FROM wablas_config WHERE setting_key = ?");
            
            $stmt->execute(['base_url']);
            $row = $stmt->fetch();
            $this->baseUrl = $row ? rtrim($row['setting_value'], '/') : 'https://tegal.wablas.com/api';
            
            $stmt->execute(['token']);
            $row = $stmt->fetch();
            $this->token = $row ? $row['setting_value'] : '';
        } catch (Exception $e) {
            $cfg = require __DIR__ . '/../config/wablas.php';
            $this->token = $cfg['token'] ?? '';
            $this->baseUrl = rtrim($cfg['baseUrl'] ?? 'https://tegal.wablas.com/api', '/');
        }
    }

    /**
     * Cek apakah Wablas sudah dikonfigurasi
     */
    public function isConfigured() {
        return !empty($this->token) && !empty($this->baseUrl);
    }

    /**
     * Kirim pesan ke satu nomor
     * Format Wablas API v1: GET dengan query string
     * URL: https://tegal.wablas.com/api/send-message?phone={phone}&message={message}&token={token}
     */
    public function send($phone, $message) {
        $this->lastError = '';
        $this->lastResponse = null;

        if (!$this->isConfigured()) {
            return [
                'success' => false,
                'error'   => 'Wablas belum dikonfigurasi. Silakan atur Base URL dan Token.',
                'debug'   => ['token' => $this->token ? 'SET' : 'EMPTY', 'base_url' => $this->baseUrl]
            ];
        }

        $phone = $this->normalizePhone($phone);
        
        // Validasi nomor
        if (!preg_match('/^62\d{8,13}$/', $phone)) {
            return [
                'success' => false,
                'error'   => "Format nomor tidak valid: $phone (harus 62xxx)",
                'debug'   => ['original_phone' => $phone]
            ];
        }

        // Build URL dengan query string (Format Wablas API v1)
        $url = $this->baseUrl . '/send-message?' . http_build_query([
            'phone'   => $phone,
            'message' => $message,
            'token'   => $this->token
        ]);

        // cURL request (GET)
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPGET, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        $curlErrno = curl_errno($ch);
        curl_close($ch);

        // Decode response
        $result = json_decode($response, true);
        $this->lastResponse = $result;

        // Handle cURL error
        if ($curlErrno) {
            $this->lastError = "cURL Error [$curlErrno]: $curlError";
            return [
                'success'   => false,
                'http_code' => 0,
                'error'     => "Koneksi gagal: $curlError",
                'debug'     => [
                    'curl_error' => $curlError,
                    'curl_errno' => $curlErrno,
                    'url' => $url
                ]
            ];
        }

        // Handle HTTP error
        if ($httpCode !== 200) {
            $this->lastError = "HTTP $httpCode: " . ($result['message'] ?? $result['error'] ?? $response);
            return [
                'success'   => false,
                'http_code' => $httpCode,
                'error'     => "HTTP Error $httpCode: " . ($result['message'] ?? $response),
                'response'  => $result,
                'debug'     => [
                    'http_code' => $httpCode,
                    'raw_response' => $response,
                    'url' => $url
                ]
            ];
        }

        // Handle Wablas response
        $success = isset($result['status']) && $result['status'] === true;
        
        if (!$success) {
            $errorMsg = $result['error'] ?? $result['message'] ?? 'Unknown error from Wablas';
            $this->lastError = $errorMsg;
            return [
                'success'   => false,
                'http_code' => $httpCode,
                'error'     => $errorMsg,
                'response'  => $result,
                'debug'     => [
                    'raw_response' => $response,
                    'url' => $url
                ]
            ];
        }

        return [
            'success'    => true,
            'http_code'  => $httpCode,
            'response'   => $result,
            'message_id' => $result['id'] ?? null
        ];
    }

    /**
     * Kirim pesan test
     */
    public function sendTest($phone, $message) {
        return $this->send($phone, $message);
    }

    /**
     * Kirim notifikasi tagihan
     */
    public function sendBillingReminder($phone, $data) {
        $msg  = "Yth. Pelanggan PT Lintas Fiber Nusantara\n\n";
        $msg .= "Nomor: " . $data['customer_number'] . "\n";
        $msg .= "Nama: " . $data['name'] . "\n";
        $msg .= "Paket: " . $data['package_name'] . "\n";
        $msg .= "Tagihan: Rp " . number_format($data['amount'], 0, ',', '.') . "\n\n";
        $msg .= "Tagihan internet Anda akan jatuh tempo dalam 3 hari.\n";
        $msg .= "Pembayaran dapat dilakukan melalui:\n\n";
        $msg .= "• QRIS\n";
        $msg .= "• Virtual Account\n";
        $msg .= "• Indomaret / Alfamart\n\n";
        $msg .= "Bayar Sekarang melalui link berikut:\n";
        $msg .= $data['payment_url'] . "\n\n";
        $msg .= "Terima kasih atas kepercayaan Anda.\n\n";
        $msg .= "Hormat kami,\n";
        $msg .= "Tim Layanan Pelanggan\n";
        $msg .= "PT Lintas Fiber Nusantara";

        return $this->sendAndLog($phone, $msg, 'reminder_h3', $data['customer_id'] ?? null);
    }

    /**
     * Notifikasi pembayaran berhasil
     */
    public function sendPaymentSuccess($phone, $data) {
        $msg  = "✅ *PEMBAYARAN BERHASIL*\n\n";
        $msg .= "Yth. " . $data['name'] . "\n\n";
        $msg .= "Pembayaran tagihan internet Anda telah kami terima:\n\n";
        $msg .= "No. Pelanggan: " . $data['customer_number'] . "\n";
        $msg .= "Periode: " . $data['period'] . "\n";
        $msg .= "Jumlah: Rp " . number_format($data['amount'], 0, ',', '.') . "\n";
        $msg .= "Status: LUNAS\n\n";
        $msg .= "Koneksi internet Anda telah diaktifkan kembali.\n\n";
        $msg .= "Terima kasih.\n";
        $msg .= "PT Lintas Fiber Nusantara";

        return $this->sendAndLog($phone, $msg, 'payment_success', $data['customer_id'] ?? null);
    }

    /**
     * Notifikasi suspend
     */
    public function sendSuspensionNotice($phone, $data) {
        $msg  = "⚠️ *PEMBERITAHUAN SUSPENSI*\n\n";
        $msg .= "Yth. " . $data['name'] . "\n\n";
        $msg .= "Tagihan internet Anda belum dibayar melewati masa tenggang.\n";
        $msg .= "Koneksi internet Anda telah kami *SUSPEND* sementara.\n\n";
        $msg .= "Segera lakukan pembayaran untuk mengaktifkan kembali:\n";
        $msg .= $data['payment_url'] . "\n\n";
        $msg .= "PT Lintas Fiber Nusantara";

        return $this->sendAndLog($phone, $msg, 'suspension', $data['customer_id'] ?? null);
    }

    /**
     * Kirim broadcast ke banyak nomor
     */
    public function sendBroadcast($phones, $message, $delay = 1) {
        $results = [
            'total'   => count($phones),
            'sent'    => 0,
            'failed'  => 0,
            'details' => []
        ];

        foreach ($phones as $phone) {
            $result = $this->send($phone, $message);
            
            if ($result['success']) {
                $results['sent']++;
            } else {
                $results['failed']++;
            }

            $results['details'][] = [
                'phone'   => $phone,
                'success' => $result['success'],
                'error'   => $result['error'] ?? null
            ];

            if ($delay > 0) {
                sleep($delay);
            }
        }

        return $results;
    }

    private function sendAndLog($phone, $message, $type, $customerId = null) {
        $result = $this->send($phone, $message);
        
        try {
            $stmt = db()->prepare("INSERT INTO notification_logs 
                (customer_id, phone, type, message, status, wablas_id, wablas_response) 
                VALUES (?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([
                $customerId,
                $phone,
                $type,
                $message,
                $result['success'] ? 'sent' : 'failed',
                $result['message_id'] ?? null,
                json_encode($result['response'] ?? ['error' => $result['error']])
            ]);
        } catch (Exception $e) {
            // Ignore log error
        }
        
        return $result;
    }

    /**
     * Normalisasi nomor telepon ke format 62xxx
     */
    private function normalizePhone($phone) {
        $phone = preg_replace('/\D/', '', $phone);
        
        // Format: 62xxx
        if (substr($phone, 0, 2) === '62') {
            return $phone;
        }
        // Format: 08xxx
        if (substr($phone, 0, 1) === '0') {
            return '62' . substr($phone, 1);
        }
        // Format: 8xxx
        if (substr($phone, 0, 1) === '8') {
            return '62' . $phone;
        }
        
        return $phone;
    }
}