<?php
// /login.php - Soul Guard Login Page
session_start();
require_once __DIR__ . '/config.php';

// If already logged in, redirect to appropriate dashboard
if (isset($_SESSION['user_id'])) {
    if (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1) {
        header('Location: /admin/index.php');
        exit;
    } elseif (isset($_SESSION['user_id'])) {
        header('Location: /index.php');
        exit;
    }
}

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

// Check for error from redirect
if (isset($_GET['error'])) {
    $error = htmlspecialchars($_GET['error']);
}

// Handle login form submission
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 {
        try {
            $pdo = getDBConnection();
            
            // Search by username OR email
            $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? OR email = ?");
            $stmt->execute([$username, $username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$user) {
                $error = 'Invalid username or password';
            } elseif ($user['is_active'] != 1) {
                $error = 'Account is not activated. Please contact administrator.';
            } elseif (!password_verify($password, $user['password_hash'])) {
                $error = 'Invalid username or password';
            } else {
                // Login successful - set session variables
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['full_name'] = $user['full_name'] ?? $user['username'];
                $_SESSION['is_admin'] = $user['is_admin'] ?? 0;
                $_SESSION['organization_id'] = $user['organization_id'] ?? null;
                
                // Update last login
                $updateStmt = $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
                $updateStmt->execute([$user['id']]);
                
                // Redirect based on admin status
                if ($user['is_admin'] == 1) {
                    header('Location: /admin/index.php');
                } else {
                    header('Location: /index.php');
                }
                exit;
            }
        } catch (PDOException $e) {
            $error = 'Database error: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - Soul Guard Security Platform</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
            background: linear-gradient(135deg, #0a0a0f 0%, #0f0f1a 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            overflow-x: hidden;
        }

        body::before {
            content: '';
            position: absolute;
            width: 100%;
            height: 100%;
            background-image: radial-gradient(circle at 20% 50%, rgba(59, 130, 246, 0.08) 0%, transparent 50%),
                              radial-gradient(circle at 80% 80%, rgba(168, 85, 247, 0.08) 0%, transparent 50%);
            pointer-events: none;
        }

        .login-container {
            background: rgba(19, 19, 26, 0.9);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.08);
            border-radius: 32px;
            padding: 48px 40px;
            width: 100%;
            max-width: 460px;
            margin: 20px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.5);
            position: relative;
            z-index: 1;
        }

        .logo {
            text-align: center;
            margin-bottom: 32px;
        }

        .logo-icon {
            width: 70px;
            height: 70px;
            background: linear-gradient(135deg, #3b82f6, #a855f7);
            border-radius: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 36px;
            margin: 0 auto 16px;
            box-shadow: 0 10px 25px -5px rgba(59, 130, 246, 0.3);
        }

        h1 {
            font-size: 28px;
            font-weight: 700;
            background: linear-gradient(135deg, #3b82f6, #a855f7);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 6px;
        }

        .subtitle {
            text-align: center;
            color: #a1a1aa;
            font-size: 13px;
            margin-top: 4px;
        }

        .form-group {
            margin-bottom: 24px;
        }

        label {
            display: block;
            color: #d4d4d8;
            font-size: 13px;
            font-weight: 500;
            margin-bottom: 8px;
        }

        .input-wrapper {
            position: relative;
        }

        .input-icon {
            position: absolute;
            left: 14px;
            top: 50%;
            transform: translateY(-50%);
            font-size: 18px;
        }

        input {
            width: 100%;
            padding: 12px 16px 12px 44px;
            background: rgba(255, 255, 255, 0.05);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 14px;
            color: #e4e4e7;
            font-size: 14px;
            transition: all 0.2s;
        }

        input:focus {
            outline: none;
            border-color: #3b82f6;
            background: rgba(59, 130, 246, 0.08);
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        input::placeholder {
            color: #52525b;
        }

        button {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #3b82f6, #a855f7);
            border: none;
            border-radius: 14px;
            color: white;
            font-size: 15px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }

        button:hover {
            transform: translateY(-1px);
            box-shadow: 0 10px 20px -5px rgba(59, 130, 246, 0.4);
        }

        button:active {
            transform: translateY(0);
        }

        .error {
            background: rgba(239, 68, 68, 0.12);
            border: 1px solid rgba(239, 68, 68, 0.25);
            border-radius: 14px;
            padding: 12px 16px;
            color: #fca5a5;
            font-size: 13px;
            margin-bottom: 24px;
            text-align: center;
        }

        .success {
            background: rgba(34, 197, 94, 0.12);
            border: 1px solid rgba(34, 197, 94, 0.25);
            border-radius: 14px;
            padding: 12px 16px;
            color: #86efac;
            font-size: 13px;
            margin-bottom: 24px;
            text-align: center;
        }

        .footer {
            text-align: center;
            margin-top: 32px;
            padding-top: 24px;
            border-top: 1px solid rgba(255, 255, 255, 0.06);
            color: #71717a;
            font-size: 11px;
        }

        .footer p {
            margin: 4px 0;
        }

        .debug-info {
            margin-top: 20px;
            padding: 12px;
            background: rgba(0, 0, 0, 0.3);
            border-radius: 10px;
            font-size: 11px;
            color: #71717a;
            display: none;
        }

        @media (max-width: 480px) {
            .login-container {
                padding: 32px 24px;
                margin: 16px;
            }
            
            h1 {
                font-size: 24px;
            }
            
            .logo-icon {
                width: 56px;
                height: 56px;
                font-size: 28px;
            }
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">
            <div class="logo-icon">🛡️</div>
            <h1>Soul Guard</h1>
            <div class="subtitle">AI-Powered Security Platform</div>
        </div>

        <?php if ($error): ?>
            <div class="error"><?php echo $error; ?></div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="success"><?php echo $success; ?></div>
        <?php endif; ?>

        <form method="POST" action="">
            <div class="form-group">
                <label>Username or Email</label>
                <div class="input-wrapper">
                    <span class="input-icon">👤</span>
                    <input type="text" name="username" required 
                           placeholder="admin or admin@security.local" 
                           value="<?php echo htmlspecialchars($_POST['username'] ?? ''); ?>"
                           autocomplete="username">
                </div>
            </div>

            <div class="form-group">
                <label>Password</label>
                <div class="input-wrapper">
                    <span class="input-icon">🔒</span>
                    <input type="password" name="password" required 
                           placeholder="Enter your password"
                           autocomplete="current-password">
                </div>
            </div>

            <button type="submit">Login to Dashboard</button>
        </form>

        <div class="footer">
            <p>&copy; <?php echo date('Y'); ?> Soul Guard Security Platform</p>
            <p>Secure Login | SSL Encrypted</p>
        </div>
    </div>
</body>
</html>