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

if(!isset($_SESSION['admin_logged_in'])) {
    header('Location: login.php');
    exit;
}

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

// Handle form submissions
if($_POST) {
    if(isset($_POST['update_logo'])) {
        $logo_type = $_POST['logo_type'];
        $logo_text = $_POST['logo_text'] ?? '';
        
        // Handle logo image upload
        $logo_path = null;
        if(isset($_FILES['logo_image']) && $_FILES['logo_image']['error'] === 0) {
            $upload_dir = '../assets/uploads/logo/';
            if(!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_extension = pathinfo($_FILES['logo_image']['name'], PATHINFO_EXTENSION);
            $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'svg'];
            
            if(in_array(strtolower($file_extension), $allowed_extensions)) {
                $new_filename = 'logo_' . time() . '.' . $file_extension;
                $upload_path = $upload_dir . $new_filename;
                
                if(move_uploaded_file($_FILES['logo_image']['tmp_name'], $upload_path)) {
                    $logo_path = 'assets/uploads/logo/' . $new_filename;
                }
            }
        }
        
        try {
            // Update site settings in database
            $pdo->beginTransaction();
            
            // Update logo type
            $stmt = $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('logo_type', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute([$logo_type, $logo_type]);
            
            // Update logo text
            $stmt = $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('logo_text', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute([$logo_text, $logo_text]);
            
            // Update logo image if uploaded
            if($logo_path) {
                $stmt = $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('logo_image', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
                $stmt->execute([$logo_path, $logo_path]);
            }
            
            $pdo->commit();
            $_SESSION['success'] = "Site settings updated successfully!";
            
        } catch(Exception $e) {
            $pdo->rollBack();
            $_SESSION['error'] = "Error updating settings: " . $e->getMessage();
        }
        
        header('Location: site-settings.php');
        exit;
        
    } elseif(isset($_POST['update_footer'])) {
        $footer_text = $_POST['footer_text'] ?? '';
        
        try {
            $stmt = $pdo->prepare("INSERT INTO site_settings (setting_key, setting_value) VALUES ('footer_text', ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute([$footer_text, $footer_text]);
            
            $_SESSION['success'] = "Footer text updated successfully!";
        } catch(Exception $e) {
            $_SESSION['error'] = "Error updating footer: " . $e->getMessage();
        }
        
        header('Location: site-settings.php');
        exit;
    }
}

// Get current settings
$settings = $default_settings;
try {
    $stmt = $pdo->query("SELECT setting_key, setting_value FROM site_settings");
    $settings_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach($settings_data as $setting) {
        $settings[$setting['setting_key']] = $setting['setting_value'];
    }
} catch(Exception $e) {
    // If table doesn't exist, use defaults
    $_SESSION['error'] = "Settings table not found. Using default settings.";
}

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Site Settings - Admin</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">
    <style>
    /* Define CSS variables */
    :root {
        --primary-blue: #1a73e8;
        --secondary-blue: #4285f4;
        --dark-blue: #0d47a1;
        --light-blue: #e8f0fe;
        --accent-blue: #34a853;
        --warning: #fbbc05;
        --danger: #ea4335;
        --light: #f8f9fa;
        --dark: #202124;
        --gray: #5f6368;
        --white: #ffffff;
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Segoe UI', system-ui, -apple-system, sans-serif;
        background-color: #f5f5f5;
        color: #333;
        line-height: 1.6;
    }

    .admin-container {
        max-width: 1000px;
        margin: 0 auto;
        padding: 2rem;
    }
    
    .admin-nav {
        background: linear-gradient(135deg, #0d47a1, #1a73e8);
        color: white;
        padding: 1rem 0;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    
    .admin-nav-container {
        max-width: 1000px;
        margin: 0 auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 2rem;
    }
    
    .admin-menu a {
        color: white;
        text-decoration: none;
        margin-left: 1.5rem;
        padding: 0.5rem 1rem;
        border-radius: 5px;
        transition: background 0.3s ease;
        font-weight: 500;
    }
    
    .admin-menu a:hover {
        background: rgba(255, 255, 255, 0.2);
    }
    
    .settings-section {
        background: white;
        padding: 2rem;
        border-radius: 10px;
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        margin-bottom: 2rem;
    }
    
    .form-grid {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 1.5rem;
    }
    
    .logo-preview {
        text-align: center;
        padding: 2rem;
        background: #f8f9fa;
        border-radius: 10px;
        margin-top: 1rem;
        border: 2px dashed #dee2e6;
        color: #333;
    }
    
    .logo-preview img {
        max-width: 200px;
        max-height: 80px;
        margin-bottom: 1rem;
    }
    
    .logo-options {
        display: flex;
        gap: 1rem;
        margin-bottom: 1rem;
    }
    
    .logo-option {
        flex: 1;
        text-align: center;
        padding: 1rem;
        border: 2px solid #e9ecef;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        color: #333;
        background: white;
    }
    
    .logo-option.active {
        border-color: #1a73e8;
        background: #e8f0fe;
    }
    
    .logo-option input[type="radio"] {
        display: none;
    }
    
    .current-logo {
        background: #e8f5e8;
        padding: 1rem;
        border-radius: 8px;
        margin-top: 1rem;
        border-left: 4px solid #34a853;
        color: #155724;
    }

    .form-group label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 600;
        color: #0d47a1;
    }

    .form-group input,
    .form-group textarea,
    .form-group select {
        width: 100%;
        padding: 12px;
        border: 2px solid #e8f0fe;
        border-radius: 8px;
        font-size: 1rem;
        transition: all 0.3s ease;
        background: white;
        color: #333;
    }

    .form-group input:focus,
    .form-group textarea:focus,
    .form-group select:focus {
        outline: none;
        border-color: #1a73e8;
        box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.1);
    }

    .btn {
        padding: 12px 30px;
        border: none;
        border-radius: 8px;
        cursor: pointer;
        font-size: 1rem;
        font-weight: 600;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        gap: 0.5rem;
        transition: all 0.3s ease;
    }

    .btn-primary {
        background: linear-gradient(135deg, #34a853, #219653);
        color: white;
        box-shadow: 0 4px 15px rgba(52, 168, 83, 0.3);
    }

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(52, 168, 83, 0.4);
    }

    .alert {
        padding: 1rem;
        border-radius: 8px;
        margin-bottom: 1rem;
        border-left: 4px solid;
    }

    .alert.success {
        background: #f0f9f0;
        color: #155724;
        border-left-color: #34a853;
    }

    .alert.error {
        background: #fdf2f2;
        color: #721c24;
        border-left-color: #ea4335;
    }

    h1, h2 {
        color: #0d47a1;
        margin-bottom: 1rem;
    }

    small {
        color: #5f6368;
        font-size: 0.9rem;
    }
    
    @media (max-width: 768px) {
        .form-grid {
            grid-template-columns: 1fr;
        }
        
        .logo-options {
            flex-direction: column;
        }
    }
</style>
</head>
<body>
    <nav class="admin-nav">
        <div class="admin-nav-container">
            <div class="nav-logo">
                <a href="index.php" style="color: white; text-decoration: none; font-weight: bold; font-size: 1.2rem;">
                    <i class="fas fa-cogs"></i> Site Settings
                </a>
            </div>
            <div class="admin-menu">
                <a href="index.php"><i class="fas fa-tachometer-alt"></i> Dashboard</a>
                <a href="manage-players.php"><i class="fas fa-users"></i> Players</a>
                <a href="manage-coaches.php"><i class="fas fa-user-tie"></i> Coaches</a>
                <a href="manage-voting.php"><i class="fas fa-vote-yea"></i> Voting</a>
                <a href="site-settings.php"><i class="fas fa-cogs"></i> Settings</a>
                <a href="../logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a>
            </div>
        </div>
    </nav>
    
    <div class="admin-container">
        <h1>Site Settings</h1>
        
        <?php if(isset($_SESSION['success'])): ?>
            <div class="alert success"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div>
        <?php endif; ?>
        
        <?php if(isset($_SESSION['error'])): ?>
            <div class="alert error"><?php echo $_SESSION['error']; unset($_SESSION['error']); ?></div>
        <?php endif; ?>
        
        <!-- Logo Settings -->
        <section class="settings-section">
            <h2><i class="fas fa-palette"></i> Site Logo Settings</h2>
            <form method="POST" enctype="multipart/form-data">
                <div class="logo-options">
                    <label class="logo-option <?php echo $logo_type === 'text' ? 'active' : ''; ?>">
                        <input type="radio" name="logo_type" value="text" <?php echo $logo_type === 'text' ? 'checked' : ''; ?>>
                        <i class="fas fa-font" style="font-size: 2rem; margin-bottom: 0.5rem; display: block;"></i>
                        Text Logo
                    </label>
                    <label class="logo-option <?php echo $logo_type === 'image' ? 'active' : ''; ?>">
                        <input type="radio" name="logo_type" value="image" <?php echo $logo_type === 'image' ? 'checked' : ''; ?>>
                        <i class="fas fa-image" style="font-size: 2rem; margin-bottom: 0.5rem; display: block;"></i>
                        Image Logo
                    </label>
                </div>
                
                <div class="form-grid">
                    <div class="form-group">
                        <label>Logo Text (if using text logo):</label>
                        <input type="text" name="logo_text" value="<?php echo htmlspecialchars($logo_text); ?>" 
                               placeholder="Enter logo text" class="logo-text-input">
                    </div>
                    
                    <div class="form-group">
                        <label>Logo Image (if using image logo):</label>
                        <input type="file" name="logo_image" accept="image/*" class="logo-image-input">
                        <small>Recommended size: 200x80px. Formats: JPG, PNG, GIF, SVG</small>
                    </div>
                </div>
                
                <?php if($logo_image && $logo_type === 'image'): ?>
                <div class="current-logo">
                    <strong>Current Logo Image:</strong>
                    <div style="margin-top: 0.5rem;">
                        <img src="../<?php echo $logo_image; ?>" alt="Current Logo" 
                             onerror="this.style.display='none'; this.nextElementSibling.style.display='block';">
                        <div style="display: none; color: #e74c3c; padding: 0.5rem; background: #fdf2f2; border-radius: 5px;">
                            <i class="fas fa-exclamation-triangle"></i> Logo image not found at: <?php echo $logo_image; ?>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <div class="logo-preview">
                    <h4>Live Preview:</h4>
                    <div id="logoPreview">
                        <?php if($logo_type === 'text'): ?>
                            <div style="font-size: 1.5rem; font-weight: bold; color: var(--primary-blue);">
                                <?php echo htmlspecialchars($logo_text); ?>
                            </div>
                        <?php elseif($logo_type === 'image' && $logo_image): ?>
                            <img src="../<?php echo $logo_image; ?>" alt="Logo Preview" 
                                 onerror="this.parentElement.innerHTML='<div style=color:red; padding: 1rem;><i class=fas fa-exclamation-triangle></i> Image not found</div>'">
                        <?php else: ?>
                            <div style="color: var(--gray); padding: 1rem;">
                                <i class="fas fa-info-circle"></i> No logo image uploaded
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <div style="margin-top: 1.5rem;">
                    <button type="submit" name="update_logo" class="btn btn-primary">
                        <i class="fas fa-save"></i> Update Logo Settings
                    </button>
                </div>
            </form>
        </section>
        
        <!-- Footer Settings -->
        <section class="settings-section">
            <h2><i class="fas fa-shoe-prints"></i> Footer Settings</h2>
            <form method="POST">
                <div class="form-group">
                    <label>Footer Text:</label>
                    <textarea name="footer_text" rows="3" placeholder="Enter footer text" class="footer-text-input"><?php echo htmlspecialchars($footer_text); ?></textarea>
                    <small>This text will appear in the website footer below the copyright notice</small>
                </div>
                
                <div class="form-group">
                    <label>Copyright Notice Preview:</label>
                    <div style="background: #f8f9fa; padding: 1.5rem; border-radius: 8px; margin-top: 0.5rem; border-left: 4px solid var(--primary-blue);">
                        <strong style="color: var(--dark-blue);">&copy; <?php echo date('Y'); ?> FantasyVote. All rights reserved.</strong><br>
                        <span style="color: var(--gray); margin-top: 0.5rem; display: block;"><?php echo htmlspecialchars($footer_text); ?></span>
                    </div>
                </div>
                
                <button type="submit" name="update_footer" class="btn btn-primary">
                    <i class="fas fa-save"></i> Update Footer Text
                </button>
            </form>
        </section>
        
        <!-- Current Settings Overview -->
        <section class="settings-section">
            <h2><i class="fas fa-info-circle"></i> Current Settings Overview</h2>
            <div class="form-grid">
                <div class="form-group">
                    <label>Logo Type:</label>
                    <input type="text" value="<?php echo ucfirst($logo_type); ?> Logo" disabled style="background: #f8f9fa;">
                </div>
                <div class="form-group">
                    <label>Current Year:</label>
                    <input type="text" value="<?php echo date('Y'); ?>" disabled style="background: #f8f9fa;">
                </div>
                <div class="form-group">
                    <label>Logo Text:</label>
                    <input type="text" value="<?php echo htmlspecialchars($logo_text); ?>" disabled style="background: #f8f9fa;">
                </div>
                <div class="form-group">
                    <label>Settings Status:</label>
                    <input type="text" value="Active" disabled style="background: #e8f5e8; color: #155724; border-color: #c3e6cb;">
                </div>
            </div>
        </section>
    </div>
    
    <script>
    // Update logo preview when settings change
    function updateLogoPreview() {
        const logoType = document.querySelector('input[name="logo_type"]:checked').value;
        const logoText = document.querySelector('input[name="logo_text"]').value;
        const preview = document.getElementById('logoPreview');
        
        if (logoType === 'text') {
            preview.innerHTML = `<div style="font-size: 1.5rem; font-weight: bold; color: var(--primary-blue);">${logoText || 'FantasyVote'}</div>`;
        } else {
            preview.innerHTML = '<div style="color: var(--gray); padding: 1rem;"><i class="fas fa-info-circle"></i> Logo image will be displayed here after upload</div>';
        }
        
        // Update active class on logo options
        document.querySelectorAll('.logo-option').forEach(option => {
            option.classList.remove('active');
        });
        document.querySelector(`.logo-option input[value="${logoType}"]`).closest('.logo-option').classList.add('active');
    }
    
    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        // Add event listeners
        document.querySelectorAll('input[name="logo_type"]').forEach(radio => {
            radio.addEventListener('change', updateLogoPreview);
        });
        
        document.querySelector('input[name="logo_text"]').addEventListener('input', updateLogoPreview);
        
        // Initial preview update
        updateLogoPreview();
        
        console.log('Site settings page loaded successfully');
    });
    </script>
</body>
</html>