<?php
/**
 * User Login Page
 * PHP User Registration - https://rskworld.in
 * Developer: Molla Samser | RSK World
 * Contact: help@rskworld.in | +91 93305 39277
 * Year: 2026
 */

require_once __DIR__ . '/includes/init.php';
require_once __DIR__ . '/includes/functions.php';

ensureDemoUser();

if (isLoggedIn()) {
    header('Location: dashboard.php');
    exit;
}

$errors = [];
$success = getFlash('success');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = filter_var(trim($_POST['email'] ?? ''), FILTER_SANITIZE_EMAIL);
    $password = $_POST['password'] ?? '';

    if (!filter_var($email, FILTER_VALIDATE_EMAIL) || empty($password)) {
        $errors[] = 'Please enter a valid email and password.';
    } else {
        $pdo = getDbConnection();
        $stmt = $pdo->prepare('SELECT id, name, email, password, email_verified FROM users WHERE email = ?');
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        if ($user && password_verify($password, $user['password'])) {
            try {
                $s = $pdo->prepare('SELECT suspended FROM users WHERE id = ?');
                $s->execute([$user['id']]);
                $r = $s->fetch();
                if ($r && !empty($r['suspended'])) {
                    $errors[] = 'This account has been suspended. Contact support.';
                    $user = null;
                }
            } catch (PDOException $e) { /* column may not exist */ }
            if ($user) {
                $_SESSION['user_id'] = (int) $user['id'];
                $_SESSION['user_name'] = $user['name'];
                $_SESSION['user_email'] = $user['email'];
                $_SESSION['email_verified'] = (bool) $user['email_verified'];
                $remember = !empty($_POST['remember']);
                if ($remember) {
                    $params = session_get_cookie_params();
                    setcookie(session_name(), session_id(), time() + 30 * 86400, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
                }
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? '';
                if (strpos($ip, ',') !== false) $ip = trim(explode(',', $ip)[0]);
                try {
                    $up = $pdo->prepare('UPDATE users SET last_login_at = NOW(), last_login_ip = ? WHERE id = ?');
                    $up->execute([$ip ?: null, $user['id']]);
                } catch (PDOException $e) {
                    try { $pdo->prepare('UPDATE users SET last_login_at = NOW() WHERE id = ?')->execute([$user['id']]); } catch (PDOException $e2) {}
                }
                $goto = 'dashboard.php';
            $redirectParam = trim($_POST['redirect'] ?? $_GET['redirect'] ?? '');
            if ($redirectParam !== '' && strpos($redirectParam, '://') === false && strpos($redirectParam, '//') !== 0) {
                $goto = $redirectParam;
            }
                header('Location: ' . $goto);
                exit;
            }
        }
        if (empty($errors)) {
            $errors[] = 'Invalid email or password.';
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'] ?? null;
            if (strpos((string) $ip, ',') !== false) $ip = trim(explode(',', (string) $ip)[0]);
            logFailedLogin($email, $ip);
        }
    }
}

$pageTitle = 'Login';
require_once __DIR__ . '/includes/header.php';
?>

<div class="auth-card">
    <h1><i class="fas fa-sign-in-alt"></i> Log In</h1>
    <p class="subtitle">PHP User Registration — <a href="https://rskworld.in" target="_blank">rskworld.in</a></p>

    <?php
    require_once __DIR__ . '/config/demo.php';
    $demoIds = getDemoUserIds();
    ?>
    <div class="demo-credentials">
        <strong><i class="fas fa-user"></i> Demo User</strong>
        <p class="demo-row"><span>User ID:</span> <code><?= $demoIds['demo'] ?? '—' ?></code></p>
        <p class="demo-row"><span>Email:</span> <code><?= htmlspecialchars(DEMO_EMAIL) ?></code></p>
        <p class="demo-row"><span>Password:</span> <code><?= htmlspecialchars(DEMO_PASSWORD) ?></code></p>
        <button type="button" class="btn btn-demo btn-demo-user" title="Log in as demo user">Use demo user</button>
    </div>
    <div class="demo-credentials demo-admin-box">
        <strong><i class="fas fa-user-shield"></i> Demo Admin</strong>
        <p class="demo-row"><span>User ID:</span> <code><?= $demoIds['admin'] ?? '—' ?></code></p>
        <p class="demo-row"><span>Email:</span> <code><?= htmlspecialchars(DEMO_ADMIN_EMAIL) ?></code></p>
        <p class="demo-row"><span>Password:</span> <code><?= htmlspecialchars(DEMO_ADMIN_PASSWORD) ?></code></p>
        <button type="button" class="btn btn-demo btn-demo-admin" title="Log in as demo admin">Use demo admin</button>
    </div>
    <div class="demo-credentials demo-superadmin-box">
        <strong><i class="fas fa-crown"></i> Demo Super Admin</strong>
        <p class="demo-row"><span>User ID:</span> <code><?= $demoIds['superadmin'] ?? '—' ?></code></p>
        <p class="demo-row"><span>Email:</span> <code><?= htmlspecialchars(DEMO_SUPERADMIN_EMAIL) ?></code></p>
        <p class="demo-row"><span>Password:</span> <code><?= htmlspecialchars(DEMO_SUPERADMIN_PASSWORD) ?></code></p>
        <button type="button" class="btn btn-demo btn-demo-superadmin" title="Log in as demo super admin">Use demo super admin</button>
    </div>

    <?php if ($success): ?>
        <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
    <?php endif; ?>
    <?php if (!empty($errors)): ?>
        <div class="alert alert-error">
            <?php foreach ($errors as $e): ?>
                <div><?= htmlspecialchars($e) ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <form method="post" action="" class="auth-form" id="login-form">
        <input type="hidden" name="redirect" value="<?= htmlspecialchars($_GET['redirect'] ?? '') ?>">
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" id="email" name="email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" required placeholder="you@example.com">
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" id="password" name="password" required placeholder="Your password">
        </div>
        <div class="form-group form-group-inline">
            <label class="checkbox-label">
                <input type="checkbox" name="remember" value="1"> Remember me
            </label>
        </div>
        <button type="submit" class="btn btn-primary">Log In</button>
    </form>
    <script>
        document.querySelector('.btn-demo-user').addEventListener('click', function() {
            var f = document.getElementById('login-form');
            f.querySelector('[name=email]').value = <?= json_encode(DEMO_EMAIL) ?>;
            f.querySelector('[name=password]').value = <?= json_encode(DEMO_PASSWORD) ?>;
            f.submit();
        });
        document.querySelector('.btn-demo-admin').addEventListener('click', function() {
            var f = document.getElementById('login-form');
            f.querySelector('[name=email]').value = <?= json_encode(DEMO_ADMIN_EMAIL) ?>;
            f.querySelector('[name=password]').value = <?= json_encode(DEMO_ADMIN_PASSWORD) ?>;
            f.submit();
        });
        document.querySelector('.btn-demo-superadmin').addEventListener('click', function() {
            var f = document.getElementById('login-form');
            f.querySelector('[name=email]').value = <?= json_encode(DEMO_SUPERADMIN_EMAIL) ?>;
            f.querySelector('[name=password]').value = <?= json_encode(DEMO_SUPERADMIN_PASSWORD) ?>;
            f.submit();
        });
    </script>
    <p class="auth-footer">
        <a href="forgot-password.php">Forgot password?</a><br>
        Don't have an account? <a href="register.php">Register</a>
    </p>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
