<?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'] ?? '');
$newPassword = trim($data['new_password'] ?? '');

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

try {
    $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);

    // 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()) {
            $pdo->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([$hashedPassword, $user['id']]);
            $pdo->prepare("DELETE FROM password_resets WHERE user_id = ?")->execute([$user['id']]);
            echo json_encode(['success' => true, 'message' => 'Password reset successful.']);
            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()) {
            $pdo->prepare("UPDATE admins SET password = ? WHERE id = ?")->execute([$hashedPassword, $admin['id']]);
            $pdo->prepare("DELETE FROM admin_password_resets WHERE admin_id = ?")->execute([$admin['id']]);
            echo json_encode(['success' => true, 'message' => 'Password reset successful.']);
            exit;
        }
    }

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

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