<?php
/**
 * SmsService — SMSlenz Gateway (cURL version for cPanel compatibility)
 * API: https://smslenz.lk/api
 */
class SmsService
{
    private static function cfg(): array
    {
        return [
            'enabled'   => setting('sms_enabled',   '0') === '1',
            'user_id'   => setting('sms_user_id',   ''),
            'api_key'   => setting('sms_api_key',   ''),
            'sender_id' => setting('sms_sender_id', 'SMSlenzDEMO'),
            'base_url'  => rtrim(setting('sms_api_url','https://smslenz.lk/api'),'/'),
        ];
    }

    /** Normalise Sri Lankan phone → +94XXXXXXXXX */
    public static function formatPhone(string $raw): ?string
    {
        $p = preg_replace('/[\s\-\(\)]/', '', trim($raw));
        if (!$p) return null;
        if (preg_match('/^\+94\d{9}$/', $p))  return $p;
        if (preg_match('/^94\d{9}$/',   $p))  return '+' . $p;
        if (preg_match('/^0[0-9]{9}$/', $p))  return '+94' . substr($p, 1);
        if (preg_match('/^7[0-9]{8}$/', $p))  return '+94' . $p;
        return null;
    }

    /** Build message from template */
    public static function buildMessage(array $d): string
    {
        $tpl = setting('sms_template',
            'Hi {customer}, Invoice {invoice_no} | Total: Rs.{total} | Paid: Rs.{paid} | Thank you! - {shop_name}'
        );
        $sym = setting('currency_symbol', 'Rs.');
        return str_replace(
            ['{invoice_no}','{total}','{paid}','{change}','{balance}',
             '{customer}','{currency}','{shop_name}','{date}'],
            [$d['invoice_no'] ?? '',
             number_format((float)($d['total']   ?? 0), 2),
             number_format((float)($d['paid']    ?? 0), 2),
             number_format((float)($d['change']  ?? 0), 2),
             number_format((float)($d['balance'] ?? 0), 2),
             $d['customer']  ?? 'Customer',
             $sym,
             setting('shop_name', 'MJPOS'),
             date('d M Y')],
            $tpl
        );
    }

    /** cURL POST helper — works on shared hosting / cPanel */
    private static function curlPost(string $url, array $params): array
    {
        if (!function_exists('curl_init')) {
            return ['success' => false, 'message' => 'cURL not available on this server'];
        }

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => http_build_query($params),
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_CONNECTTIMEOUT => 8,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_HTTPHEADER     => [
                'Content-Type: application/x-www-form-urlencoded',
                'Accept: application/json',
                'User-Agent: MJPOS/1.0',
            ],
        ]);

        $raw   = curl_exec($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        $http  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($errno) {
            return ['success' => false, 'message' => "cURL error ({$errno}): {$error}"];
        }

        $resp = $raw ? json_decode($raw, true) : null;
        if (!$resp) {
            return ['success' => false, 'message' => "Invalid response (HTTP {$http}): " . substr($raw ?? '', 0, 200)];
        }
        return $resp;
    }

    /** cURL GET helper */
    private static function curlGet(string $url): array
    {
        if (!function_exists('curl_init')) {
            return ['success' => false, 'message' => 'cURL not available'];
        }
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 15,
            CURLOPT_CONNECTTIMEOUT => 8,
            CURLOPT_SSL_VERIFYPEER => true,
            CURLOPT_HTTPHEADER     => ['Accept: application/json', 'User-Agent: MJPOS/1.0'],
        ]);
        $raw   = curl_exec($ch);
        $errno = curl_errno($ch);
        $error = curl_error($ch);
        curl_close($ch);

        if ($errno) return ['success' => false, 'message' => "cURL error: {$error}"];
        return $raw ? (json_decode($raw, true) ?? []) : [];
    }

    /** Send single SMS */
    public static function send(string $phone, string $message): array
    {
        $c = self::cfg();
        if (!$c['enabled'])
            return ['success' => false, 'message' => 'SMS is disabled in settings'];
        if (!$c['user_id'] || !$c['api_key'] || !$c['sender_id'])
            return ['success' => false, 'message' => 'SMS not configured — check Settings → SMS'];

        $to = self::formatPhone($phone);
        if (!$to)
            return ['success' => false, 'message' => "Invalid phone number: {$phone}"];

        $resp = self::curlPost($c['base_url'] . '/send-sms', [
            'user_id'   => $c['user_id'],
            'api_key'   => $c['api_key'],
            'sender_id' => $c['sender_id'],
            'contact'   => $to,
            'message'   => $message,
        ]);

        if ($resp['success'] ?? false) {
            return [
                'success' => true,
                'message' => "SMS sent to {$to}",
                'balance' => $resp['data']['sms_credit_balance'] ?? null,
            ];
        }
        return [
            'success' => false,
            'message' => $resp['message'] ?? 'SMS send failed — check credentials',
        ];
    }

    /** Check account status / balance */
    public static function accountStatus(): array
    {
        $c = self::cfg();
        if (!$c['user_id'] || !$c['api_key'])
            return ['success' => false, 'message' => 'SMS not configured'];

        return self::curlGet(
            $c['base_url'] . '/account-status'
            . '?user_id=' . urlencode($c['user_id'])
            . '&api_key='  . urlencode($c['api_key'])
        );
    }
}