<?php
session_start();

require_once '../includes/database.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';

$database = new Database();
$pdo = $database->getConnection();
$siteManager = new SiteManager($database);
$auth = new MultiTenantAuth($pdo);
$currentSite = $siteManager->getCurrentSite();

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

// If already logged in, redirect to admin
if (isset($_SESSION['admin_session_id'])) {
    header('Location: dashboard-multi.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $loginType = $_POST['login_type'] ?? 'sub_admin';
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($username) || empty($password)) {
        $error = 'Username dan password wajib diisi';
    } else {
        $adminData = false;
        
        if ($loginType === 'master_admin') {
            // Master admin login
            $adminData = $auth->authenticateMasterAdmin($username, $password, $currentSite['id'] ?? null);
        } else {
            // Sub-admin login
            $adminData = $auth->authenticateSubAdmin($username, $password, $currentSite['id'] ?? null);
        }
        
        if ($adminData) {
            // Set session
            $_SESSION['admin_session_id'] = $adminData['session_id'] ?? 'master_session_' . time();
            $_SESSION['admin_data'] = $adminData;
            $_SESSION['login_time'] = time();
            
            // Redirect to admin dashboard
            header('Location: dashboard-multi.php');
            exit;
        } else {
            $error = 'Username atau password salah';
            
            // Log failed attempt
            if ($loginType === 'sub_admin') {
                error_log("Failed sub-admin login attempt: $username from " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
            } else {
                error_log("Failed master admin login attempt: $username from " . ($_SERVER['REMOTE_ADDR'] ?? 'unknown'));
            }
        }
    }
}

// Get site info for branding
$siteName = $currentSite['site_name'] ?? 'Autoprediksi';
$primaryColor = $currentSite['primary_color'] ?? '#25d366';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Login - <?= htmlspecialchars($siteName) ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        :root {
            --primary-color: <?= htmlspecialchars($primaryColor) ?>;
            --primary-rgb: <?= implode(',', sscanf($primaryColor, "#%02x%02x%02x")) ?>;
        }
        
        body {
            background: linear-gradient(135deg, var(--primary-color) 0%, rgba(var(--primary-rgb), 0.8) 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .login-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .login-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            max-width: 450px;
            width: 100%;
        }
        
        .login-header {
            text-align: center;
            padding: 40px 30px 20px;
            border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        }
        
        .login-logo {
            width: 80px;
            height: 80px;
            background: var(--primary-color);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            color: white;
            font-size: 2rem;
        }
        
        .login-body {
            padding: 30px;
        }
        
        .form-control {
            border-radius: 12px;
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.8);
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(var(--primary-rgb), 0.25);
            background: white;
        }
        
        .btn-login {
            background: var(--primary-color);
            border: none;
            border-radius: 12px;
            padding: 12px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            transition: all 0.3s ease;
        }
        
        .btn-login:hover {
            background: rgba(var(--primary-rgb), 0.9);
            transform: translateY(-2px);
            box-shadow: 0 8px 20px rgba(var(--primary-rgb), 0.3);
        }
        
        .login-type-tabs {
            display: flex;
            background: #f8f9fa;
            border-radius: 12px;
            padding: 4px;
            margin-bottom: 25px;
        }
        
        .login-type-tab {
            flex: 1;
            padding: 12px;
            text-align: center;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            border: none;
            background: transparent;
        }
        
        .login-type-tab.active {
            background: var(--primary-color);
            color: white;
            box-shadow: 0 2px 8px rgba(var(--primary-rgb), 0.3);
        }
        
        .alert {
            border-radius: 12px;
            border: none;
        }
        
        .input-group {
            position: relative;
            margin-bottom: 20px;
        }
        
        .input-icon {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            z-index: 5;
        }
        
        .form-control.has-icon {
            padding-left: 48px;
        }
        
        .site-info {
            text-align: center;
            padding: 20px 30px;
            background: rgba(0, 0, 0, 0.05);
            border-radius: 0 0 20px 20px;
            color: #6c757d;
            font-size: 0.9rem;
        }
        
        .password-toggle {
            position: absolute;
            right: 16px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #6c757d;
            z-index: 5;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="login-card">
            <div class="login-header">
                <div class="login-logo">
                    <i class="bi bi-shield-lock"></i>
                </div>
                <h3 class="mb-1">Admin Panel</h3>
                <p class="text-muted mb-0"><?= htmlspecialchars($siteName) ?></p>
            </div>
            
            <div class="login-body">
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        <?= htmlspecialchars($error) ?>
                    </div>
                <?php endif; ?>
                
                <form method="POST" id="loginForm">
                    <div class="login-type-tabs">
                        <button type="button" class="login-type-tab active" data-type="sub_admin">
                            <i class="bi bi-person me-2"></i>Sub Admin
                        </button>
                        <button type="button" class="login-type-tab" data-type="master_admin">
                            <i class="bi bi-crown me-2"></i>Master Admin
                        </button>
                    </div>
                    
                    <input type="hidden" name="login_type" id="loginType" value="sub_admin">
                    
                    <div class="input-group">
                        <i class="bi bi-person input-icon"></i>
                        <input type="text" 
                               class="form-control has-icon" 
                               name="username" 
                               placeholder="Username atau Email" 
                               required 
                               autocomplete="username"
                               id="usernameField">
                    </div>
                    
                    <div class="input-group">
                        <i class="bi bi-lock input-icon"></i>
                        <input type="password" 
                               class="form-control has-icon" 
                               name="password" 
                               placeholder="Password" 
                               required 
                               autocomplete="current-password"
                               id="passwordField">
                        <i class="bi bi-eye password-toggle" id="passwordToggle"></i>
                    </div>
                    
                    <button type="submit" class="btn btn-login btn-primary w-100">
                        <i class="bi bi-box-arrow-in-right me-2"></i>
                        Login
                    </button>
                </form>
                
                <div class="mt-3">
                    <small class="text-muted">
                        <i class="bi bi-info-circle me-1"></i>
                        <span id="loginInfo">
                            Login sebagai Sub Admin untuk mengelola konten situs
                        </span>
                    </small>
                </div>
            </div>
            
            <div class="site-info">
                <i class="bi bi-globe2 me-2"></i>
                <?= htmlspecialchars($currentSite['domain'] ?? $_SERVER['HTTP_HOST']) ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Login type toggle
            const tabs = document.querySelectorAll('.login-type-tab');
            const loginTypeInput = document.getElementById('loginType');
            const usernameField = document.getElementById('usernameField');
            const loginInfo = document.getElementById('loginInfo');
            
            tabs.forEach(tab => {
                tab.addEventListener('click', function() {
                    tabs.forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    
                    const type = this.dataset.type;
                    loginTypeInput.value = type;
                    
                    if (type === 'master_admin') {
                        usernameField.placeholder = 'Master Admin Email';
                        loginInfo.textContent = 'Login sebagai Master Admin untuk mengelola semua fitur';
                    } else {
                        usernameField.placeholder = 'Username Sub Admin';
                        loginInfo.textContent = 'Login sebagai Sub Admin untuk mengelola konten situs';
                    }
                });
            });
            
            // Password toggle
            const passwordField = document.getElementById('passwordField');
            const passwordToggle = document.getElementById('passwordToggle');
            
            passwordToggle.addEventListener('click', function() {
                if (passwordField.type === 'password') {
                    passwordField.type = 'text';
                    this.classList.remove('bi-eye');
                    this.classList.add('bi-eye-slash');
                } else {
                    passwordField.type = 'password';
                    this.classList.remove('bi-eye-slash');
                    this.classList.add('bi-eye');
                }
            });
            
            // Form validation
            const form = document.getElementById('loginForm');
            form.addEventListener('submit', function(e) {
                const username = usernameField.value.trim();
                const password = passwordField.value;
                
                if (!username || !password) {
                    e.preventDefault();
                    alert('Mohon isi username dan password');
                    return false;
                }
                
                // Show loading state
                const submitBtn = form.querySelector('button[type="submit"]');
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>Login...';
                
                return true;
            });
        });
    </script>
</body>
</html>