<?php
// /edenrms/ajax/send_verification_sms.php
// Fire-and-forget SMS sender for the latest OTP.

declare(strict_types=1);
@date_default_timezone_set('Asia/Colombo');
header('Content-Type: application/json; charset=utf-8');
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = null;
if (is_file(__DIR__ . '/../includes/auth.php')) {
  require_once __DIR__ . '/../includes/auth.php';
  $db = function_exists('ec_db') ? ec_db() : null;
  if ($db instanceof mysqli) $mysqli = $db;
}
if (!$mysqli) { $mysqli = new mysqli('localhost','root','','edencamp_edencampus'); }
$mysqli->set_charset('utf8mb4');

$student_id = (int)($_POST['student_id'] ?? 0);
if ($student_id <= 0) { echo json_encode(['ok'=>false,'message'=>'bad student']); exit; }

// read student mobile
$mobile = '';
if ($r = $mysqli->query("SELECT mobile FROM studentss WHERE id={$student_id} LIMIT 1")->fetch_assoc()) {
  $mobile = trim((string)($r['mobile'] ?? ''));
}

// read OTP (we don’t store plain; this endpoint is optional)
// In production, you’d pass the OTP from complete_verification.php directly here (session/message bus)
// For now, log a generic SMS.
if (!is_dir(__DIR__.'/../logs')) { @mkdir(__DIR__.'/../logs', 0775, true); }
file_put_contents(__DIR__.'/../logs/sms.log', date('c')." student_id={$student_id} to={$mobile} message=Eden RMS: Your verification code was generated.\n", FILE_APPEND);

// TODO: integrate your SMS gateway here.

echo json_encode(['ok'=>true,'queued'=>true]);
