<?php 
session_start();
require_once 'includes/database.php';

// Initialize default settings
$settings = [
    'logo_type' => 'text',
    'logo_text' => 'FantasyVote',
    'logo_image' => '',
    'footer_text' => 'Vote for your favorite players and coaches every game week!'
];

try {
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM site_settings");
    if ($stmt) {
        $settings_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach($settings_data as $setting) {
            $settings[$setting['setting_key']] = $setting['setting_value'];
        }
    }
} catch(Exception $e) {
    // Use defaults if settings table doesn't exist or query fails
    error_log("Site settings error: " . $e->getMessage());
}

$logo_type = $settings['logo_type'];
$logo_text = $settings['logo_text'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - FantasyVote</title>
    <link rel="stylesheet" href="css/style.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
    <nav class="navbar">
        <div class="nav-container">
            <div class="nav-logo">
                <a href="index.php">
                    <?php if($logo_type === 'image' && !empty($settings['logo_image'])): ?>
                        <img src="<?php echo $settings['logo_image']; ?>" alt="<?php echo htmlspecialchars($logo_text); ?>" 
                             style="height: 40px; max-width: 200px; object-fit: contain;"
                             onerror="this.style.display='none'; document.getElementById('fallbackLogo').style.display='inline-block';">
                        <span id="fallbackLogo" style="display: none;"><?php echo htmlspecialchars($logo_text); ?></span>
                    <?php else: ?>
                        <?php echo htmlspecialchars($logo_text); ?>
                    <?php endif; ?>
                </a>
            </div>
            
            <div class="menu-toggle">
                <span></span>
                <span></span>
                <span></span>
            </div>
            
            <div class="nav-menu">
                <a href="index.php"><i class="fas fa-home"></i> Home</a>
                <a href="vote.php"><i class="fas fa-vote-yea"></i> Vote</a>
                <a href="leaderboard.php"><i class="fas fa-trophy"></i> Leaderboard</a>
                <a href="team-of-week.php"><i class="fas fa-users"></i> Team of Week</a>
                <a href="login.php"><i class="fas fa-sign-in-alt"></i> Login</a>
            </div>
        </div>
    </nav>

    <main>
        <div class="container">
            <div class="auth-form">
                <h2>Create Account</h2>
                <p class="bonus-notice" style="background: linear-gradient(135deg, #27ae60, #219653); color: white; padding: 1rem; border-radius: 8px; text-align: center; margin-bottom: 1.5rem;">
                    <i class="fas fa-gift"></i> <strong>Get 100 FREE ZIT Coins</strong> when you register!<br>
                    <small>Use coins to vote for your favorite players (10 coins per vote)</small>
                </p>
                
                <?php
                if($_POST){
                    $username = trim($_POST['username']);
                    $email = trim($_POST['email']);
                    $password = $_POST['password'];
                    $confirm_password = $_POST['confirm_password'];
                    
                    try {
                        // Validate inputs
                        if(empty($username) || empty($email) || empty($password)) {
                            throw new Exception("All fields are required!");
                        }
                        
                        if($password !== $confirm_password) {
                            throw new Exception("Passwords do not match!");
                        }
                        
                        if(strlen($password) < 6) {
                            throw new Exception("Password must be at least 6 characters long!");
                        }
                        
                        if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                            throw new Exception("Invalid email format!");
                        }
                        
                        // Check if username or email already exists
                        $stmt = $pdo->prepare("SELECT id FROM users WHERE username = ? OR email = ?");
                        $stmt->execute([$username, $email]);
                        
                        if($stmt->fetch()) {
                            throw new Exception("Username or email already exists!");
                        }
                        
                        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                        
                        $pdo->beginTransaction();
                        
                        // Insert user
                        $stmt = $pdo->prepare("INSERT INTO users (username, email, password) VALUES (?, ?, ?)");
                        $stmt->execute([$username, $email, $hashed_password]);
                        $user_id = $pdo->lastInsertId();
                        
                        // Create wallet with 100 free coins
                        $stmt = $pdo->prepare("INSERT INTO user_wallets (user_id, balance) VALUES (?, 100.00)");
                        $stmt->execute([$user_id]);
                        
                        // Add bonus transaction record
                        $stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description) VALUES (?, 'bonus', 100.00, 'Welcome bonus - 100 free ZIT Coins')");
                        $stmt->execute([$user_id]);
                        
                        $pdo->commit();
                        
                        echo "<div class='alert success'>
                            <strong>Registration successful!</strong><br>
                            You've received 100 FREE ZIT Coins!<br>
                            <a href='login.php' style='color: #155724; text-decoration: underline;'>Login here to start voting</a>
                        </div>";
                        
                    } catch(PDOException $e) {
                        if(isset($pdo) && $pdo->inTransaction()) {
                            $pdo->rollBack();
                        }
                        echo "<div class='alert error'>Username or email already exists!</div>";
                    } catch(Exception $e) {
                        if(isset($pdo) && $pdo->inTransaction()) {
                            $pdo->rollBack();
                        }
                        echo "<div class='alert error'>" . $e->getMessage() . "</div>";
                    }
                }
                ?>
                
                <form method="POST">
                    <div class="form-group">
                        <label>Username:</label>
                        <input type="text" name="username" value="<?php echo $_POST['username'] ?? ''; ?>" required 
                               placeholder="Choose a username">
                    </div>
                    
                    <div class="form-group">
                        <label>Email:</label>
                        <input type="email" name="email" value="<?php echo $_POST['email'] ?? ''; ?>" required 
                               placeholder="Enter your email">
                    </div>
                    
                    <div class="form-group">
                        <label>Password:</label>
                        <input type="password" name="password" required 
                               placeholder="At least 6 characters">
                    </div>
                    
                    <div class="form-group">
                        <label>Confirm Password:</label>
                        <input type="password" name="confirm_password" required 
                               placeholder="Re-enter your password">
                    </div>
                    
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-user-plus"></i> Create Account & Get 100 Coins
                    </button>
                </form>
                
                <p style="text-align: center; margin-top: 1.5rem;">
                    Already have an account? <a href="login.php">Login here</a>
                </p>
                
                <div style="background: #f8f9fa; padding: 1rem; border-radius: 8px; margin-top: 1.5rem; border-left: 4px solid #3498db;">
                    <h4 style="margin-bottom: 0.5rem; color: #2c3e50;">
                        <i class="fas fa-info-circle"></i> About ZIT Coins
                    </h4>
                    <ul style="margin: 0; padding-left: 1.2rem; color: #5f6368;">
                        <li>1 Vote = 10 ZIT Coins</li>
                        <li>Get 100 free coins when you register</li>
                        <li>Buy more coins anytime from your wallet</li>
                        <li>Transfer coins to other users</li>
                    </ul>
                </div>
            </div>
        </div>
    </main>

    <?php
    // Get footer text from settings
    $footer_text = $settings['footer_text'];
    $current_year = date('Y');
    ?>

    <footer style="background: linear-gradient(135deg, #0d47a1, #1a73e8); color: white; padding: 3rem 0; margin-top: 4rem;">
        <div class="container" style="text-align: center;">
            <div style="display: inline-block; background: rgba(255,255,255,0.1); padding: 1rem 2rem; border-radius: 10px;">
                <p style="margin: 0; font-size: 1.1rem; font-weight: 600; color: white;">&copy; <?php echo $current_year; ?> FantasyVote. All rights reserved.</p>
                <p style="margin: 0.5rem 0 0 0; opacity: 0.9; color: white;"><?php echo htmlspecialchars($footer_text); ?></p>
            </div>
            <div style="margin-top: 1.5rem;">
                <a href="index.php" style="color: white; margin: 0 1rem; text-decoration: none; transition: opacity 0.3s;">Home</a>
                <a href="vote.php" style="color: white; margin: 0 1rem; text-decoration: none; transition: opacity 0.3s;">Vote</a>
                <a href="leaderboard.php" style="color: white; margin: 0 1rem; text-decoration: none; transition: opacity 0.3s;">Leaderboard</a>
                <a href="team-of-week.php" style="color: white; margin: 0 1rem; text-decoration: none; transition: opacity 0.3s;">Team of Week</a>
            </div>
        </div>
    </footer>

    <script src="js/script.js"></script>
</body>
</html>