<?php
// Start session
session_start();

// Include language file
require_once 'includes/language.php';

// Check if user is already logged in
if (isset($_SESSION['user_id'])) {
    header("Location: home.php");
    exit;
}

// Include database and user class
require_once 'config/database.php';
require_once 'classes/User.php';

// Initialize variables
$username = "";
$email = "";
$error_msg = "";
$success_msg = "";

// Process registration form
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Get form data
    $username = trim($_POST['username'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = trim($_POST['password'] ?? '');
    $confirm_password = trim($_POST['confirm_password'] ?? '');
    
    // Validate input
    if (empty($username) || empty($email) || empty($password) || empty($confirm_password)) {
        $error_msg = "Please fill in all fields.";
    } else if ($password !== $confirm_password) {
        $error_msg = __('passwords_not_match');
    } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error_msg = "Invalid email format.";
    } else {
        try {
            // Create database connection
            $database = new Database();
            $db = $database->getConnection();
            
            // Check if username already exists
            $query = "SELECT id FROM users WHERE username = :username LIMIT 1";
            $stmt = $db->prepare($query);
            $stmt->bindParam(":username", $username);
            $stmt->execute();
            
            if ($stmt->rowCount() > 0) {
                $error_msg = __('username_exists');
            } else {
                // Check if email already exists
                $query = "SELECT id FROM users WHERE email = :email LIMIT 1";
                $stmt = $db->prepare($query);
                $stmt->bindParam(":email", $email);
                $stmt->execute();
                
                if ($stmt->rowCount() > 0) {
                    $error_msg = __('email_exists');
                } else {
                    // Create user object
                    $user = new User($db);
                    $user->username = $username;
                    $user->email = $email;
                    $user->password = $password;
                    
                    // Register user
                    if ($user->register()) {
                        $success_msg = __('registration_success');
                        // Clear form data
                        $username = "";
                        $email = "";
                    } else {
                        $error_msg = "Unable to register. Please try again.";
                    }
                }
            }
        } catch (Exception $e) {
            $error_msg = "An error occurred: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="<?php echo $_SESSION['lang']; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo __('register') . ' - ' . __('climbing_journal'); ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <div class="container">
        <div class="login-container">
            <h1><?php echo __('climbing_journal'); ?></h1>
            
            <div class="language-switcher">
                <a href="?lang=en" class="lang-link <?php echo ($_SESSION['lang'] == 'en') ? 'active' : ''; ?>">ENG</a> / 
                <a href="?lang=sr" class="lang-link <?php echo ($_SESSION['lang'] == 'sr') ? 'active' : ''; ?>">SRB</a>
            </div>
            
            <div class="login-form">
                <h2><?php echo __('register'); ?></h2>
                
                <?php if (!empty($error_msg)): ?>
                <div class="alert alert-danger">
                    <?php echo $error_msg; ?>
                </div>
                <?php endif; ?>
                
                <?php if (!empty($success_msg)): ?>
                <div class="alert alert-success">
                    <?php echo $success_msg; ?>
                </div>
                <?php endif; ?>
                
                <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
                    <div class="form-group">
                        <label for="username"><?php echo __('username'); ?></label>
                        <input type="text" name="username" id="username" value="<?php echo htmlspecialchars($username); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="email"><?php echo __('email'); ?></label>
                        <input type="email" name="email" id="email" value="<?php echo htmlspecialchars($email); ?>" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="password"><?php echo __('password'); ?></label>
                        <input type="password" name="password" id="password" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm_password"><?php echo __('confirm_password'); ?></label>
                        <input type="password" name="confirm_password" id="confirm_password" required>
                    </div>
                    
                    <div class="form-group">
                        <button type="submit" class="btn btn-primary"><?php echo __('register_button'); ?></button>
                    </div>
                </form>
                
                <div class="login-link">
                    <?php echo __('login_link'); ?> <a href="index.php"><?php echo __('login'); ?></a>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
