<?php
session_start();

/* ============================================================
   SECURE PATH — JSON IN AUTHENTICATION DIRECTORY
   ============================================================ */
$usersFile = "C:/inetpub/Authentication/OldiesAndMore/users.json";

/* ============================================================
   TEMP FALLBACK LOGIN FOR TEST SERVER
   Remove this once external auth is live.
   ============================================================ */
$tempUser = 'admin';
$tempPass = 'temp123';

$error = "";

// If already logged in, go straight to admin
if (isset($_SESSION['user'])) {
    header("Location: index.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $loginSuccess = false;
    $role = 'admin';
    $permissions = 'all';

    if (file_exists($usersFile)) {
        $users = json_decode(file_get_contents($usersFile), true);

        if (is_array($users) && isset($users[$username])) {
            $stored = $users[$username]['password'] ?? '';

            // If stored password is already hashed
            if ($stored !== '' && password_verify($password, $stored)) {
                $loginSuccess = true;

            // If stored password is still plain text (first login)
            } elseif ($stored !== '' && hash_equals((string)$stored, $password)) {
                $loginSuccess = true;

                // Auto-upgrade to hashed password when possible
                $users[$username]['password'] = password_hash($password, PASSWORD_DEFAULT);
                @file_put_contents($usersFile, json_encode($users, JSON_PRETTY_PRINT));
            }

            if ($loginSuccess) {
                $role = $users[$username]['role'] ?? 'view';
                $permissions = $users[$username]['permissions'] ?? '';
            }
        }
    }

    // Fallback temp login for local/test builds
    if (!$loginSuccess && hash_equals($tempUser, $username) && hash_equals($tempPass, $password)) {
        $loginSuccess = true;
        $role = 'admin';
        $permissions = 'all';
    }

    if ($loginSuccess) {
        // MASTERDEV OVERRIDE
        if ($username === 'MasterDev') {
            $role = 'admin';
            $permissions = 'all';
        }

        $_SESSION['user'] = $username;
        $_SESSION['role'] = $role;
        $_SESSION['permissions'] = $permissions;
        $_SESSION['last_activity'] = time();

        session_regenerate_id(true);

        header("Location: index.php");
        exit;
    }

    $error = "Invalid username or password.";
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Admin Login</title>

    <link rel="stylesheet" href="/css/site.css">
    <link rel="stylesheet" href="/css/sidebar.css">
    <link rel="stylesheet" href="/admin/assets/css/panel.css">
</head>
<body>

<div class="main-wrap">
    <div class="content-panel">
        <div class="content-box center-text">

            <h1 class="section-title">🔐 Admin Login</h1>

            <?php if ($error): ?>
                <div class="msg error"><?= $error ?></div>
            <?php endif; ?>

            <?php if (isset($_GET['timeout'])): ?>
                <div class="msg error">Session expired. Please log in again.</div>
            <?php endif; ?>

            <form method="POST">
                <label>Username:</label>
                <input type="text" name="username" class="input-field" required>

                <label>Password:</label>
                <input type="password" name="password" class="input-field" required>

                <button type="submit" class="button" style="margin-top:20px;">Login</button>
            </form>

        </div>
    </div>
</div>

</body>
</html>
