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

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

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

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

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

    if (!$villager) {
        jsonOut(false, 'No registration found for this phone number. Please register first.');
    }

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

    $token = villagerIssueToken($pdo, $villager['id']);
    logActivity($pdo, 'villager', $villager['id'], 'login', 'villager', $villager['id'], 'Villager logged in via app');

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