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

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

$phone = cleanInput($_POST['phone'] ?? '');
$otp = cleanInput($_POST['otp'] ?? '');
$purpose = cleanInput($_POST['purpose'] ?? 'register');

if ($phone === '' || $otp === '') {
    jsonOut(false, 'Phone and OTP are required');
}

try {
    if (!verifyOtp($pdo, $phone, $purpose, $otp)) {
        jsonOut(false, 'Invalid or expired OTP');
    }

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

    if (!$villager) {
        // First time - create a minimal stub row; api_register.php fills in name/photo next
        $ins = $pdo->prepare("INSERT INTO villager (fullname, phone, status, paymentstatus) VALUES ('', ?, 'pending', 'unpaid')");
        $ins->execute([$phone]);
        $villagerid = $pdo->lastInsertId();
        $stmt = $pdo->prepare("SELECT * FROM villager WHERE id = ?");
        $stmt->execute([$villagerid]);
        $villager = $stmt->fetch();
    }

    $token = villagerIssueToken($pdo, $villager['id']);
    logActivity($pdo, 'villager', $villager['id'], 'otpverified', 'villager', $villager['id'], 'OTP verified for ' . $purpose);

    jsonOut(true, 'OTP verified successfully', [
        'apitoken' => $token,
        'villagerid' => (int)$villager['id'],
        'progress' => villagerProgress($villager),
    ]);
} catch (Exception $e) {
    logDebug('[api_verifyotp] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
