<?php
define('ADMIN_ACCESS', true);
require_once 'config.php';
require_once '../includes/site-manager.php';
require_once '../includes/multi-tenant-auth.php';
require_once '../includes/integrated-admin-auth.php';

$integratedAuth = new IntegratedAdminAuth();
$siteManager = new SiteManager(new Database());
$currentSite = $siteManager->getCurrentSite();

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

// Check if already logged in
if (isset($_SESSION['integrated_admin_session_id'])) {
    header('Location: dashboard.php');
    exit;
}

// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $loginType = $_POST['login_type'] ?? 'auto';
    
    if (empty($username) || empty($password)) {
        $error = 'Username dan password wajib diisi';
    } else {
        $result = $integratedAuth->login($username, $password, $loginType);
        
        if ($result['success']) {
            // Set integrated session
            $_SESSION['integrated_admin_session_id'] = $result['admin_data']['session_id'];
            $_SESSION['integrated_admin_data'] = $result['admin_data'];
            $_SESSION['integrated_login_time'] = time();
            
            $success = $result['message'];
            
            // Redirect after brief delay to show success message
            echo "<script>setTimeout(function(){ window.location.href = 'dashboard.php'; }, 1500);</script>";
        } else {
            $error = $result['message'];
        }
    }
}

// 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;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .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%;
            overflow: hidden;
        }
        
        .login-header {
            background: linear-gradient(45deg, var(--primary-color), rgba(var(--primary-rgb), 0.9));
            color: white;
            text-align: center;
            padding: 40px 30px 30px;
        }
        
        .login-logo {
            width: 80px;
            height: 80px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 20px;
            font-size: 2rem;
        }
        
        .login-body {
            padding: 40px 30px;
        }
        
        .form-control {
            border-radius: 12px;
            padding: 15px 20px;
            border: 2px solid #e9ecef;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.9);
            margin-bottom: 20px;
        }
        
        .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: 15px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            transition: all 0.3s ease;
            width: 100%;
        }
        
        .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;
            color: #6c757d;
            font-size: 0.85rem;
        }
        
        .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;
            margin-bottom: 25px;
        }
        
        .input-group {
            position: relative;
            margin-bottom: 20px;
        }
        
        .input-icon {
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            z-index: 5;
        }
        
        .form-control.has-icon {
            padding-left: 55px;
        }
        
        .password-toggle {
            position: absolute;
            right: 20px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #6c757d;
            z-index: 5;
        }
        
        .version-info {
            text-align: center;
            padding: 20px;
            background: rgba(0, 0, 0, 0.05);
            color: #6c757d;
            font-size: 0.85rem;
        }
    </style>
</head>
<body>
    <div class="login-card">
        <div class="login-header">
            <div class="login-logo">
                <i class="bi bi-shield-lock"></i>
            </div>
            <h3 class="mb-2">Admin Panel</h3>
            <p class="mb-0 opacity-75"><?= 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; ?>
            
            <?php if ($success): ?>
                <div class="alert alert-success">
                    <i class="bi bi-check-circle me-2"></i>
                    <?= htmlspecialchars($success) ?>
                    <div class="mt-2">
                        <small><i class="bi bi-arrow-right me-1"></i>Mengalihkan ke dashboard...</small>
                    </div>
                </div>
            <?php endif; ?>
            
            <form method="POST" id="loginForm">
                <div class="login-type-tabs">
                    <button type="button" class="login-type-tab active" data-type="auto">
                        <i class="bi bi-person-check me-1"></i>Auto
                    </button>
                    <button type="button" class="login-type-tab" data-type="master">
                        <i class="bi bi-crown me-1"></i>Master
                    </button>
                    <button type="button" class="login-type-tab" data-type="sub">
                        <i class="bi bi-person me-1"></i>Sub Admin
                    </button>
                </div>
                
                <input type="hidden" name="login_type" id="loginType" value="auto">
                
                <div class="input-group">
                    <i class="bi bi-person input-icon"></i>
                    <input type="text" 
                           class="form-control has-icon" 
                           name="username" 
                           placeholder="Username" 
                           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">
                    <i class="bi bi-box-arrow-in-right me-2"></i>
                    Login
                </button>
            </form>
            
            <div class="mt-3 text-center">
                <small class="text-muted">
                    <i class="bi bi-info-circle me-1"></i>
                    <span id="loginInfo">
                        Sistem akan mendeteksi otomatis jenis admin
                    </span>
                </small>
            </div>
        </div>
        
        <div class="version-info">
            <i class="bi bi-gear me-2"></i>
            Integrated Admin System v2.0 | <?= htmlspecialchars($currentSite['domain'] ?? $_SERVER['HTTP_HOST']) ?>
        </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 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;
                    
                    switch(type) {
                        case 'auto':
                            loginInfo.textContent = 'Sistem akan mendeteksi otomatis jenis admin';
                            break;
                        case 'master':
                            loginInfo.textContent = 'Login khusus untuk Master Admin (admin lama)';
                            break;
                        case 'sub':
                            loginInfo.textContent = 'Login khusus untuk Sub Admin per situs';
                            break;
                    }
                });
            });
            
            // 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 and loading state
            const form = document.getElementById('loginForm');
            form.addEventListener('submit', function(e) {
                const username = document.querySelector('input[name="username"]').value.trim();
                const password = document.querySelector('input[name="password"]').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>Memproses...';
            });
        });
    </script>
</body>
</html>