<?php
/*******************************************************************************************************************
| Software Name        : EasyStream
| Software Description : High End YouTube Clone Script with Videos, Shorts, Streams, Images, Audio, Documents, Blogs
| Software Author      : (c) Sami Ahmed
|*******************************************************************************************************************
|
|*******************************************************************************************************************
| This source file is subject to the EasyStream Proprietary License Agreement.
| 
| By using this software, you acknowledge having read this Agreement and agree to be bound thereby.
|*******************************************************************************************************************
| Copyright (c) 2025 Sami Ahmed. All rights reserved.
|*******************************************************************************************************************/

defined('_ISVALID') or header('Location: /error');

// Initialize branding system
$branding = VBranding::getInstance();
$imageManager = VImageManager::getInstance();

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'update_settings':
            if (VSecurity::validateCSRFFromPost('branding_update')) {
                $updated = 0;
                $category = $_POST['category'] ?? 'general';
                
                foreach ($_POST as $key => $value) {
                    if (strpos($key, 'setting_') === 0) {
                        $settingKey = substr($key, 8); // Remove 'setting_' prefix
                        $settingType = $_POST["type_$settingKey"] ?? 'text';
                        
                        if ($branding->set($settingKey, $value, $settingType)) {
                            $updated++;
                        }
                    }
                }
                
                $message = $updated > 0 ? "Successfully updated $updated settings!" : "No changes were made.";
                $messageType = $updated > 0 ? 'success' : 'info';
            } else {
                $message = "Security validation failed. Please try again.";
                $messageType = 'error';
            }
            break;
            
        case 'apply_preset':
            if (VSecurity::validateCSRFFromPost('preset_apply')) {
                $presetName = $_POST['preset_name'] ?? '';
                if ($branding->applyPreset($presetName)) {
                    $message = "Successfully applied preset: $presetName";
                    $messageType = 'success';
                } else {
                    $message = "Failed to apply preset: $presetName";
                    $messageType = 'error';
                }
            }
            break;
            
        case 'upload_image':
            if (VSecurity::validateCSRFFromPost('image_upload')) {
                $imageKey = $_POST['image_key'] ?? '';
                $presetKey = $_POST['preset_key'] ?? null;
                
                if (isset($_FILES['image_file']) && !empty($imageKey)) {
                    $result = $imageManager->uploadImage($_FILES['image_file'], $imageKey, $presetKey);
                    
                    if ($result['success']) {
                        $message = "Image uploaded successfully! Dimensions: {$result['width']}x{$result['height']}";
                        $messageType = 'success';
                    } else {
                        $message = "Upload failed: " . $result['error'];
                        $messageType = 'error';
                    }
                } else {
                    $message = "Please select a file and specify an image key.";
                    $messageType = 'error';
                }
            }
            break;
            
        case 'delete_image':
            if (VSecurity::validateCSRFFromPost('image_delete')) {
                $imageId = (int) ($_POST['image_id'] ?? 0);
                
                if ($imageId > 0 && $imageManager->deleteImage($imageId)) {
                    $message = "Image deleted successfully!";
                    $messageType = 'success';
                } else {
                    $message = "Failed to delete image.";
                    $messageType = 'error';
                }
            }
            break;
    }
}

// Get current tab and data
$currentTab = $_GET['tab'] ?? 'general';
$categories = $branding->getCategories();
$presets = $branding->getPresets();
$siteInfo = $branding->getSiteInfo();
$imagePresets = $imageManager->getImagePresets();
$uploadedImages = $imageManager->getUploadedImages();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Branding Management - <?php echo htmlspecialchars($siteInfo['name']); ?></title>
    <style>
        <?php echo $branding->generateCSS(); ?>
    </style>
</head>
<body>
    <div class="admin-container">
        <h1>🎨 Branding Management</h1>
        
        <?php if (isset($message)): ?>
            <div class="message <?php echo $messageType; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>
        
        <div class="tabs">
            <?php foreach ($categories as $category): ?>
                <a href="?tab=<?php echo urlencode($category); ?>" 
                   class="tab <?php echo $currentTab === $category ? 'active' : ''; ?>">
                    <?php echo ucfirst($category); ?>
                </a>
            <?php endforeach; ?>
            <a href="?tab=images" class="tab <?php echo $currentTab === 'images' ? 'active' : ''; ?>">
                Images
            </a>
            <a href="?tab=presets" class="tab <?php echo $currentTab === 'presets' ? 'active' : ''; ?>">
                Presets
            </a>
        </div>
        
        <div class="tab-content">
            <?php $settings = $branding->getByCategory($currentTab); ?>
            <?php if (!empty($settings)): ?>
                <h2><?php echo ucfirst($currentTab); ?> Settings</h2>
                
                <form method="post">
                    <?php echo VSecurity::getCSRFField('branding_update'); ?>
                    <input type="hidden" name="action" value="update_settings">
                    <input type="hidden" name="category" value="<?php echo htmlspecialchars($currentTab); ?>">
                    
                    <?php foreach ($settings as $key => $setting): ?>
                        <div class="setting-item">
                            <label><?php echo ucwords(str_replace('_', ' ', $key)); ?></label>
                            
                            <input type="hidden" name="type_<?php echo htmlspecialchars($key); ?>" value="<?php echo htmlspecialchars($setting['type']); ?>">
                            
                            <?php if ($setting['type'] === 'color'): ?>
                                <input type="color" 
                                       name="setting_<?php echo htmlspecialchars($key); ?>" 
                                       value="<?php echo htmlspecialchars($setting['value']); ?>">
                            <?php else: ?>
                                <input type="text" 
                                       name="setting_<?php echo htmlspecialchars($key); ?>" 
                                       value="<?php echo htmlspecialchars($setting['value']); ?>">
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                    
                    <button type="submit">Save Changes</button>
                </form>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>