<?php
namespace App\Helpers;

class Sms
{
    private static function getSetting($key, $default = '')
    {
        try {
            $db = \App\Config\Database::getInstance()->getConnection();
            $stmt = $db->prepare("SELECT `value` FROM settings WHERE `key` = ?");
            $stmt->execute([$key]);
            $result = $stmt->fetch(\PDO::FETCH_OBJ);
            return $result ? $result->value : $default;
        } catch (\Exception $e) {
            return $default;
        }
    }

    public static function send($to, $message)
    {
        $provider = self::getSetting('sms_provider', 'hubtel');

        if ($provider === 'hubtel') {
            return self::sendHubtel($to, $message);
        }

        error_log("SMS: Unknown provider $provider");
        return false;
    }

    public static function sendHubtel($to, $message)
    {
        $apiKey = self::getSetting('sms_api_key');
        $apiSecret = self::getSetting('sms_api_secret');
        $senderId = self::getSetting('sms_sender_id', 'GAS');

        if (empty($apiKey) || empty($apiSecret)) {
            error_log('SMS Hubtel: API credentials not configured');
            return false;
        }

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL => 'https://api.hubtel.com/v1/messages/send',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
            CURLOPT_USERPWD => "$apiKey:$apiSecret",
            CURLOPT_POSTFIELDS => json_encode([
                'From' => $senderId,
                'To' => $to,
                'Content' => $message,
                'RegisteredDelivery' => true,
            ]),
            CURLOPT_TIMEOUT => 30,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode >= 200 && $httpCode < 300) {
            return true;
        }

        error_log("SMS Hubtel Error (HTTP $httpCode): $response");
        return false;
    }

    public static function sendPasswordResetOtp($phone, $otp)
    {
        $message = "Your Ghana Anaesthesiologists Society password reset code is: $otp. This code expires in 15 minutes.";
        return self::send($phone, $message);
    }
}
