<?php
require '../db.php';
require '../functions.php';

header('Content-Type: application/json');

$phone = cleanInput($_POST['phone'] ?? '');
$purpose = cleanInput($_POST['purpose'] ?? 'register'); // register or login

if ($phone === '' || !preg_match('/^[0-9]{10}$/', $phone)) {
    jsonOut(false, 'A valid 10-digit phone number is required');
}
if (!in_array($purpose, ['register', 'login'], true)) {
    jsonOut(false, 'Invalid purpose');
}

try {
    $stmt = $pdo->prepare("SELECT id FROM villager WHERE phone = ? AND isdeleted = 0");
    $stmt->execute([$phone]);
    $existing = $stmt->fetch();

    if ($purpose === 'login' && !$existing) {
        jsonOut(false, 'No registration found for this phone number. Please register first.');
    }

    $otp = generateOtp($pdo, $phone, $purpose);
    sendOtpSms($pdo, $phone, $otp);

    jsonOut(true, 'OTP sent successfully');
} catch (Exception $e) {
    logDebug('[api_sendotp] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
