<?php
// POST /api/auth/send_otp.php
require_once __DIR__ . '/../init.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') Response::error('Method not allowed.', 405);

$ip   = clientIp();
$body = getBody();

$identifier = trim($body['identifier'] ?? '');
$purpose    = $body['purpose'] ?? 'login';  // login | register | verify

if (!$identifier) Response::error('Email or phone number is required.');

$allowed = ['login', 'register', 'verify', 'reset'];
if (!in_array($purpose, $allowed, true)) Response::error('Invalid OTP purpose.');

// ─── Rate limit ───────────────────────────────────────────
if (!RateLimit::check($ip, RL_OTP_MAX, RL_OTP_WINDOW)) {
    Response::error('Too many OTP requests. Please wait 10 minutes.', 429);
}

$db = DB::conn();

// ─── Verify user exists (for non-register purposes) ───────
if ($purpose !== 'register') {
    $stmt = $db->prepare('SELECT id FROM users WHERE email = ? OR phone = ? LIMIT 1');
    $stmt->execute([$identifier, $identifier]);
    if (!$stmt->fetch()) {
        Response::error('No account found for this email or phone.', 404);
    }
}

// ─── Invalidate existing OTPs ────────────────────────────
$stmt = $db->prepare(
    'UPDATE otp_codes SET is_used = 1 WHERE identifier = ? AND purpose = ? AND is_used = 0'
);
$stmt->execute([$identifier, $purpose]);

// ─── Generate new OTP ─────────────────────────────────────
$code      = generateOTP();
$expiresAt = date('Y-m-d H:i:s', time() + OTP_TTL_MINS * 60);
$stmt      = $db->prepare(
    'INSERT INTO otp_codes (identifier, code, purpose, expires_at) VALUES (?, ?, ?, ?)'
);
$stmt->execute([$identifier, $code, $purpose, $expiresAt]);

error_log("📱 [OTP:{$purpose}] {$identifier} => {$code}");

Response::success("OTP sent to {$identifier}. Valid for " . OTP_TTL_MINS . " minutes.", [
    'otp_hint' => APP_ENV === 'development' ? $code : null,
]);
