<?php
// /edenrms/includes/sms.php
// Safe, provider-pluggable SMS helpers. Nothing executes at include time.

if (session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once __DIR__ . '/auth.php';

/* ---------------- settings helpers ---------------- */
if (!function_exists('sms_setting_get')) {
  function sms_setting_get(mysqli $db, string $k, string $d=''): string {
    $k = $db->real_escape_string($k);
    $res = $db->query("SELECT v FROM app_settings WHERE k='{$k}'");
    if ($res && ($row = $res->fetch_row())) return (string)$row[0];
    return $d;
  }
}

if (!function_exists('sms_cfg')) {
  function sms_cfg(): array {
    static $cfg = null;
    if ($cfg !== null) return $cfg;

    $db = ec_db();
    if ($db) {
      @$db->query("CREATE TABLE IF NOT EXISTS app_settings (
        k VARCHAR(64) PRIMARY KEY,
        v VARCHAR(255) NOT NULL,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");

      $cfg = [
        'sms_enabled'          => sms_setting_get($db,'sms_enabled','0') === '1',
        'birthday_sms_enabled' => sms_setting_get($db,'birthday_sms_enabled','0') === '1',
        'sms_provider'         => sms_setting_get($db,'sms_provider','devlog'), // devlog|textbelt|vonage|twilio
        'default_country'      => sms_setting_get($db,'sms_default_country','LK'),

        // Twilio
        'twilio_sid'           => sms_setting_get($db,'twilio_sid',''),
        'twilio_token'         => sms_setting_get($db,'twilio_token',''),
        'twilio_from'          => sms_setting_get($db,'twilio_from',''),

        // Vonage
        'vonage_key'           => sms_setting_get($db,'vonage_key',''),
        'vonage_secret'        => sms_setting_get($db,'vonage_secret',''),
        'vonage_from'          => sms_setting_get($db,'vonage_from',''),

        // Textbelt
        'textbelt_key'         => sms_setting_get($db,'textbelt_key','textbelt'),
      ];
    } else {
      $cfg = [
        'sms_enabled' => false, 'birthday_sms_enabled' => false, 'sms_provider' => 'devlog', 'default_country' => 'LK',
        'twilio_sid' => '', 'twilio_token' => '', 'twilio_from' => '',
        'vonage_key' => '', 'vonage_secret' => '', 'vonage_from' => '',
        'textbelt_key' => 'textbelt',
      ];
    }
    return $cfg;
  }
}

/* ---------------- formatting ---------------- */
/* Accept mixed input and sanitize to avoid TypeErrors if callers pass null. */
if (!function_exists('sms_normalize_e164')) {
  function sms_normalize_e164($to, string $cc='LK'): string {
    $digits = preg_replace('/\D+/', '', (string)$to);
    if ($digits === '') return '';

    if ($cc === 'LK') { // Sri Lanka
      if (preg_match('/^0\d{9}$/', $digits)) return '+94' . substr($digits, 1);
      if (preg_match('/^94\d{9}$/', $digits)) return '+' . $digits;
    }
    // Generic: if already +..., keep; else prefix +
    return str_starts_with((string)$to, '+') ? (string)$to : '+' . $digits;
  }
}

/* ---------------- send ---------------- */
if (!function_exists('sms_send')) {
  function sms_send($to, string $msg, ?string &$err = null): bool {
    $cfg = sms_cfg();
    if (!$cfg['sms_enabled']) { $err = 'SMS is disabled'; return false; }

    $to = sms_normalize_e164($to, $cfg['default_country'] ?: 'LK');
    if ($to === '') { $err = 'Invalid phone'; return false; }

    $provider = $cfg['sms_provider'] ?: 'devlog';

    // 1) Dev log (always succeeds; writes to storage/sms.log)
    if ($provider === 'devlog') {
      $logDir = __DIR__ . '/../storage';
      if (!is_dir($logDir)) @mkdir($logDir, 0777, true);
      @file_put_contents($logDir . '/sms.log', '[' . date('Y-m-d H:i:s') . "] {$to} | {$msg}\n", FILE_APPEND);
      return true;
    }

    // 2) Textbelt (https://textbelt.com) — free 1/day with key "textbelt"
    if ($provider === 'textbelt') {
      $key = $cfg['textbelt_key'] ?: 'textbelt';
      $ch = curl_init('https://textbelt.com/text');
      curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query(['phone' => $to, 'message' => $msg, 'key' => $key]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
      ]);
      $resp = curl_exec($ch);
      if (curl_errno($ch)) { $err = curl_error($ch); curl_close($ch); return false; }
      curl_close($ch);
      $data = json_decode($resp, true);
      if (!empty($data['success'])) return true;
      $err = $data['error'] ?? 'Textbelt error';
      return false;
    }

    // 3) Vonage (Nexmo)
    if ($provider === 'vonage') {
      $key    = $cfg['vonage_key'];
      $secret = $cfg['vonage_secret'];
      $from   = $cfg['vonage_from'] ?: 'EdenRMS';
      if (!$key || !$secret) { $err = 'Vonage creds missing'; return false; }

      $ch = curl_init('https://rest.nexmo.com/sms/json');
      curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query(['api_key'=>$key,'api_secret'=>$secret,'to'=>$to,'from'=>$from,'text'=>$msg]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
      ]);
      $resp = curl_exec($ch);
      if (curl_errno($ch)) { $err = curl_error($ch); curl_close($ch); return false; }
      curl_close($ch);
      $data = json_decode($resp, true);
      $m = $data['messages'][0] ?? [];
      if (($m['status'] ?? '1') === '0') return true;
      $err = $m['error-text'] ?? 'Vonage error';
      return false;
    }

    // 4) Twilio (kept for completeness)
    if ($provider === 'twilio') {
      $sid   = $cfg['twilio_sid'];
      $token = $cfg['twilio_token'];
      $from  = $cfg['twilio_from'];
      if (!$sid || !$token || !$from) { $err = 'Twilio creds missing'; return false; }

      $url = "https://api.twilio.com/2010-04-01/Accounts/{$sid}/Messages.json";
      $ch = curl_init($url);
      curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query(['From'=>$from,'To'=>$to,'Body'=>$msg]),
        CURLOPT_USERPWD => $sid . ':' . $token,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 15,
      ]);
      $resp = curl_exec($ch);
      $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      if (curl_errno($ch)) { $err = curl_error($ch); curl_close($ch); return false; }
      curl_close($ch);
      if ($http >= 200 && $http < 300) return true;
      $err = "Twilio HTTP {$http}: {$resp}";
      return false;
    }

    $err = 'Unknown provider: ' . $provider;
    return false;
  }
}
