<?php
require_once '../includes/config.php';

if (isAdmin()) {
    header('Location: ' . SITE_URL . '/admin/'); exit;
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitize($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $remember = isset($_POST['remember']);

    if ($username && $password) {
        $db = getDB();
        try { $db->exec("ALTER TABLE users ADD COLUMN remember_token VARCHAR(64) DEFAULT NULL"); } catch(Exception $e) {}
        $stmt = $db->prepare("SELECT * FROM users WHERE (username=? OR email=?) AND status='active' AND role='admin'");
        $stmt->execute([$username,$username]);
        $user = $stmt->fetch();

        if ($user && password_verify($password, $user['password'])) {
            $_SESSION['user_id']       = $user['id'];
            $_SESSION['role']          = $user['role'];
            $_SESSION['name']          = $user['name'];
            $_SESSION['last_activity'] = time();

            if ($remember) {
                $token = bin2hex(random_bytes(32));
                $db->prepare("UPDATE users SET remember_token=? WHERE id=?")->execute([$token,$user['id']]);
                setcookie('remember_token', $token, time()+86400*30, '/', '', true, true);
            }
            header('Location: ' . SITE_URL . '/admin/'); exit;
        } else {
            $error = 'Invalid admin credentials!';
            // Log failed attempt
            error_log("Admin login failed for: $username from ".$_SERVER['REMOTE_ADDR']);
        }
    } else {
        $error = 'Please fill all fields!';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Admin Login - <?= SITE_NAME ?></title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:'Segoe UI',sans-serif;background:linear-gradient(135deg,#0d1f4e 0%,#1a1a2e 50%,#16213e 100%);min-height:100vh;display:flex;align-items:center;justify-content:center;padding:20px}
.card{background:white;border-radius:24px;padding:36px 30px;width:100%;max-width:380px;box-shadow:0 25px 60px rgba(0,0,0,0.4)}
.logo{text-align:center;margin-bottom:28px}
.logo-icon{width:70px;height:70px;background:linear-gradient(135deg,#1a1a2e,#0d1f4e);border-radius:20px;display:flex;align-items:center;justify-content:center;margin:0 auto 14px;font-size:26px}
.logo h1{font-size:22px;font-weight:800;color:#0d1f4e}
.logo h1 span{color:#e53e3e}
.logo p{font-size:12px;color:#888;margin-top:4px;display:flex;align-items:center;justify-content:center;gap:6px}
.admin-badge{background:#fff5f5;color:#c53030;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:700;border:1px solid #fed7d7}
.alert-err{background:#fff5f5;color:#c53030;border:1px solid #fed7d7;padding:11px 14px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:16px;display:flex;align-items:center;gap:8px}
.fg{margin-bottom:14px}
.fg label{font-size:12px;font-weight:700;color:#555;text-transform:uppercase;letter-spacing:0.4px;display:block;margin-bottom:6px}
.inp-wrap{position:relative}
.inp-wrap i.prefix{position:absolute;left:14px;top:50%;transform:translateY(-50%);color:#aaa;font-size:14px}
.inp-wrap input{width:100%;padding:13px 13px 13px 42px;border:2px solid #e8ecf4;border-radius:12px;font-size:15px;outline:none;transition:0.2s}
.inp-wrap input:focus{border-color:#0d1f4e;box-shadow:0 0 0 3px rgba(13,31,78,0.1)}
.toggle-pw{position:absolute;right:14px;top:50%;transform:translateY(-50%);color:#aaa;cursor:pointer;font-size:14px;border:none;background:none}
.remember-row{display:flex;align-items:center;justify-content:space-between;margin-bottom:18px}
.remember-row label{display:flex;align-items:center;gap:8px;font-size:13px;color:#555;cursor:pointer;font-weight:600}
.remember-row input[type=checkbox]{width:17px;height:17px;cursor:pointer;accent-color:#0d1f4e}
.submit-btn{width:100%;padding:14px;background:linear-gradient(135deg,#0d1f4e,#1a3c8f);color:white;border:none;border-radius:12px;font-size:15px;font-weight:700;cursor:pointer;transition:0.2s;display:flex;align-items:center;justify-content:center;gap:8px}
.submit-btn:hover{opacity:0.95}
.user-link{text-align:center;margin-top:20px;font-size:13px;color:#aaa}
.user-link a{color:#0d1f4e;font-weight:700;text-decoration:none}
.security-note{background:#f8fafc;border-radius:10px;padding:10px 12px;font-size:11px;color:#888;text-align:center;margin-top:16px;display:flex;align-items:center;justify-content:center;gap:6px}
</style>
</head>
<body>
<div class="card">
    <div class="logo">
        <div class="logo-icon">🔐</div>
        <h1>Admin <span>Panel</span></h1>
        <p><span class="admin-badge">🛡️ Admin Only</span></p>
    </div>

    <?php if($error): ?>
    <div class="alert-err"><i class="fas fa-shield-alt"></i> <?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <form method="POST">
        <div class="fg">
            <label>Admin Username</label>
            <div class="inp-wrap">
                <i class="fas fa-user-shield prefix"></i>
                <input type="text" name="username" placeholder="Admin username" required autofocus value="<?= htmlspecialchars($_POST['username']??'') ?>">
            </div>
        </div>
        <div class="fg">
            <label>Password</label>
            <div class="inp-wrap">
                <i class="fas fa-lock prefix"></i>
                <input type="password" name="password" id="pwInput" placeholder="Admin password" required>
                <button type="button" class="toggle-pw" onclick="togglePw()"><i class="fas fa-eye" id="eyeIcon"></i></button>
            </div>
        </div>
        <div class="remember-row">
            <label>
                <input type="checkbox" name="remember" <?= isset($_POST['remember'])?'checked':'' ?>>
                Stay signed in (30 days)
            </label>
        </div>
        <button type="submit" class="submit-btn">
            <i class="fas fa-sign-in-alt"></i> Admin Sign In
        </button>
    </form>

    <div class="user-link">
        Not admin? <a href="../login.php">← User Login</a>
    </div>
    <div class="security-note">
        <i class="fas fa-shield-alt"></i> Admin access only — unauthorized attempts are logged
    </div>
</div>
<script>
function togglePw() {
    const inp = document.getElementById('pwInput');
    const ico = document.getElementById('eyeIcon');
    if (inp.type === 'password') { inp.type='text'; ico.className='fas fa-eye-slash'; }
    else { inp.type='password'; ico.className='fas fa-eye'; }
}
</script>
</body>
</html>
