<?php
session_start();
require_once '../config/database.php';
require_once '../includes/auth.php';
require_once '../config/logger.php';

// Redirect if already logged in
if (isLoggedIn()) {
    header('Location: index.php');
    exit();
}

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

// Check for success message from registration
if (isset($_GET['registered']) && $_GET['registered'] == '1') {
    $success = "Registration successful! Please login with your credentials.";
}

// Handle login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email']);
    $password = trim($_POST['password']);
    
    logInfo("Job portal login attempt started", [
        'email' => $email,
        'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown'
    ]);
    
    if (empty($email) || empty($password)) {
        $error = "Please provide both email and password.";
        logInfo("Login failed - missing credentials", ['email' => $email]);
    } else {
        // Check user credentials in job portal users table
        $userQuery = "SELECT * FROM job_portal_users WHERE email = ? AND status = 'active'";
        $user = fetchRow($userQuery, [$email]);
        
        logInfo("User lookup result", [
            'email' => $email,
            'user_found' => $user ? 'yes' : 'no',
            'user_type' => $user ? $user['user_type'] : 'n/a',
            'user_status' => $user ? $user['status'] : 'n/a',
            'member_id' => $user ? ($user['member_id'] ?? 'null') : 'n/a'
        ]);
        
        if ($user) {
            // Test password verification
            $passwordMatch = password_verify($password, $user['password']);
            
            logInfo("Password verification attempt", [
                'email' => $email,
                'user_id' => $user['id'],
                'user_type' => $user['user_type'],
                'password_match' => $passwordMatch ? 'yes' : 'no',
                'password_hash_length' => strlen($user['password']),
                'password_hash_prefix' => substr($user['password'], 0, 10)
            ]);
            
            if ($passwordMatch) {
                // Login successful
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_email'] = $user['email'];
                $_SESSION['user_name'] = $user['full_name'];
                $_SESSION['user_type'] = $user['user_type'];
                $_SESSION['member_id'] = $user['member_id'];
                
                logInfo("Job portal login successful", [
                    'user_id' => $user['id'],
                    'email' => $user['email'],
                    'user_type' => $user['user_type'],
                    'member_id' => $user['member_id'] ?? 'null'
                ]);
                
                // Redirect to intended page or dashboard
                $redirect = isset($_GET['redirect']) ? $_GET['redirect'] : 'index.php';
                header('Location: ' . $redirect);
                exit();
            } else {
                $error = "Invalid email or password.";
                logError("Job portal login failed - password mismatch", [
                    'email' => $email,
                    'user_id' => $user['id'],
                    'user_type' => $user['user_type'],
                    'attempted_password_length' => strlen($password)
                ]);
            }
        } else {
            $error = "Invalid email or password.";
            
            // Check if user exists but is inactive
            $inactiveUser = fetchRow("SELECT * FROM job_portal_users WHERE email = ?", [$email]);
            if ($inactiveUser) {
                logError("Job portal login failed - user inactive", [
                    'email' => $email,
                    'user_status' => $inactiveUser['status'],
                    'user_type' => $inactiveUser['user_type']
                ]);
            } else {
                logError("Job portal login failed - user not found", [
                    'email' => $email
                ]);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - GHAMECC Job Portal</title>
    
    <?php include '../includes/favicon.php'; ?>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
        }
        .login-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            overflow: hidden;
            max-width: 400px;
            width: 100%;
        }
        .login-header {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        .login-body {
            padding: 2rem;
        }
        .btn-primary {
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
            border: none;
            padding: 12px 30px;
            border-radius: 25px;
        }
        .btn-primary:hover {
            background: linear-gradient(135deg, #45a049 0%, #4CAF50 100%);
        }
        .form-control:focus {
            border-color: #4CAF50;
            box-shadow: 0 0 0 0.2rem rgba(76, 175, 80, 0.25);
        }
        .social-login {
            border-top: 1px solid #e9ecef;
            padding-top: 1.5rem;
            margin-top: 1.5rem;
        }
        .forgot-password {
            color: #6c757d;
            text-decoration: none;
            font-size: 0.9rem;
        }
        .forgot-password:hover {
            color: #4CAF50;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-5">
                <div class="login-container">
                    <div class="login-header">
                        <h3><i class="fas fa-sign-in-alt me-2"></i>Welcome Back</h3>
                        <p class="mb-0">Sign in to GHAMECC Job Portal</p>
                    </div>
                    
                    <div class="login-body">
                        <?php if (!empty($error)): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-triangle me-2"></i><?php echo $error; ?>
                            </div>
                        <?php endif; ?>

                        <?php if (!empty($success)): ?>
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                            </div>
                        <?php endif; ?>

                        <form method="POST">
                            <div class="mb-3">
                                <label for="email" class="form-label">
                                    <i class="fas fa-envelope me-1"></i>Email Address
                                </label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" 
                                       required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">
                                    <i class="fas fa-lock me-1"></i>Password
                                </label>
                                <input type="password" class="form-control" id="password" name="password" required>
                            </div>
                            
                            <div class="mb-3 form-check">
                                <input type="checkbox" class="form-check-input" id="remember" name="remember">
                                <label class="form-check-label" for="remember">
                                    Remember me
                                </label>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-sign-in-alt me-2"></i>Sign In
                            </button>
                        </form>

                        <div class="text-center mt-3">
                            <a href="forgot-password.php" class="forgot-password">
                                <i class="fas fa-key me-1"></i>Forgot your password?
                            </a>
                        </div>

                        <div class="social-login text-center">
                            <p class="text-muted mb-3">Don't have an account?</p>
                            <a href="register.php" class="btn btn-outline-success w-100">
                                <i class="fas fa-user-plus me-2"></i>Create New Account
                            </a>
                        </div>

                        <div class="text-center mt-3">
                            <a href="index.php" class="text-muted text-decoration-none">
                                <i class="fas fa-home me-1"></i>Back to Homepage
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
