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

$action = cleanInput($_POST['action'] ?? '');
$username = cleanInput($_POST['username'] ?? '');

if ($username === '') {
    jsonOut(false, 'Username is required');
}

try {
    $stmt = $pdo->prepare("SELECT id, phone FROM adminuser WHERE username = ? AND isactive = 1 AND isdeleted = 0");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if (!$user) {
        // Do not reveal whether username exists
        jsonOut(true, 'If the username exists, an OTP has been sent');
    }

    if ($action === 'sendotp') {
        $otp = generateOtp($pdo, $username, 'forgotpassword');
        sendOtpSms($pdo, $user['phone'], $otp);
        jsonOut(true, 'OTP sent to registered mobile number');
    }

    if ($action === 'reset') {
        $otp = cleanInput($_POST['otp'] ?? '');
        $newpassword = cleanInput($_POST['newpassword'] ?? '');

        if ($otp === '' || $newpassword === '') {
            jsonOut(false, 'OTP and new password are required');
        }
        if (strlen($newpassword) < 6) {
            jsonOut(false, 'Password must be at least 6 characters');
        }
        if (!verifyOtp($pdo, $username, 'forgotpassword', $otp)) {
            jsonOut(false, 'Invalid or expired OTP');
        }

        $upd = $pdo->prepare("UPDATE adminuser SET password = ? WHERE id = ?");
        $upd->execute([hashPassword($newpassword), $user['id']]);

        logActivity($pdo, 'adminuser', $user['id'], 'passwordreset', 'admin', $user['id'], 'Password reset via forgot-password');

        jsonOut(true, 'Password reset successful. Please login.');
    }

    jsonOut(false, 'Invalid action');
} catch (Exception $e) {
    logDebug('[ajax_admin_forgotpassword] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
