<?php
require_once '../functions.php';

// Redirect if already logged in as admin
if (isAdminLoggedIn()) {
    header('Location: dashboard.php');
    exit();
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        $error = 'Please enter both username and password.';
    } else {
        $db = getDB();
        // FIX 1: Changed 'status = 1' to 'is_active = 1' to match flexiaccess.sql
        $stmt = $db->prepare("SELECT * FROM admin_users WHERE username = ? AND is_active = 1");
        $stmt->bind_param('s', $username);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($result->num_rows === 1) {
            $admin = $result->fetch_assoc();
            
            if (verifyPassword($password, $admin['password'])) {
                // FIX 2: Changed 'login_ip' to 'last_login_ip' to match flexiaccess.sql
                $stmt = $db->prepare("UPDATE admin_users SET last_login = NOW(), last_login_ip = ? WHERE id = ?");
                $ip = $_SERVER['REMOTE_ADDR'];
                $stmt->bind_param('si', $ip, $admin['id']);
                $stmt->execute();
                
                logLogin($admin['id'], 'admin', 'success');
                
                // Set session
                $_SESSION['admin_id'] = $admin['id'];
                $_SESSION['user_type'] = 'admin';
                $_SESSION['admin_username'] = $admin['username'];
                $_SESSION['admin_role'] = $admin['role'];
                // FIX 3: Changed $admin['full_name'] to combine first_name and last_name 
                $_SESSION['admin_name'] = trim($admin['first_name'] . ' ' . $admin['last_name']);
                
                header('Location: dashboard.php');
                exit();
            } else {
                $error = 'Invalid username or password.';
            }
        } else {
            $error = 'Invalid username or password.';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        .admin-login-card {
            background: var(--white);
            border-radius: var(--border-radius-lg);
            padding: 48px;
            box-shadow: var(--shadow-xl);
            max-width: 420px;
            width: 100%;
        }
    </style>
</head>
<body class="login-page">
    <div class="login-container" style="max-width: 420px;">
        <div class="admin-login-card">
            <div class="login-logo">
                <img src="../assets/images/logo.png" alt="<?php echo SITE_NAME; ?>">
                <h1>Admin Portal</h1>
                <p><?php echo SITE_NAME; ?> Management Console</p>
            </div>
            
            <?php if ($error): ?>
                <div class="alert alert-danger" style="margin-bottom: 20px;">
                    <span>⚠</span> <?php echo e($error); ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="form-group">
                    <label class="form-label">Username</label>
                    <input type="text" name="username" class="form-control" placeholder="Enter admin username" required autofocus>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Password</label>
                    <div style="position: relative;">
                        <input type="password" name="password" id="admin-password" class="form-control" placeholder="Enter password" required>
                        <button type="button" onclick="togglePassword('admin-password', this)" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: var(--gray);">👁️‍🗨️</button>
                    </div>
                </div>
                
                <button type="submit" class="btn btn-primary btn-block" style="padding: 14px;">
                    Sign In to Admin
                </button>
            </form>
            
            <div style="text-align: center; margin-top: 24px;">
                <a href="../index.php" style="font-size: 13px; color: var(--gray);">
                    ← Client Login
                </a>
            </div>
        </div>
        
        <p style="text-align: center; margin-top: 20px; font-size: 12px; color: rgba(255,255,255,0.5);">
            &copy; <?php echo date('Y'); ?> <?php echo SITE_NAME; ?>. All rights reserved.
        </p>
    </div>
    
    <script src="../assets/js/main.js"></script>
</body>
</html>