<?php
// /edenrms/pages/settings_sms.php
if (session_status() !== PHP_SESSION_ACTIVE) session_start();
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/sms.php';

ec_require_login();
if (!(ec_can('settings.manage') || ec_role()==='super_admin')) { header('Location: /edenrms/pages/403.php'); exit; }

$ACTIVE = 'settings';
$db = ec_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");

function sget(mysqli $db, string $k, string $d=''){ $k=$db->real_escape_string($k); $r=$db->query("SELECT v FROM app_settings WHERE k='{$k}'"); if($r && ($row=$r->fetch_row())) return (string)$row[0]; return $d; }
function sset(mysqli $db, string $k, string $v){ $st=$db->prepare("INSERT INTO app_settings(k,v) VALUES(?,?) ON DUPLICATE KEY UPDATE v=VALUES(v)"); if($st){ $st->bind_param('ss',$k,$v); $st->execute(); $st->close(); } }

$flash = '';
if ($_SERVER['REQUEST_METHOD']==='POST') {
  sset($db, 'sms_enabled',              isset($_POST['sms_enabled'])?'1':'0');
  sset($db, 'birthday_sms_enabled',     isset($_POST['birthday_sms_enabled'])?'1':'0');
  sset($db, 'sms_provider',             $_POST['sms_provider'] ?? 'devlog');
  sset($db, 'sms_default_country',      $_POST['sms_default_country'] ?? 'LK');

  // Twilio
  sset($db, 'twilio_sid',   trim($_POST['twilio_sid'] ?? ''));
  if (trim($_POST['twilio_token'] ?? '') !== '') sset($db, 'twilio_token', trim($_POST['twilio_token']));
  sset($db, 'twilio_from',  trim($_POST['twilio_from'] ?? ''));

  // Vonage
  sset($db, 'vonage_key',    trim($_POST['vonage_key'] ?? ''));
  if (trim($_POST['vonage_secret'] ?? '') !== '') sset($db, 'vonage_secret', trim($_POST['vonage_secret']));
  sset($db, 'vonage_from',   trim($_POST['vonage_from'] ?? ''));

  // Textbelt
  sset($db, 'textbelt_key',  trim($_POST['textbelt_key'] ?? 'textbelt'));

  // Optional test
  $test = trim($_POST['test_phone'] ?? '');
  if ($test !== '') {
    $err=null; $ok=sms_send($test,'Test SMS from Eden Campus RMS ✅',$err);
    $flash = $ok ? 'Saved. Test SMS sent.' : ('Saved. Test failed: '.htmlspecialchars($err));
  } else {
    $flash = 'Saved.';
  }
}

$cfg = sms_cfg();

