<?php
/**
 * Store Customization Page - For Store Owners to customize their store appearance
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';
require_once '../app/classes/SessionManager.php';
use App\classes\SessionManager;

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

$userId = $_SESSION['user_id'];

// SECURITY: Validate session
$sessionManager = new SessionManager($conn);
$sessionValidation = $sessionManager->validateSession($userId);

if (!$sessionValidation['valid']) {
    error_log("Invalid session detected - User ID: $userId, Reason: " . $sessionValidation['reason']);
    $sessionManager->forceLogout();
    header("Location: ../login.php?error=session_invalid");
    exit();
}

// Verify user is a store owner
$storeManager = new StoreManager($conn);
$verification = $storeManager->verifyStoreOwner($userId);

if (!$verification['valid']) {
    error_log("Store Customization Access Denied - User ID: $userId, Reason: " . $verification['reason']);
    header("Location: store_dashboard.php");
    exit();
}

// Load store
$store = $storeManager->getStoreByOwnerId($userId);

if (!$store) {
    header("Location: store_dashboard.php");
    exit();
}

// Generate store URL
$baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'];
$storeUrl = $baseUrl . "/store.php?slug=" . urlencode($store['store_slug']);

// Include reusable navigation
require_once 'includes/store_nav.php';

$message = '';
$messageType = '';

// CSRF Protection
function generateCSRFToken() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validateCSRFToken($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Protection
    if (!isset($_POST['csrf_token']) || !validateCSRFToken($_POST['csrf_token'])) {
        $message = 'Invalid security token. Please refresh the page and try again.';
        $messageType = 'error';
    } else {
        // Handle reset to default
        if (isset($_POST['reset_to_default']) && $_POST['reset_to_default'] === '1') {
            // Reset all customization fields to default values
            $defaultData = [
                'hero_color_1' => '#3b82f6',
                'hero_color_2' => '#8b5cf6',
                'button_color' => '#3b82f6',
                'button_hover_color' => '#2563eb',
                'background_color' => '#0f172a',
                'form_theme' => 'dark'
            ];
            
            // Reset working hours to NULL (all disabled)
            $resetWorkingHoursStmt = $conn->prepare("UPDATE stores SET working_hours = NULL WHERE id = ?");
            $resetWorkingHoursStmt->bind_param("i", $store['id']);
            $resetWorkingHoursStmt->execute();
            $resetWorkingHoursStmt->close();
            
            $result = $storeManager->updateStore($store['id'], $defaultData);
            if ($result['success']) {
                $message = 'Store customization reset to default values successfully!';
                $messageType = 'success';
                // Reload store data
                $store = $storeManager->getStoreByOwnerId($userId);
            } else {
                $message = 'Error: ' . $result['message'];
                $messageType = 'error';
            }
        } else {
            $updateData = [];
            
            // Handle hero colors
            if (isset($_POST['hero_color_1']) && preg_match('/^#[0-9A-Fa-f]{6}$/', $_POST['hero_color_1'])) {
                $updateData['hero_color_1'] = $_POST['hero_color_1'];
            }
            
            if (isset($_POST['hero_color_2']) && preg_match('/^#[0-9A-Fa-f]{6}$/', $_POST['hero_color_2'])) {
                $updateData['hero_color_2'] = $_POST['hero_color_2'];
            }
            
            // Handle button colors
            if (isset($_POST['button_color']) && preg_match('/^#[0-9A-Fa-f]{6}$/', $_POST['button_color'])) {
                $updateData['button_color'] = $_POST['button_color'];
            }
            
            if (isset($_POST['button_hover_color']) && preg_match('/^#[0-9A-Fa-f]{6}$/', $_POST['button_hover_color'])) {
                $updateData['button_hover_color'] = $_POST['button_hover_color'];
            }
            
            // Handle background color
            if (isset($_POST['background_color']) && preg_match('/^#[0-9A-Fa-f]{6}$/', $_POST['background_color'])) {
                $updateData['background_color'] = $_POST['background_color'];
            }
            
            // Handle form theme
            if (isset($_POST['form_theme']) && in_array($_POST['form_theme'], ['dark', 'light'])) {
                $updateData['form_theme'] = $_POST['form_theme'];
            }
            
            // Handle working hours
            if (isset($_POST['working_hours'])) {
                $workingHours = [];
                $days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
                
                foreach ($days as $day) {
                    $enabled = isset($_POST['working_hours'][$day]['enabled']) ? 1 : 0;
                    $openTime = isset($_POST['working_hours'][$day]['open']) ? $_POST['working_hours'][$day]['open'] : '08:00';
                    $closeTime = isset($_POST['working_hours'][$day]['close']) ? $_POST['working_hours'][$day]['close'] : '17:00';
                    
                    // Validate time format (HH:MM)
                    if (preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $openTime) && 
                        preg_match('/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/', $closeTime)) {
                        $workingHours[$day] = [
                            'enabled' => $enabled,
                            'open' => $openTime,
                            'close' => $closeTime
                        ];
                    }
                }
                
                if (!empty($workingHours)) {
                    $updateData['working_hours'] = json_encode($workingHours);
                }
            }
            
            // Update store
            if (!empty($updateData)) {
                $result = $storeManager->updateStore($store['id'], $updateData);
                if ($result['success']) {
                    $message = 'Store customization updated successfully!';
                    $messageType = 'success';
                    // Reload store data
                    $store = $storeManager->getStoreByOwnerId($userId);
                } else {
                    $message = 'Error: ' . $result['message'];
                    $messageType = 'error';
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <title>Store Customization | Store Dashboard</title>
    
    <!-- Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');
        
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(180deg, #0f172a 0%, #1e293b 100%);
            min-height: 100vh;
        }
    </style>
</head>
<body class="bg-gray-900 text-white">
    <?php renderStoreNav($store, 'customization'); ?>

    <div class="min-h-screen py-4 sm:py-6">
        <div class="container mx-auto px-4">
            <!-- Header -->
            <div class="mb-6">
                <div class="mb-4">
                    <h1 class="text-2xl sm:text-3xl font-bold text-white mb-2">
                        <i class="fas fa-palette mr-2"></i>Store Customization
                    </h1>
                    <p class="text-gray-400 text-sm sm:text-base">Customize your store's appearance, colors, and branding</p>
                </div>
                
                <?php if ($message): ?>
                <div class="mb-4 p-4 rounded-lg <?php echo $messageType === 'success' ? 'bg-green-900/50 border border-green-700 text-green-300' : 'bg-red-900/50 border border-red-700 text-red-300'; ?>">
                    <i class="fas <?php echo $messageType === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?> mr-2"></i>
                    <?php echo htmlspecialchars($message); ?>
                </div>
                <?php endif; ?>
            </div>
            
            <!-- Customization Form -->
            <form method="POST" class="space-y-6">
                <input type="hidden" name="csrf_token" value="<?php echo generateCSRFToken(); ?>">
                <!-- Hero Section Colors -->
                <div class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700">
                    <h2 class="text-xl font-bold mb-4 text-white">
                        <i class="fas fa-paint-brush mr-2"></i>Hero Section Colors
                    </h2>
                    
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">Hero Color 1 (Gradient Start)</label>
                            <div class="flex items-center gap-2">
                                <input type="color" name="hero_color_1" id="hero_color_1" 
                                       value="<?php echo htmlspecialchars($store['hero_color_1'] ?? '#3b82f6'); ?>"
                                       class="w-16 h-10 rounded-lg border border-gray-600 cursor-pointer">
                                <input type="text" name="hero_color_1_text" id="hero_color_1_text" 
                                       value="<?php echo htmlspecialchars($store['hero_color_1'] ?? '#3b82f6'); ?>"
                                       pattern="^#[0-9A-Fa-f]{6}$"
                                       class="flex-1 bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">Hero Color 2 (Gradient End)</label>
                            <div class="flex items-center gap-2">
                                <input type="color" name="hero_color_2" id="hero_color_2" 
                                       value="<?php echo htmlspecialchars($store['hero_color_2'] ?? '#8b5cf6'); ?>"
                                       class="w-16 h-10 rounded-lg border border-gray-600 cursor-pointer">
                                <input type="text" name="hero_color_2_text" id="hero_color_2_text" 
                                       value="<?php echo htmlspecialchars($store['hero_color_2'] ?? '#8b5cf6'); ?>"
                                       pattern="^#[0-9A-Fa-f]{6}$"
                                       class="flex-1 bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                            </div>
                        </div>
                    </div>
                    
                    <div class="p-3 bg-gray-900 rounded-lg border border-gray-700">
                        <p class="text-xs text-gray-400 mb-2">Hero Section Preview:</p>
                        <div id="hero_preview" class="h-20 rounded-lg" style="background: linear-gradient(135deg, <?php echo htmlspecialchars($store['hero_color_1'] ?? '#3b82f6'); ?> 0%, <?php echo htmlspecialchars($store['hero_color_2'] ?? '#8b5cf6'); ?> 100%);"></div>
                    </div>
                </div>
                
                <!-- Button Colors -->
                <div class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700">
                    <h2 class="text-xl font-bold mb-4 text-white">
                        <i class="fas fa-mouse-pointer mr-2"></i>Button Colors
                    </h2>
                    
                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 mb-4">
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">Button Color</label>
                            <div class="flex items-center gap-2">
                                <input type="color" name="button_color" id="button_color" 
                                       value="<?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?>"
                                       class="w-16 h-10 rounded-lg border border-gray-600 cursor-pointer">
                                <input type="text" name="button_color_text" id="button_color_text" 
                                       value="<?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?>"
                                       pattern="^#[0-9A-Fa-f]{6}$"
                                       class="flex-1 bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                            </div>
                        </div>
                        
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">Button Hover Color</label>
                            <div class="flex items-center gap-2">
                                <input type="color" name="button_hover_color" id="button_hover_color" 
                                       value="<?php echo htmlspecialchars($store['button_hover_color'] ?? '#2563eb'); ?>"
                                       class="w-16 h-10 rounded-lg border border-gray-600 cursor-pointer">
                                <input type="text" name="button_hover_color_text" id="button_hover_color_text" 
                                       value="<?php echo htmlspecialchars($store['button_hover_color'] ?? '#2563eb'); ?>"
                                       pattern="^#[0-9A-Fa-f]{6}$"
                                       class="flex-1 bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                            </div>
                        </div>
                    </div>
                    
                    <div class="p-3 bg-gray-900 rounded-lg border border-gray-700">
                        <p class="text-xs text-gray-400 mb-2">Button Preview:</p>
                        <div class="flex gap-3">
                            <button type="button" id="button_preview" 
                                    class="px-6 py-3 rounded-lg text-white font-medium transition-colors"
                                    style="background-color: <?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?>;"
                                    onmouseover="this.style.backgroundColor='<?php echo htmlspecialchars($store['button_hover_color'] ?? '#2563eb'); ?>';"
                                    onmouseout="this.style.backgroundColor='<?php echo htmlspecialchars($store['button_color'] ?? '#3b82f6'); ?>';">
                                Sample Button
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- Background Color -->
                <div class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700">
                    <h2 class="text-xl font-bold mb-4 text-white">
                        <i class="fas fa-fill mr-2"></i>Background Color
                    </h2>
                    
                    <div class="mb-4">
                        <label class="block text-sm text-gray-400 mb-2">Store Page Background</label>
                        <div class="flex items-center gap-2">
                            <input type="color" name="background_color" id="background_color" 
                                   value="<?php echo htmlspecialchars($store['background_color'] ?? '#0f172a'); ?>"
                                   class="w-16 h-10 rounded-lg border border-gray-600 cursor-pointer">
                            <input type="text" name="background_color_text" id="background_color_text" 
                                   value="<?php echo htmlspecialchars($store['background_color'] ?? '#0f172a'); ?>"
                                   pattern="^#[0-9A-Fa-f]{6}$"
                                   class="flex-1 bg-gray-700 text-white px-4 py-2 rounded-lg border border-gray-600">
                        </div>
                        <p class="text-xs text-gray-500 mt-1">This color will be used as the main background for your store page</p>
                    </div>
                    
                    <div class="p-3 bg-gray-900 rounded-lg border border-gray-700">
                        <p class="text-xs text-gray-400 mb-2">Background Preview:</p>
                        <div id="background_preview" class="h-20 rounded-lg border-2 border-gray-700" 
                             style="background: linear-gradient(180deg, <?php echo htmlspecialchars($store['background_color'] ?? '#0f172a'); ?> 0%, <?php echo htmlspecialchars($store['background_color'] ?? '#0f172a'); ?> 100%);"></div>
                    </div>
                </div>
                
                <!-- Form Theme -->
                <div class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700">
                    <h2 class="text-xl font-bold mb-4 text-white">
                        <i class="fas fa-adjust mr-2"></i>Form Theme
                    </h2>
                    
                    <div class="mb-4">
                        <label class="block text-sm text-gray-400 mb-2">Choose Form Theme</label>
                        <div class="grid grid-cols-2 gap-4">
                            <label class="relative cursor-pointer">
                                <input type="radio" name="form_theme" value="dark" 
                                       <?php echo ($store['form_theme'] ?? 'dark') === 'dark' ? 'checked' : ''; ?>
                                       class="sr-only peer">
                                <div class="p-4 bg-gray-700 border-2 border-gray-600 rounded-lg peer-checked:border-blue-500 peer-checked:bg-blue-900/20 transition-all">
                                    <div class="flex items-center gap-3">
                                        <div class="w-12 h-12 bg-gray-800 rounded-lg flex items-center justify-center">
                                            <i class="fas fa-moon text-gray-400 text-xl"></i>
                                        </div>
                                        <div>
                                            <p class="text-white font-semibold">Dark Theme</p>
                                            <p class="text-xs text-gray-400">Dark form with light text</p>
                                        </div>
                                    </div>
                                </div>
                            </label>
                            
                            <label class="relative cursor-pointer">
                                <input type="radio" name="form_theme" value="light" 
                                       <?php echo ($store['form_theme'] ?? 'dark') === 'light' ? 'checked' : ''; ?>
                                       class="sr-only peer">
                                <div class="p-4 bg-gray-700 border-2 border-gray-600 rounded-lg peer-checked:border-blue-500 peer-checked:bg-blue-900/20 transition-all">
                                    <div class="flex items-center gap-3">
                                        <div class="w-12 h-12 bg-white/20 backdrop-blur-sm rounded-lg flex items-center justify-center border border-white/30">
                                            <i class="fas fa-sun text-yellow-400 text-xl"></i>
                                        </div>
                                        <div>
                                            <p class="text-white font-semibold">Light Theme</p>
                                            <p class="text-xs text-gray-400">Glass-like professional design</p>
                                        </div>
                                    </div>
                                </div>
                            </label>
                        </div>
                    </div>
                    
                    <div class="p-3 bg-gray-900 rounded-lg border border-gray-700">
                        <p class="text-xs text-gray-400 mb-2">Form Preview:</p>
                        <div id="form_preview" class="rounded-lg p-4 <?php echo ($store['form_theme'] ?? 'dark') === 'light' ? 'bg-white/95 backdrop-blur-sm border border-white/30' : 'bg-gray-800'; ?>">
                            <input type="text" placeholder="Sample input" 
                                   class="w-full px-3 py-2 rounded-lg border <?php echo ($store['form_theme'] ?? 'dark') === 'light' ? 'bg-white/80 backdrop-blur-sm border-gray-300/50 text-gray-900' : 'bg-gray-700 border-gray-600 text-white'; ?>"
                                   readonly>
                        </div>
                    </div>
                </div>
                
                <!-- Working Hours -->
                <div class="bg-gray-800 rounded-xl p-4 sm:p-6 border border-gray-700">
                    <h2 class="text-xl font-bold mb-4 text-white">
                        <i class="fas fa-clock mr-2"></i>Working Hours
                    </h2>
                    <p class="text-sm text-gray-400 mb-4">Set your store's working hours for each day of the week</p>
                    
                    <?php
                    // Parse existing working hours
                    $workingHours = [];
                    if (!empty($store['working_hours'])) {
                        $workingHours = json_decode($store['working_hours'], true) ?: [];
                    }
                    
                    $days = [
                        'monday' => 'Monday',
                        'tuesday' => 'Tuesday',
                        'wednesday' => 'Wednesday',
                        'thursday' => 'Thursday',
                        'friday' => 'Friday',
                        'saturday' => 'Saturday',
                        'sunday' => 'Sunday'
                    ];
                    ?>
                    
                    <div class="space-y-3">
                        <?php foreach ($days as $dayKey => $dayName): ?>
                        <?php
                        $dayHours = $workingHours[$dayKey] ?? ['enabled' => 0, 'open' => '08:00', 'close' => '17:00'];
                        ?>
                        <div class="bg-gray-900 rounded-lg p-3 sm:p-4 border border-gray-700">
                            <div class="flex flex-col sm:flex-row sm:items-center gap-3 sm:gap-4">
                                <div class="flex items-center gap-2 w-full sm:w-auto sm:min-w-[120px]">
                                    <input type="checkbox" 
                                           name="working_hours[<?php echo $dayKey; ?>][enabled]" 
                                           value="1"
                                           id="wh_<?php echo $dayKey; ?>_enabled"
                                           <?php echo $dayHours['enabled'] ? 'checked' : ''; ?>
                                           class="w-5 h-5 sm:w-4 sm:h-4 rounded border-gray-600 bg-gray-700 text-blue-600 focus:ring-blue-500 flex-shrink-0">
                                    <label for="wh_<?php echo $dayKey; ?>_enabled" class="text-white font-medium cursor-pointer text-sm sm:text-base">
                                        <?php echo $dayName; ?>
                                    </label>
                                </div>
                                
                                <div class="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-2 flex-1 w-full sm:w-auto">
                                    <div class="flex items-center gap-2 flex-1 sm:flex-initial">
                                        <label class="text-xs sm:text-sm text-gray-400 whitespace-nowrap">Open:</label>
                                        <input type="time" 
                                               name="working_hours[<?php echo $dayKey; ?>][open]" 
                                               value="<?php echo htmlspecialchars($dayHours['open']); ?>"
                                               class="bg-gray-700 text-white px-2 sm:px-3 py-2 rounded-lg border border-gray-600 flex-1 sm:flex-initial sm:min-w-[100px] text-sm sm:text-base"
                                               <?php echo $dayHours['enabled'] ? '' : 'disabled'; ?>>
                                    </div>
                                    
                                    <div class="flex items-center gap-2 flex-1 sm:flex-initial">
                                        <label class="text-xs sm:text-sm text-gray-400 whitespace-nowrap">Close:</label>
                                        <input type="time" 
                                               name="working_hours[<?php echo $dayKey; ?>][close]" 
                                               value="<?php echo htmlspecialchars($dayHours['close']); ?>"
                                               class="bg-gray-700 text-white px-2 sm:px-3 py-2 rounded-lg border border-gray-600 flex-1 sm:flex-initial sm:min-w-[100px] text-sm sm:text-base"
                                               <?php echo $dayHours['enabled'] ? '' : 'disabled'; ?>>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    
                    <p class="text-xs text-gray-500 mt-4">
                        <i class="fas fa-info-circle mr-1"></i>
                        Enable each day and set the opening and closing times. Disabled days will be shown as closed.
                    </p>
                </div>
                
                <!-- Submit Buttons -->
                <div class="flex justify-between gap-3">
                    <button type="submit" name="reset_to_default" value="1" 
                            onclick="return confirm('Are you sure you want to reset all customization settings to default values? This cannot be undone.');"
                            class="px-6 py-3 bg-gray-600 hover:bg-gray-700 text-white rounded-lg font-medium transition">
                        <i class="fas fa-undo mr-2"></i>Reset to Default
                    </button>
                    <button type="submit" class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white rounded-lg font-medium transition">
                        <i class="fas fa-save mr-2"></i>Save Customization
                    </button>
                </div>
            </form>
        </div>
    </div>
    
    <script>
        // Hero color picker synchronization
        const heroColor1 = document.getElementById('hero_color_1');
        const heroColor1Text = document.getElementById('hero_color_1_text');
        const heroColor2 = document.getElementById('hero_color_2');
        const heroColor2Text = document.getElementById('hero_color_2_text');
        const heroPreview = document.getElementById('hero_preview');
        
        function updateHeroPreview() {
            const color1 = heroColor1.value;
            const color2 = heroColor2.value;
            heroPreview.style.background = `linear-gradient(135deg, ${color1} 0%, ${color2} 100%)`;
        }
        
        if (heroColor1 && heroColor1Text) {
            heroColor1.addEventListener('input', function() {
                heroColor1Text.value = this.value;
                updateHeroPreview();
            });
            heroColor1Text.addEventListener('input', function() {
                if (/^#[0-9A-Fa-f]{6}$/.test(this.value)) {
                    heroColor1.value = this.value;
                    updateHeroPreview();
                }
            });
        }
        
        if (heroColor2 && heroColor2Text) {
            heroColor2.addEventListener('input', function() {
                heroColor2Text.value = this.value;
                updateHeroPreview();
            });
            heroColor2Text.addEventListener('input', function() {
                if (/^#[0-9A-Fa-f]{6}$/.test(this.value)) {
                    heroColor2.value = this.value;
                    updateHeroPreview();
                }
            });
        }
        
        // Button color picker synchronization
        const buttonColor = document.getElementById('button_color');
        const buttonColorText = document.getElementById('button_color_text');
        const buttonHoverColor = document.getElementById('button_hover_color');
        const buttonHoverColorText = document.getElementById('button_hover_color_text');
        const buttonPreview = document.getElementById('button_preview');
        
        function updateButtonPreview() {
            buttonPreview.style.backgroundColor = buttonColor.value;
        }
        
        if (buttonColor && buttonColorText) {
            buttonColor.addEventListener('input', function() {
                buttonColorText.value = this.value;
                updateButtonPreview();
            });
            buttonColorText.addEventListener('input', function() {
                if (/^#[0-9A-Fa-f]{6}$/.test(this.value)) {
                    buttonColor.value = this.value;
                    updateButtonPreview();
                }
            });
        }
        
        if (buttonHoverColor && buttonHoverColorText) {
            buttonHoverColor.addEventListener('input', function() {
                buttonHoverColorText.value = this.value;
            });
            buttonHoverColorText.addEventListener('input', function() {
                if (/^#[0-9A-Fa-f]{6}$/.test(this.value)) {
                    buttonHoverColor.value = this.value;
                }
            });
        }
        
        // Background color picker synchronization
        const backgroundColor = document.getElementById('background_color');
        const backgroundColorText = document.getElementById('background_color_text');
        const backgroundPreview = document.getElementById('background_preview');
        
        function updateBackgroundPreview() {
            const bgColor = backgroundColor.value;
            backgroundPreview.style.background = `linear-gradient(180deg, ${bgColor} 0%, ${bgColor} 100%)`;
        }
        
        if (backgroundColor && backgroundColorText) {
            backgroundColor.addEventListener('input', function() {
                backgroundColorText.value = this.value;
                updateBackgroundPreview();
            });
            backgroundColorText.addEventListener('input', function() {
                if (/^#[0-9A-Fa-f]{6}$/.test(this.value)) {
                    backgroundColor.value = this.value;
                    updateBackgroundPreview();
                }
            });
        }
        
        // Form theme preview update
        const formThemeInputs = document.querySelectorAll('input[name="form_theme"]');
        const formPreview = document.getElementById('form_preview');
        const formPreviewInput = formPreview ? formPreview.querySelector('input') : null;
        
        formThemeInputs.forEach(input => {
            input.addEventListener('change', function() {
                if (formPreview) {
                    if (this.value === 'light') {
                        formPreview.className = 'rounded-lg p-4 bg-white/95 backdrop-blur-sm border border-white/30';
                        if (formPreviewInput) {
                            formPreviewInput.className = 'w-full px-3 py-2 rounded-lg border bg-white/80 backdrop-blur-sm border-gray-300/50 text-gray-900';
                        }
                    } else {
                        formPreview.className = 'rounded-lg p-4 bg-gray-800';
                        if (formPreviewInput) {
                            formPreviewInput.className = 'w-full px-3 py-2 rounded-lg border bg-gray-700 border-gray-600 text-white';
                        }
                    }
                }
            });
        });
        
        // Update form submission to use color picker values
        document.querySelector('form').addEventListener('submit', function(e) {
            if (buttonColor) {
                this.querySelector('input[name="button_color"]').value = buttonColor.value;
            }
            if (buttonHoverColor) {
                this.querySelector('input[name="button_hover_color"]').value = buttonHoverColor.value;
            }
            if (heroColor1) {
                this.querySelector('input[name="hero_color_1"]').value = heroColor1.value;
            }
            if (heroColor2) {
                this.querySelector('input[name="hero_color_2"]').value = heroColor2.value;
            }
            if (backgroundColor) {
                this.querySelector('input[name="background_color"]').value = backgroundColor.value;
            }
        });
        
        // Enable/disable time inputs based on checkbox
        document.querySelectorAll('input[type="checkbox"][id^="wh_"]').forEach(function(checkbox) {
            checkbox.addEventListener('change', function() {
                const dayKey = this.id.replace('wh_', '').replace('_enabled', '');
                const openInput = document.querySelector(`input[name="working_hours[${dayKey}][open]"]`);
                const closeInput = document.querySelector(`input[name="working_hours[${dayKey}][close]"]`);
                
                if (openInput && closeInput) {
                    if (this.checked) {
                        openInput.disabled = false;
                        closeInput.disabled = false;
                    } else {
                        openInput.disabled = true;
                        closeInput.disabled = true;
                    }
                }
            });
        });
        
        // Mobile menu toggle
        document.getElementById('mobileMenuBtn').addEventListener('click', function() {
            const menu = document.getElementById('mobileMenu');
            menu.classList.toggle('hidden');
        });
    </script>
</body>
</html>

