<?php
/**
 * Login Page - PREMIUM VERSION
 * Digital Marketplace
 */

require_once __DIR__ . '/config/database.php';

$page_title = 'Login';

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

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        $email = sanitize_email($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $remember = isset($_POST['remember']);
        
        // Validation
        if (empty($email)) {
            $errors[] = 'Email is required';
        }
        if (empty($password)) {
            $errors[] = 'Password is required';
        }
        
        if (empty($errors)) {
            // Check login attempts
            if (!check_login_attempts($email)) {
                $errors[] = 'Too many failed login attempts. Please try again later.';
            } else {
                // Get user
                $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ? AND is_active = 1");
                $stmt->execute([$email]);
                $user = $stmt->fetch();
                
                if ($user && verify_password($password, $user['password'])) {
                    // Login successful
                    log_login_attempt($email, true);
                    
                    // Set session
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['user_logged_in'] = true;
                    $_SESSION['user_name'] = $user['name'];
                    $_SESSION['user_email'] = $user['email'];
                    
                    // Remember me
                    if ($remember) {
                        $token = generate_random_string(32);
                        $expires = date('Y-m-d H:i:s', strtotime('+30 days'));
                        
                        $stmt = $pdo->prepare("INSERT INTO user_remember_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
                        $stmt->execute([$user['id'], hash('sha256', $token), $expires]);
                        
                        setcookie('remember_token', $token, time() + 30 * 24 * 60 * 60, '/', '', false, true);
                    }
                    
                    // Merge cart
                    merge_cart_on_login($user['id']);
                    
                    // Log activity
                    log_activity('user_login', "User {$user['email']} logged in");
                    
                    // Redirect
                    $redirect = $_SESSION['redirect_after_login'] ?? BASE_URL . '/account/index.php';
                    unset($_SESSION['redirect_after_login']);
                    
                    set_flash_message('Welcome back, ' . $user['name'] . '!', 'success');
                    header('Location: ' . $redirect);
                    exit;
                } else {
                    log_login_attempt($email, false);
                    $errors[] = 'Invalid email or password';
                }
            }
        }
    }
}

include __DIR__ . '/includes/header.php';
?>

<section class="section">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6 col-lg-5">
                <div class="card auth-card" data-aos="fade-up">
                    <div class="card-body p-5">
                        <div class="text-center mb-4">
                            <div class="auth-icon mb-3">
                                <i class="fas fa-user-circle"></i>
                            </div>
                            <h2 class="mb-2">Welcome Back</h2>
                            <p class="text-muted">Sign in to your account</p>
                        </div>
                        
                        <?php if (!empty($errors)): ?>
                            <div class="alert alert-danger">
                                <?php foreach ($errors as $error): ?>
                                    <div><i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?></div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" id="loginForm">
                            <?php echo csrf_field(); ?>
                            
                            <div class="mb-3">
                                <label class="form-label">Email Address</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                                    <input type="email" name="email" class="form-control" 
                                           placeholder="Enter your email" required
                                           value="<?php echo sanitize($_POST['email'] ?? ''); ?>">
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Password</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                    <input type="password" name="password" class="form-control" 
                                           placeholder="Enter your password" required
                                           id="passwordInput">
                                    <button type="button" class="input-group-text password-toggle" data-target="#passwordInput">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <div class="form-check">
                                    <input type="checkbox" name="remember" class="form-check-input" id="rememberMe">
                                    <label class="form-check-label" for="rememberMe">Remember me</label>
                                </div>
                                <a href="<?php echo BASE_URL; ?>/forgot-password.php" class="text-primary">Forgot password?</a>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100 btn-lg mb-3">
                                <i class="fas fa-sign-in-alt me-2"></i>Sign In
                            </button>
                            
                            <div class="text-center">
                                <p class="mb-0">Don't have an account? <a href="<?php echo BASE_URL; ?>/register.php" class="text-primary">Sign up</a></p>
                            </div>
                        </form>
                        
                        <hr class="my-4">
                        
                        <div class="text-center">
                            <p class="text-muted mb-3">Or continue with</p>
                            <div class="social-login">
                                <a href="#" class="social-btn google">
                                    <i class="fab fa-google"></i>
                                </a>
                                <a href="#" class="social-btn facebook">
                                    <i class="fab fa-facebook-f"></i>
                                </a>
                                <a href="#" class="social-btn github">
                                    <i class="fab fa-github"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<style>
/* Auth Card */
.auth-card {
    border: 1px solid var(--dark-lighter);
    background: var(--gradient-card);
}

.auth-icon {
    width: 80px;
    height: 80px;
    margin: 0 auto;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--gradient-primary);
    border-radius: 50%;
    font-size: 2.5rem;
    color: var(--white);
}

/* Password Toggle */
.password-toggle {
    cursor: pointer;
    background: var(--dark-lighter);
    border: 1px solid var(--dark-lighter);
    color: var(--gray-400);
}

.password-toggle:hover {
    color: var(--white);
}

/* Social Login */
.social-login {
    display: flex;
    justify-content: center;
    gap: 12px;
}

.social-btn {
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    background: var(--dark-lighter);
    border-radius: var(--radius);
    color: var(--white);
    font-size: 1.25rem;
    transition: var(--transition);
}

.social-btn:hover {
    background: var(--primary);
    color: var(--white);
}
</style>

<?php include __DIR__ . '/includes/footer.php'; ?>
