<?php
session_start();
require_once 'config/db.php';

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = trim($_POST['password'] ?? '');

    $stmt = $pdo->prepare("SELECT * FROM user WHERE username = ? AND user_category = 'Admin' LIMIT 1");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user) {
        $dbPassword = $user['password'] ?? '';

        $valid = false;
        if (password_verify($password, $dbPassword)) {
            $valid = true;
        } elseif ($password === $dbPassword) {
            $valid = true;
        }

        if ($valid) {
            $_SESSION['admin_user'] = [
                'id' => $user['id'] ?? null,
                'username' => $user['username'] ?? '',
                'name' => $user['name'] ?? ($user['username'] ?? 'Admin')
            ];
            header('Location: index.php');
            exit;
        }
    }

    $error = 'Invalid Admin login credentials.';
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>KSP Monitor Login</title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body class="login-body">
    <div class="login-wrapper">
        <div class="login-card">
            <img src="logo/logo_circle1.png" alt="Logo" class="login-logo">
            <h1>KSP Monitor</h1>
            <p class="subtitle">Admin access only</p>

            <?php if ($error): ?>
                <div class="alert-danger"><?php echo htmlspecialchars($error); ?></div>
            <?php endif; ?>

            <form method="POST" class="login-form">
                <input type="text" name="username" placeholder="Username" required>
                <input type="password" name="password" placeholder="Password" required>
                <button type="submit">Login</button>
            </form>
        </div>
    </div>
</body>
</html>