<?php
require_once 'config/database.php';
require_once 'config/session.php';

// If already logged in, redirect to dashboard
if (isLoggedIn()) {
    redirectBasedOnRole();
}

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

// Check for registration success message
if (isset($_GET['registered']) && $_GET['registered'] == '1') {
    $success = "Registration successful! Your account is pending admin approval. You will receive an email when activated.";
}

// Check for account activation message
if (isset($_GET['activated']) && $_GET['activated'] == '1') {
    $success = "Your account has been activated! You can now login.";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim($_POST['username']);
    $password = $_POST['password'];
    
    try {
        // Get user with employee details
        $stmt = $pdo->prepare("
            SELECT u.*, e.department, e.full_name as employee_name, e.id as employee_id 
            FROM users u 
            LEFT JOIN employees e ON u.id = e.user_id 
            WHERE u.username = ? OR u.email = ?
        ");
        $stmt->execute([$username, $username]);
        $user = $stmt->fetch();
        
        if ($user) {
            // Check if account is active
            if (!$user['is_active']) {
                $error = "Your account is pending admin approval. Please wait for activation.";
            } elseif (password_verify($password, $user['password'])) {
                // Set session variables
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['full_name'] = $user['employee_name'] ?? $user['username'];
                $_SESSION['department'] = $user['department'] ?? '';
                $_SESSION['employee_id'] = $user['employee_id'] ?? null;
                $_SESSION['login_time'] = time();
                $_SESSION['last_activity'] = time();
                
                // Update last login
                $updateStmt = $pdo->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
                $updateStmt->execute([$user['id']]);
                
                // Redirect based on role
                redirectBasedOnRole();
                
            } else {
                $error = "Invalid username or password!";
            }
        } else {
            $error = "Invalid username or password!";
        }
        
    } catch (PDOException $e) {
        $error = "Login error. Please try again.";
        error_log("Login 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>HR System - Login</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.8.1/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .login-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            width: 100%;
            max-width: 450px;
            overflow: hidden;
            height: 90vh;
        }
        .login-header {
            background: linear-gradient(90deg, #0d6efd, #0dcaf0);
            color: white;
            padding: 30px;
            text-align: center;
        }
        .card-body {
            padding: 30px;
        }
        .role-badge {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 4px;
            font-size: 0.8em;
            margin-top: 5px;
        }
        .badge-admin { background: #dc3545; color: white; }
        .badge-manager { background: #ffc107; color: black; }
        .badge-employee { background: #28a745; color: white; }
        .form-control:focus {
            border-color: #0d6efd;
            box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
        }
        .btn-login {
            background: linear-gradient(90deg, #0d6efd, #0dcaf0);
            border: none;
            color: white;
            padding: 10px 0;
            font-weight: 600;
        }
        .btn-login:hover {
            background: linear-gradient(90deg, #0b5ed7, #0ba8d9);
            color: white;
        }
    </style>
</head>
<body>
    <div class="login-card">
        <div class="login-header">
            <h3><i class="bi bi-people-fill"></i> HR System</h3>
            <p class="mb-0">Employee Management Portal</p>
        </div>
        <div class="card-body">
            <?php if($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <i class="bi bi-check-circle"></i> <?php echo $success; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <?php if($error): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <i class="bi bi-exclamation-triangle"></i> <?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="">
                <div class="mb-3">
                    <label for="username" class="form-label">Username or Email</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-person"></i></span>
                        <input type="text" class="form-control" id="username" name="username" 
                               placeholder="Enter username or email" required autofocus>
                    </div>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Password</label>
                    <div class="input-group">
                        <span class="input-group-text"><i class="bi bi-lock"></i></span>
                        <input type="password" class="form-control" id="password" name="password" 
                               placeholder="Enter password" required>
                    </div>
                </div>
                <div class="mb-3 form-check">
                    <input type="checkbox" class="form-check-input" id="remember">
                    <label class="form-check-label" for="remember">Remember me</label>
                    <a href="#" class="float-end text-decoration-none" data-bs-toggle="modal" data-bs-target="#forgotPasswordModal">
                        <small>Forgot password?</small>
                    </a>
                </div>
                <button type="submit" class="btn btn-login w-100 mb-3">Login</button>
                
                <div class="text-center">
                    <p class="mb-2">New employee? <a href="register.php" class="text-decoration-none fw-bold">Register here</a></p>
                    <small class="text-muted">Registration requires admin approval</small>
                </div>
            </form>
            
            <hr class="my-4">
            
            <div class="text-center">
                <p class="mb-2">Demo Accounts:</p>
                <div class="row g-2">
                    <div class="col-12">
                        <div class="border rounded p-2">
                            <small><strong>Admin:</strong> admin / password123</small>
                            <span class="badge-admin role-badge">Admin</span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="border rounded p-2">
                            <small><strong>Employee:</strong> employee1 / password123</small>
                            <span class="badge-employee role-badge">Employee</span>
                        </div>
                    </div>
                    <div class="col-12">
                        <div class="border rounded p-2">
                            <small><strong>Manager:</strong> manager1 / password123</small>
                            <span class="badge-manager role-badge">Manager</span>
                        </div>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Forgot Password Modal -->
    <div class="modal fade" id="forgotPasswordModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Forgot Password</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p>Please contact your HR administrator or system admin to reset your password.</p>
                    <div class="alert alert-info">
                        <i class="bi bi-info-circle"></i> 
                        <strong>HR Department:</strong> hr@company.com<br>
                        <strong>System Admin:</strong> admin@hrsystem.com
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Auto focus on username field
        document.getElementById('username').focus();
        
        // Show/hide password
        document.querySelector('input[name="password"]').addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                document.querySelector('form').submit();
            }
        });
    </script>
</body>
</html>