<?php
session_start();

$usersFile = 'C:/inetpub/Authentication/OldiesAndMore/users.json';
$tempUser = 'admin';
$tempPass = 'admin123';
$error = '';

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 = 'view';
    $permissions = '';

    if (file_exists($usersFile)) {
        $users = json_decode(file_get_contents($usersFile), true);
        if (is_array($users) && isset($users[$username])) {
            $stored = $users[$username]['password'] ?? '';
            if ((is_string($stored) && $stored !== '' && password_verify($password, $stored)) || $password === $stored) {
                $loginSuccess = true;
                $role = $users[$username]['role'] ?? 'view';
                $permissions = $users[$username]['permissions'] ?? '';

                if ($password === $stored && $stored !== '') {
                    $users[$username]['password'] = password_hash($password, PASSWORD_DEFAULT);
                    @file_put_contents($usersFile, json_encode($users, JSON_PRETTY_PRINT));
                }
            }
        }
    } else {
        if ($username === $tempUser && $password === $tempPass) {
            $loginSuccess = true;
            $role = 'admin';
            $permissions = 'all';
        }
    }

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

    if ($loginSuccess) {
        $_SESSION['user'] = $username;
        $_SESSION['role'] = $role;
        $_SESSION['permissions'] = $permissions;
        $_SESSION['is_admin'] = ($role === 'admin');
        $_SESSION['last_activity'] = time();
        session_regenerate_id(true);
        header('Location: index.php');
        exit;
    }

    $error = file_exists($usersFile) ? 'Invalid username or password.' : 'Invalid temporary login.';
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Admin Login</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../css/site.css">
    <link rel="stylesheet" href="../css/sidebar.css">
    <link rel="stylesheet" href="assets/css/panel.css">
    <style>
        body.admin-login .main-wrap{margin-left:0;min-height:100vh;padding:20px;display:flex;align-items:center;justify-content:center;}
        body.admin-login .content-panel{width:min(100%,520px);padding:28px;}
        body.admin-login .content-box{width:100%;box-sizing:border-box;}
        body.admin-login form{display:block;width:100%;}
        body.admin-login .button, body.admin-login .input-field{width:100%;box-sizing:border-box;}
        @media (max-width: 700px){body.admin-login .content-panel{padding:20px;}}
    </style>
</head>
<body class="admin-login">
<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"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div>
            <?php endif; ?>

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

            <?php if (!file_exists($usersFile)): ?>
                <div class="msg" style="margin-bottom:15px;">Temporary test login active: <strong><?= htmlspecialchars($tempUser, ENT_QUOTES, 'UTF-8') ?></strong> / <strong><?= htmlspecialchars($tempPass, ENT_QUOTES, 'UTF-8') ?></strong></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>