include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<main class="ec-main">
<div class="container-fluid py-4"><div class="page" style="max-width:920px">
  <h5 class="fw-bold mb-3">SMS Settings</h5>
  <?php if($flash): ?><div class="alert alert-info py-2"><?= $flash ?></div><?php endif; ?>

  <form method="post" class="card-ghost p-3">
    <div class="row g-3">
      <div class="col-md-4">
        <div class="form-check form-switch">
          <input class="form-check-input" type="checkbox" id="sms_enabled" name="sms_enabled" <?= $cfg['sms_enabled']?'checked':''?>>
          <label for="sms_enabled" class="form-check-label">Enable SMS (global)</label>
        </div>
      </div>
      <div class="col-md-4">
        <div class="form-check form-switch">
          <input class="form-check-input" type="checkbox" id="birthday_sms_enabled" name="birthday_sms_enabled" <?= $cfg['birthday_sms_enabled']?'checked':''?>>
          <label for="birthday_sms_enabled" class="form-check-label">Send automatic Birthday SMS</label>
        </div>
      </div>
      <div class="col-md-4">
        <label class="form-label">Default Country</label>
        <select name="sms_default_country" class="form-select">
          <option value="LK" <?= $cfg['default_country']==='LK'?'selected':'' ?>>Sri Lanka (LK)</option>
          <option value="IN" <?= $cfg['default_country']==='IN'?'selected':'' ?>>India (IN)</option>
          <option value="US" <?= $cfg['default_country']==='US'?'selected':'' ?>>United States (US)</option>
        </select>
      </div>
    </div>

    <hr class="my-3">

    <div class="row g-3">
      <div class="col-md-4">
        <label class="form-label">Provider</label>
        <select class="form-select" name="sms_provider" id="sms_provider">
          <option value="devlog"  <?= $cfg['sms_provider']==='devlog'?'selected':'' ?>>Dev Log (write to file)</option>
          <option value="textbelt"<?= $cfg['sms_provider']==='textbelt'?'selected':'' ?>>Textbelt</option>
          <option value="vonage"  <?= $cfg['sms_provider']==='vonage'?'selected':'' ?>>Vonage (Nexmo)</option>
          <option value="twilio"  <?= $cfg['sms_provider']==='twilio'?'selected':'' ?>>Twilio</option>
        </select>
        <div class="form-text">Choose a provider. “Dev Log” writes to <code>/edenrms/storage/sms.log</code>.</div>
      </div>
    </div>

    <div id="prov_textbelt" class="mt-3">
      <div class="row g-3">
        <div class="col-md-4">
          <label class="form-label">Textbelt Key</label>
          <input name="textbelt_key" class="form-control" value="<?= htmlspecialchars($cfg['textbelt_key']) ?>" placeholder="textbelt (free) or your paid key">
        </div>
      </div>
    </div>

    <div id="prov_vonage" class="mt-3">
      <div class="row g-3">
        <div class="col-md-4">
          <label class="form-label">Vonage API Key</label>
          <input name="vonage_key" class="form-control" value="<?= htmlspecialchars($cfg['vonage_key']) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Vonage API Secret</label>
          <input name="vonage_secret" class="form-control" value="" placeholder="<?= $cfg['vonage_secret']?'•••••• (keep)':'' ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">From (sender)</label>
          <input name="vonage_from" class="form-control" value="<?= htmlspecialchars($cfg['vonage_from']) ?>" placeholder="EdenRMS or number">
        </div>
      </div>
    </div>

    <div id="prov_twilio" class="mt-3">
      <div class="row g-3">
        <div class="col-md-4">
          <label class="form-label">Twilio SID</label>
          <input name="twilio_sid" class="form-control" value="<?= htmlspecialchars($cfg['twilio_sid']) ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">Twilio Token</label>
          <input name="twilio_token" class="form-control" value="" placeholder="<?= $cfg['twilio_token']?'•••••• (keep)':'' ?>">
        </div>
        <div class="col-md-4">
          <label class="form-label">From Number (E.164)</label>
          <input name="twilio_from" class="form-control" value="<?= htmlspecialchars($cfg['twilio_from']) ?>" placeholder="+94XXXXXXXXX">
        </div>
      </div>
    </div>

    <hr class="my-3">

    <div class="row g-2 align-items-end">
      <div class="col-md-6">
        <label class="form-label">Send Test SMS To</label>
        <input name="test_phone" class="form-control" placeholder="+94XXXXXXXXX or 07XXXXXXXX">
      </div>
      <div class="col-md-6 text-md-end">
        <button class="btn btn-primary">Save settings</button>
      </div>
    </div>
  </form>

  <div class="small text-muted mt-3">
    Textbelt: free 1/day with key <code>textbelt</code>; paid keys available. Vonage/Twilio require credentials.
  </div>
</div></div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

<script>
// show/hide provider sections
(function(){
  const sel = document.getElementById('sms_provider');
  const blocks = {
    textbelt: document.getElementById('prov_textbelt'),
    vonage:   document.getElementById('prov_vonage'),
    twilio:   document.getElementById('prov_twilio'),
    devlog:   null
  };
  function refresh(){
    const v = sel.value;
    Object.keys(blocks).forEach(k=>{
      const el = blocks[k];
      if (!el) return;
      el.style.display = (v===k) ? 'block' : 'none';
    });
  }
  sel.addEventListener('change', refresh);
  refresh();
})();
</script>
</main>