<?php
/**
 * Admin Login Page - Fixed Version
 */

$error = '';
$success = '';

// Check if config exists
$configFile = dirname(__DIR__) . '/config/config.php';
if (!file_exists($configFile)) {
    $error = 'Configuration file not found. Please run install.php first.';
} else {
    require_once $configFile;
    
    // Installation check removed
    
    // Load database
    try {
        require_once dirname(__DIR__) . '/config/database.php';
        require_once dirname(__DIR__) . '/includes/functions.php';
        require_once dirname(__DIR__) . '/includes/Auth.php';
        
        // Check if already logged in
        if (isset($_SESSION['user_type']) && $_SESSION['user_type'] === 'admin') {
            header('Location: dashboard.php');
            exit;
        }
        
        // Handle login
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            
            if (empty($username) || empty($password)) {
                $error = 'Please enter username and password.';
            } else {
                // Direct database query for login
                try {
                    $stmt = db()->prepare("SELECT * FROM admin_users WHERE username = ? OR email = ?");
                    $stmt->execute([$username, $username]);
                    $admin = $stmt->fetch(PDO::FETCH_ASSOC);
                    
                    if (!$admin) {
                        $error = 'Invalid username or email.';
                    } elseif ($admin['status'] !== 'active') {
                        $error = 'Your account is not active.';
                    } elseif (!password_verify($password, $admin['password'])) {
                        $error = 'Invalid password.';
                    } else {
                        // Login successful
                        $_SESSION['user_id'] = $admin['id'];
                        $_SESSION['user_type'] = 'admin';
                        $_SESSION['admin_role'] = $admin['role'];
                        $_SESSION['admin_name'] = $admin['full_name'];
                        
                        // Update last login
                        $updateStmt = db()->prepare("UPDATE admin_users SET last_login = NOW() WHERE id = ?");
                        $updateStmt->execute([$admin['id']]);
                        
                        header('Location: dashboard.php');
                        exit;
                    }
                } catch (PDOException $e) {
                    $error = 'Database error: ' . $e->getMessage();
                }
            }
        }
    } catch (Exception $e) {
        $error = 'System error: ' . $e->getMessage();
    }
}

$appName = defined('APP_NAME') ? APP_NAME : 'Binary Options';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login - <?= htmlspecialchars($appName) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --bg: #0a0e17;
            --card: #151c28;
            --border: #1f2937;
            --green: #00d09c;
            --red: #ff5252;
            --blue: #3b82f6;
            --text: #ffffff;
            --muted: #6b7280;
        }
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Inter', sans-serif;
            background: var(--bg);
            color: var(--text);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 1rem;
        }
        .container {
            width: 100%;
            max-width: 420px;
        }
        .header {
            text-align: center;
            margin-bottom: 2rem;
        }
        .logo {
            width: 64px;
            height: 64px;
            background: linear-gradient(135deg, var(--green), #00b386);
            border-radius: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.75rem;
            margin: 0 auto 1rem;
        }
        .title {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        .subtitle {
            color: var(--muted);
            font-size: 0.9rem;
        }
        .card {
            background: var(--card);
            border: 1px solid var(--border);
            border-radius: 16px;
            padding: 2rem;
        }
        .alert {
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
        }
        .alert-danger {
            background: rgba(255, 82, 82, 0.1);
            border: 1px solid var(--red);
            color: var(--red);
        }
        .alert-success {
            background: rgba(0, 208, 156, 0.1);
            border: 1px solid var(--green);
            color: var(--green);
        }
        .form-group {
            margin-bottom: 1.5rem;
        }
        .form-label {
            display: block;
            margin-bottom: 0.5rem;
            font-size: 0.875rem;
            font-weight: 500;
        }
        .input-wrap {
            position: relative;
        }
        .input-wrap i {
            position: absolute;
            left: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: var(--muted);
        }
        .form-control {
            width: 100%;
            padding: 0.875rem 1rem 0.875rem 2.75rem;
            background: var(--bg);
            border: 1px solid var(--border);
            border-radius: 8px;
            color: var(--text);
            font-size: 1rem;
            transition: border-color 0.2s;
        }
        .form-control:focus {
            outline: none;
            border-color: var(--green);
        }
        .form-control::placeholder {
            color: var(--muted);
        }
        .toggle-pass {
            position: absolute;
            right: 1rem;
            top: 50%;
            transform: translateY(-50%);
            color: var(--muted);
            cursor: pointer;
            background: none;
            border: none;
        }
        .toggle-pass:hover {
            color: var(--green);
        }
        .btn {
            width: 100%;
            padding: 1rem;
            background: var(--green);
            border: none;
            border-radius: 8px;
            color: #000;
            font-size: 1rem;
            font-weight: 600;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0, 208, 156, 0.3);
        }
        .footer {
            text-align: center;
            margin-top: 1.5rem;
            padding-top: 1.5rem;
            border-top: 1px solid var(--border);
            color: var(--muted);
            font-size: 0.875rem;
        }
        .footer a {
            color: var(--green);
            text-decoration: none;
        }
        .back-link {
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            color: var(--muted);
            text-decoration: none;
            font-size: 0.875rem;
            margin-top: 1.5rem;
        }
        .back-link:hover {
            color: var(--green);
        }
        .reset-link {
            display: block;
            text-align: center;
            margin-top: 1rem;
            color: var(--blue);
            text-decoration: none;
            font-size: 0.85rem;
        }
        .reset-link:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="logo">
                <i class="fas fa-chart-line" style="color: #fff"></i>
            </div>
            <h1 class="title"><?= htmlspecialchars($appName) ?></h1>
            <p class="subtitle">Admin Control Panel</p>
        </div>
        
        <div class="card">
            <?php if ($error): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-circle"></i>
                    <span><?= htmlspecialchars($error) ?></span>
                </div>
            <?php endif; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    <span><?= htmlspecialchars($success) ?></span>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="form-group">
                    <label class="form-label">Username or Email</label>
                    <div class="input-wrap">
                        <i class="fas fa-user"></i>
                        <input type="text" name="username" class="form-control" 
                               placeholder="Enter username or email" required
                               value="<?= htmlspecialchars($_POST['username'] ?? '') ?>">
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Password</label>
                    <div class="input-wrap">
                        <i class="fas fa-lock"></i>
                        <input type="password" name="password" id="password" class="form-control" 
                               placeholder="Enter password" required>
                        <button type="button" class="toggle-pass" onclick="togglePassword()">
                            <i class="fas fa-eye" id="toggleIcon"></i>
                        </button>
                    </div>
                </div>
                
                <button type="submit" class="btn">
                    <i class="fas fa-sign-in-alt"></i>
                    Sign In
                </button>
            </form>
            
            <a href="../reset-admin.php" class="reset-link">
                <i class="fas fa-key"></i> Reset Admin Password
            </a>
            
            <div class="footer">
                <p>Use <a href="../reset-admin.php">reset-admin.php</a> to create/reset admin</p>
            </div>
        </div>
        
        <div style="text-align: center">
            <a href="../" class="back-link">
                <i class="fas fa-arrow-left"></i>
                Back to Website
            </a>
        </div>
    </div>
    
    <script>
        function togglePassword() {
            const input = document.getElementById('password');
            const icon = document.getElementById('toggleIcon');
            if (input.type === 'password') {
                input.type = 'text';
                icon.classList.replace('fa-eye', 'fa-eye-slash');
            } else {
                input.type = 'password';
                icon.classList.replace('fa-eye-slash', 'fa-eye');
            }
        }
    </script>
</body>
</html>
