<?php
require_once __DIR__ . '/../config/cors.php';
require_once __DIR__ . '/../config/db.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method Not Allowed']);
    exit;
}

$json = file_get_contents('php://input');
$data = json_decode($json, true);

$identity = trim($data['nroi_id'] ?? '');
$otp = trim($data['otp'] ?? '');

if (empty($identity) || empty($otp)) {
    echo json_encode(['success' => false, 'message' => 'Identity and OTP are required.']);
    exit;
}

try {
    // 1. Try finding in Regular Users
    $stmtUser = $pdo->prepare("SELECT id FROM users WHERE nroi_id = ?");
    $stmtUser->execute([$identity]);
    $user = $stmtUser->fetch();

    if ($user) {
        $stmtOtp = $pdo->prepare("SELECT * FROM password_resets WHERE user_id = ? AND otp = ? AND expires_at > NOW()");
        $stmtOtp->execute([$user['id'], $otp]);
        if ($stmtOtp->fetch()) {
            echo json_encode(['success' => true, 'message' => 'OTP verified successfully.', 'user_type' => 'regular']);
            exit;
        }
    }

    // 2. Try finding in Admins
    $stmtAdmin = $pdo->prepare("SELECT id FROM admins WHERE username = ?");
    $stmtAdmin->execute([$identity]);
    $admin = $stmtAdmin->fetch();

    if ($admin) {
        $stmtOtp = $pdo->prepare("SELECT * FROM admin_password_resets WHERE admin_id = ? AND otp = ? AND expires_at > NOW()");
        $stmtOtp->execute([$admin['id'], $otp]);
        if ($stmtOtp->fetch()) {
            echo json_encode(['success' => true, 'message' => 'OTP verified successfully.', 'user_type' => 'admin']);
            exit;
        }
    }

    echo json_encode(['success' => false, 'message' => 'Invalid or expired OTP.']);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>