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

$username = cleanInput($_POST['username'] ?? '');
$password = cleanInput($_POST['password'] ?? '');
$redirect = basename($_POST['redirect'] ?? '');

if ($username === '' || $password === '') {
    jsonOut(false, 'Username and password are required');
}

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

    if (!$user || !verifyPassword($password, $user['password'])) {
        jsonOut(false, 'Invalid username or password');
    }

    $_SESSION['userid'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['name'] = $user['name'];
    $_SESSION['role'] = 'rnduser';

    logActivity($pdo, 'rnduser', $user['id'], 'login', 'rnduser', $user['id'], 'RND user logged in');

    jsonOut(true, 'Login successful', ['redirect' => $redirect !== '' ? $redirect : 'rnd_dashboard.php']);
} catch (Exception $e) {
    logDebug('[ajax_rnd_login] ' . $e->getMessage());
    jsonOut(false, 'Something went wrong. Please try again.');
}
