<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'includes/db.php';
require_once 'includes/functions.php';

if (isLoggedIn()) {
    $role = getUserRole();
    if ($role === 'admin') {
        header('Location: ' . SITE_URL . '/admin/');
    } elseif ($role === 'employer') {
        header('Location: ' . SITE_URL . '/employer/dashboard.php');
    } else {
        header('Location: ' . SITE_URL . '/candidate/dashboard.php');
    }
    exit;
}

$error = '';
$redirect = $_GET['redirect'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    
    if (empty($email) || empty($password)) {
        $error = 'Please enter your email and password.';
    } else {
        $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $user = $stmt->fetch();
        
        if ($user && verifyPassword($password, $user['password'])) {
            if (empty($user['is_active']) || $user['is_active'] != 1) {
                $error = 'Your account is not active. Please contact support.';
            } else {
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['user_name'] = $user['name'];
                $_SESSION['user_email'] = $user['email'];
                $_SESSION['user_role'] = $user['role'];
                
                flash('success', 'Welcome back, ' . $user['name'] . '!');
                
                if (!empty($redirect)) {
                    header('Location: ' . SITE_URL . '/' . $redirect);
                } elseif ($user['role'] === 'admin') {
                    header('Location: ' . SITE_URL . '/admin/');
                } elseif ($user['role'] === 'employer') {
                    header('Location: ' . SITE_URL . '/employer/dashboard.php');
                } else {
                    header('Location: ' . SITE_URL . '/candidate/dashboard.php');
                }
                exit;
            }
        } else {
            $error = 'Invalid email or password.';
        }
    }
}

$pageTitle = 'Login';
$pageDescription = 'Sign in to your ' . SITE_NAME . ' account to access your dashboard, manage job applications, and find your dream career opportunity.';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <title><?php echo $pageTitle . ' - ' . SITE_NAME; ?></title>
    <meta name="description" content="<?php echo htmlspecialchars($pageDescription, ENT_QUOTES, 'UTF-8'); ?>">
    <meta property="og:title" content="<?php echo $pageTitle . ' - ' . SITE_NAME; ?>">
    <meta property="og:description" content="<?php echo htmlspecialchars($pageDescription, ENT_QUOTES, 'UTF-8'); ?>">
    <meta property="og:type" content="website">
    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="<?php echo $pageTitle . ' - ' . SITE_NAME; ?>">
    <meta name="twitter:description" content="<?php echo htmlspecialchars($pageDescription, ENT_QUOTES, 'UTF-8'); ?>">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="/assets/css/style.css?v=<?php echo time(); ?>">
</head>
<body>
    <div class="auth-container">
        <div class="auth-card">
            <a href="<?php echo SITE_URL; ?>" class="logo" style="display: flex; align-items: center; justify-content: center; gap: 12px; margin-bottom: 20px; text-decoration: none;">
                <img src="/logo-icon.png" alt="<?php echo SITE_NAME; ?>" style="width: 52px; height: auto; display: block;">
                <span style="
                    font-size: 2rem;
                    font-weight: 700;
                    line-height: 1;
                    background: linear-gradient(135deg, #4f46e5, #7c3aed);
                    -webkit-background-clip: text;
                    -webkit-text-fill-color: transparent;
                    background-clip: text;
                ">WorklyJobs</span>
            </a>
            
            <h1>Welcome Back</h1>
            <p class="subtitle">Sign in to your account</p>
            
            <?php if ($error): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-times-circle"></i>
                    <?php echo $error; ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="" data-validate>
                <input type="hidden" name="redirect" value="<?php echo sanitize($redirect); ?>">
                
                <div class="form-group">
                    <label for="email">Email Address</label>
                    <input type="email" id="email" name="email" class="form-control" placeholder="Enter your email" required autocomplete="email" value="<?php echo sanitize($_POST['email'] ?? ''); ?>">
                </div>
                
                <div class="form-group">
                    <label for="password">Password</label>
                    <div style="position: relative;">
                        <input type="password" id="password" name="password" class="form-control" placeholder="Enter your password" required autocomplete="current-password">
                        <button type="button" class="password-toggle" style="position: absolute; right: 15px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: var(--gray-500);">
                            <i class="fas fa-eye"></i>
                        </button>
                    </div>
                </div>
                
                <div style="text-align: right; margin-bottom: 15px;">
                    <a href="<?php echo SITE_URL; ?>/forgot-password.php" style="color: var(--primary); font-size: 14px;">Forgot Password?</a>
                </div>
                
                <button type="submit" class="btn btn-primary btn-lg" style="width: 100%;">
                    <i class="fas fa-sign-in-alt"></i> Sign In
                </button>
            </form>
            
            <?php
            $socialSettings = [];
            $stmt = $pdo->query("SELECT setting_key, setting_value FROM site_settings WHERE setting_key IN ('social_login_enabled', 'google_client_id', 'linkedin_client_id')");
            while ($row = $stmt->fetch()) {
                $socialSettings[$row['setting_key']] = $row['setting_value'];
            }
            $socialEnabled = ($socialSettings['social_login_enabled'] ?? 'false') === 'true';
            $googleEnabled = !empty($socialSettings['google_client_id']);
            $linkedinEnabled = !empty($socialSettings['linkedin_client_id']);
            
            if ($socialEnabled && ($googleEnabled || $linkedinEnabled)):
            ?>
            <div class="social-login-divider" style="display: flex; align-items: center; margin: 25px 0; gap: 15px;">
                <div style="flex: 1; height: 1px; background: #e2e8f0;"></div>
                <span style="color: var(--gray-500); font-size: 14px;">or continue with</span>
                <div style="flex: 1; height: 1px; background: #e2e8f0;"></div>
            </div>
            
            <div class="social-login-buttons" style="display: flex; gap: 15px;">
                <?php if ($googleEnabled): ?>
                <a href="<?php echo SITE_URL; ?>/auth/google.php" class="btn btn-outline" style="flex: 1; display: flex; align-items: center; justify-content: center; gap: 10px; padding: 12px; border: 2px solid #e2e8f0; border-radius: 10px; text-decoration: none; color: #333;">
                    <svg width="20" height="20" viewBox="0 0 24 24"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>
                    Google
                </a>
                <?php endif; ?>
                <?php if ($linkedinEnabled): ?>
                <a href="<?php echo SITE_URL; ?>/auth/linkedin.php" class="btn btn-outline" style="flex: 1; display: flex; align-items: center; justify-content: center; gap: 10px; padding: 12px; border: 2px solid #e2e8f0; border-radius: 10px; text-decoration: none; color: #333;">
                    <i class="fab fa-linkedin" style="color: #0077b5; font-size: 20px;"></i>
                    LinkedIn
                </a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            
            <div class="auth-footer">
                Don't have an account? <a href="register.php">Sign Up</a>
            </div>
            
            <div style="text-align: center; margin-top: 20px;">
                <a href="<?php echo SITE_URL; ?>" style="color: var(--gray-500);">
                    <i class="fas fa-arrow-left"></i> Back to Home
                </a>
            </div>
        </div>
    </div>
    
    <script src="/assets/js/main.js?v=<?php echo time(); ?>"></script>
</body>
</html>
