<?php
/**
 * Hostxolo - User Login Page
 */
require_once 'config.php';

// Redirect if already logged in
if (is_logged_in()) {
    redirect(BASE_URL . 'user/dashboard.php');
}

$error = '';

// Process login form
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Verify CSRF token
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $email = sanitize($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $remember = isset($_POST['remember']);
        
        if (empty($email) || empty($password)) {
            $error = 'Please enter both email and password.';
        } else {
            try {
                // Check user credentials
                $stmt = db()->prepare("SELECT * FROM users WHERE email = ? AND status = 'active'");
                $stmt->execute([$email]);
                $user = $stmt->fetch();
                
                if ($user && password_verify($password, $user['password'])) {
                    // Update last login
                    $stmt = db()->prepare("UPDATE users SET last_login = NOW() WHERE id = ?");
                    $stmt->execute([$user['id']]);
                    
                    // Set session
                    $_SESSION['user_id'] = $user['id'];
                    $_SESSION['user_name'] = $user['full_name'];
                    $_SESSION['user_email'] = $user['email'];
                    $_SESSION['user_role'] = 'user';
                    
                    // Set remember me cookie
                    if ($remember) {
                        $token = generate_random_string(32);
                        setcookie('remember_token', $token, time() + (30 * 24 * 60 * 60), '/');
                        
                        // Store token in database (optional enhancement)
                    }
                    
                    // Log activity
                    log_activity('login', 'User logged in successfully', $user['id'], 'user');
                    
                    // Redirect to dashboard
                    $redirect = $_SESSION['redirect_after_login'] ?? BASE_URL . 'user/dashboard.php';
                    unset($_SESSION['redirect_after_login']);
                    redirect($redirect, 'success', 'Welcome back, ' . $user['full_name'] . '!');
                } else {
                    $error = 'Invalid email or password.';
                    log_activity('login_failed', 'Failed login attempt for: ' . $email, null, 'user');
                }
            } catch (PDOException $e) {
                $error = 'Login failed. Please try again.';
                error_log("Login error: " . $e->getMessage());
            }
        }
    }
}

$csrf_token = generate_csrf_token();

// Set page specific SEO
$page_title = 'Login - Hostxolo';

include 'includes/header.php';
?>

<section class="py-5" style="margin-top: 70px; min-height: calc(100vh - 300px);">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6 col-lg-5">
                <div class="card shadow-lg border-0">
                    <div class="card-body p-4 p-md-5">
                        <div class="text-center mb-4">
                            <div class="mb-3">
                                <i class="bi bi-person-circle text-primary" style="font-size: 4rem;"></i>
                            </div>
                            <h2 class="fw-bold">Welcome Back</h2>
                            <p class="text-muted">Sign in to your Hostxolo account</p>
                        </div>
                        
                        <?php if ($error): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="bi bi-exclamation-triangle-fill me-2"></i><?php echo $error; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" action="" class="needs-validation" novalidate>
                            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
                            
                            <div class="mb-4">
                                <label for="email" class="form-label">Email Address</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="bi bi-envelope"></i></span>
                                    <input type="email" class="form-control" id="email" name="email" required 
                                           placeholder="Enter your email" value="<?php echo $_POST['email'] ?? ''; ?>">
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <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" required 
                                           placeholder="Enter your password">
                                    <button class="btn btn-outline-secondary password-toggle" type="button">
                                        <i class="bi bi-eye"></i>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="d-flex justify-content-between align-items-center mb-4">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="remember" name="remember">
                                    <label class="form-check-label" for="remember">
                                        Remember me
                                    </label>
                                </div>
                                <a href="<?php echo BASE_URL; ?>forgot-password.php" class="text-decoration-none">
                                    Forgot password?
                                </a>
                            </div>
                            
                            <div class="d-grid mb-4">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="bi bi-box-arrow-in-right me-2"></i>Sign In
                                </button>
                            </div>
                            
                            <div class="text-center">
                                <p class="text-muted mb-0">Don't have an account? 
                                    <a href="<?php echo BASE_URL; ?>register.php" class="fw-bold">Register now</a>
                                </p>
                            </div>
                        </form>
                        
                        <hr class="my-4">
                        
                        <!-- Social Login (Placeholder) -->
                        <div class="text-center">
                            <p class="text-muted mb-3">Or continue with</p>
                            <div class="d-flex justify-content-center gap-2">
                                <a href="#" class="btn btn-outline-secondary">
                                    <i class="bi bi-google"></i>
                                </a>
                                <a href="#" class="btn btn-outline-secondary">
                                    <i class="bi bi-facebook"></i>
                                </a>
                                <a href="#" class="btn btn-outline-secondary">
                                    <i class="bi bi-linkedin"></i>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

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