<?php
require_once '../includes/config.php';

// Check if user is already logged in
if (isUserLoggedIn()) {
    redirect(SITE_URL);
}

$error = '';
$username = '';

// Save redirect URL if provided
if (isset($_GET['redirect'])) {
    $_SESSION['redirect_after_login'] = $_GET['redirect'];
} 

// Process login form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitize($_POST['username']);
    $password = $_POST['password'];
    
    // Validate input
    if (empty($username) || empty($password)) {
        $error = 'Silakan lengkapi semua field';
    } else {
        try {
            $conn = connectDB();
            $stmt = $conn->prepare("SELECT * FROM users WHERE username = :username");
            $stmt->bindParam(':username', $username);
            $stmt->execute();
            
            if ($user = $stmt->fetch(PDO::FETCH_ASSOC)) {
                // Verify password
                if (password_verify($password, $user['password'])) {
                    // Set session variables
                    $_SESSION['user_id'] = $user['user_id'];
                    $_SESSION['user_name'] = $user['name'];
                    $_SESSION['user_username'] = $user['username'];
                    
                    // Check if we have a redirect URL
                    if (isset($_SESSION['redirect_after_login'])) {
                        $redirectUrl = $_SESSION['redirect_after_login'];
                        unset($_SESSION['redirect_after_login']);
                        
                        // Make sure the redirect URL is to the same site
                        if (strpos($redirectUrl, '/') === 0) {
                            // It's a relative URL, so it's safe
                            redirect($redirectUrl);
                        } else {
                            // It might be a full URL, check if it's for our site
                            $urlParts = parse_url($redirectUrl);
                            if (!isset($urlParts['host']) || $urlParts['host'] == $_SERVER['HTTP_HOST']) {
                                redirect($redirectUrl);
                            } else {
                                // If it's an external URL, redirect to home
                                redirect(SITE_URL);
                            }
                        }
                    } else {
                        // No redirect URL, go to home page
                        redirect(SITE_URL);
                    }
                } else {
                    $error = 'Username atau password salah';
                }
            } else {
                $error = 'Username atau password salah';
            }
        } catch (PDOException $e) {
            $error = 'Terjadi kesalahan: ' . $e->getMessage();
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>assets/css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background-color: #f4f4f4;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
        }
        
        .user-login-container {
            background: white;
            padding: 30px;
            border-radius: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 400px;
            /* Ensuring proper responsiveness for smaller screens */
            margin: 20px; /* Add some margin for smaller screens */
            box-sizing: border-box;
        }
        
        .user-login-container h2 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        
        .user-login-logo {
            text-align: center;
            margin-bottom: 20px;
        }
        
        .user-login-logo h1 {
            color: var(--primary-color);
            font-size: 24px;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
        }
        
        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .btn {
            display: block;
            width: 100%;
            padding: 10px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            text-align: center;
        }
        
        .btn:hover {
            background-color: #3a8f3a;
        }
        
        .error {
            background-color: #f8d7da;
            color: #721c24;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        
        .user-login-footer {
            margin-top: 20px;
            text-align: center;
            font-size: 14px;
        }
        
        .user-login-footer a {
            color: var(--primary-color);
            text-decoration: none;
        }
        
        .user-login-footer a:hover {
            text-decoration: underline;
        }
        
        .back-to-site {
            display: block;
            text-align: center;
            margin-top: 15px;
            color: #666;
        }
        
        /* Password visibility toggle */
        .password-input-wrapper {
            position: relative;
        }
        
        .password-toggle {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #666;
            z-index: 10;
        }
        
        .password-toggle:hover {
            color: var(--primary-color);
        }

        @media (max-width: 480px) {
            .user-login-container {
                margin: 10px;
                padding: 20px;
            }
            .user-login-logo h1 { font-size: 20px; }
            .user-login-logo p { font-size: 14px; }
        }
    </style>
</head>
<body>
    <div class="user-login-container">
        <div class="user-login-logo">
            <h1><?php echo SITE_NAME; ?></h1>
            <p>Login Pengguna</p>
        </div>
        
        <?php if ($error): ?>
            <div class="error"><?php echo $error; ?></div>
        <?php endif; ?>
        
        <form action="login.php<?php echo isset($_GET['redirect']) ? '?redirect=' . htmlspecialchars($_GET['redirect']) : ''; ?>" method="post">
            <div class="form-group">
                <label for="username">Username:</label>
                <input type="text" id="username" name="username" value="<?php echo $username; ?>" required>
            </div>
            
            <div class="form-group">
                <label for="password">Password:</label>
                <div class="password-input-wrapper">
                    <input type="password" id="password" name="password" required>
                    <span class="password-toggle" onclick="togglePassword('password')">
                        <i class="far fa-eye" id="password-toggle-icon"></i>
                    </span>
                </div>
            </div>
            
            <button type="submit" class="btn">Login</button>
        </form>
        
        <div class="user-login-footer">
            <p>Belum punya akun? <a href="register.php">Daftar di sini</a></p>
            <p>Lupa password? <a href="forgot_password.php">Klik di sini</a></p>
            <a href="<?php echo SITE_URL; ?>" class="back-to-site">
                <i class="fas fa-arrow-left"></i> Kembali ke Website
            </a>
        </div>
    </div>
    
    <script>
        function togglePassword(inputId) {
            const passwordInput = document.getElementById(inputId);
            const toggleIcon = document.getElementById(inputId + '-toggle-icon');
            
            if (passwordInput) {
                if (passwordInput.type === 'password') {
                    passwordInput.type = 'text';
                    toggleIcon.classList.remove('fa-eye');
                    toggleIcon.classList.add('fa-eye-slash');
                } else {
                    passwordInput.type = 'password';
                    toggleIcon.classList.remove('fa-eye-slash');
                    toggleIcon.classList.add('fa-eye');
                }
            }
        }
    </script>
</body>
</html> 