<?php
require_once 'includes/init.php';

if (!isAuthenticated()) {
    redirect(APP_URL . '/login.php');
}

$chatUserId = sanitizeInput($_GET['user'] ?? '');
if (empty($chatUserId)) {
    redirect(APP_URL . '/chats.php');
}

$db = getDB();
$currentUserId = $_SESSION['user_id'];

// Get chat partner info
$stmt = $db->prepare("SELECT id, unique_id, name FROM users WHERE unique_id = ? AND status = 'approved'");
$stmt->execute([$chatUserId]);
$chatPartner = $stmt->fetch();

if (!$chatPartner) {
    redirect(APP_URL . '/chats.php?error=user_not_found');
}

$pageTitle = 'Chat Theme';
$activePage = 'chats';
$hideBottomNav = true;

// Handle theme update
$message = '';
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_theme') {
        // Check if theme is locked
        $stmt = $db->prepare("SELECT is_locked, locked_by FROM chat_themes WHERE user_id = ? AND chat_with_id = ?");
        $stmt->execute([$currentUserId, $chatPartner['id']]);
        $existingTheme = $stmt->fetch();
        
        if ($existingTheme && $existingTheme['is_locked']) {
            $error = 'This theme is locked and cannot be modified';
        } else {
            $themeName = sanitizeInput($_POST['theme_name'] ?? 'default');
            $backgroundColor = sanitizeInput($_POST['background_color'] ?? '#ECE5DD');
            $messageColor = sanitizeInput($_POST['message_color'] ?? '#DCF8C6');
            $textColor = sanitizeInput($_POST['text_color'] ?? '#111B21');
            $emojiSet = sanitizeInput($_POST['emoji_set'] ?? 'default');
            
            // Handle background image upload
            $backgroundImage = '';
            if (isset($_FILES['background_image']) && $_FILES['background_image']['error'] === 0) {
                $uploadDir = 'uploads/chat-backgrounds/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                
                $fileName = 'bg_' . $currentUserId . '_' . $chatPartner['id'] . '_' . time() . '.jpg';
                $targetPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['background_image']['tmp_name'], $targetPath)) {
                    $backgroundImage = $fileName;
                }
            }
            
            // Update or insert theme
            $stmt = $db->prepare("
                INSERT INTO chat_themes (user_id, chat_with_id, theme_name, background_color, message_color, text_color, emoji_set, background_image, updated_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())
                ON DUPLICATE KEY UPDATE 
                theme_name = VALUES(theme_name),
                background_color = VALUES(background_color),
                message_color = VALUES(message_color),
                text_color = VALUES(text_color),
                emoji_set = VALUES(emoji_set),
                background_image = VALUES(background_image),
                updated_at = VALUES(updated_at)
            ");
            
            $stmt->execute([
                $currentUserId, 
                $chatPartner['id'], 
                $themeName, 
                $backgroundColor, 
                $messageColor, 
                $textColor, 
                $emojiSet, 
                $backgroundImage
            ]);
            
            $message = 'Theme updated successfully!';
        }
    }
}

// Get current theme
$stmt = $db->prepare("SELECT * FROM chat_themes WHERE user_id = ? AND chat_with_id = ?");
$stmt->execute([$currentUserId, $chatPartner['id']]);
$currentTheme = $stmt->fetch();

// WhatsApp-inspired default theme colors
$whatsappThemes = [
    'whatsapp_default' => [
        'name' => 'WhatsApp Default',
        'background' => '#ECE5DD',
        'message_sent' => '#DCF8C6',
        'message_received' => '#FFFFFF',
        'text_sent' => '#111B21',
        'text_received' => '#111B21'
    ],
    'whatsapp_dark' => [
        'name' => 'WhatsApp Dark',
        'background' => '#111B21',
        'message_sent' => '#005C4B',
        'message_received' => '#1F2C36',
        'text_sent' => '#FFFFFF',
        'text_received' => '#FFFFFF'
    ],
    'whatsapp_blue' => [
        'name' => 'WhatsApp Blue',
        'background' => '#E5F3FF',
        'message_sent' => '#DCF8C6',
        'message_received' => '#FFFFFF',
        'text_sent' => '#111B21',
        'text_received' => '#111B21'
    ],
    'whatsapp_green' => [
        'name' => 'WhatsApp Green',
        'background' => '#E8F5E8',
        'message_sent' => '#DCF8C6',
        'message_received' => '#FFFFFF',
        'text_sent' => '#111B21',
        'text_received' => '#111B21'
    ]
];

include 'includes/header.php';
?>

<div class="min-h-screen bg-background-light dark:bg-background-dark">
    <div class="max-w-4xl mx-auto">
        <!-- Header -->
        <header class="bg-white dark:bg-slate-800 shadow-sm border-b border-slate-200 dark:border-slate-800">
            <div class="px-4 py-4">
                <div class="flex items-center justify-between">
                    <div>
                        <h1 class="text-xl font-bold text-slate-900 dark:text-slate-100">Chat Theme</h1>
                        <p class="text-sm text-slate-600 dark:text-slate-400">Customize chat appearance with <?php echo htmlspecialchars($chatPartner['name']); ?></p>
                    </div>
                    <a href="chat.php?user=<?php echo $chatUserId; ?>" class="px-4 py-2 bg-slate-100 dark:bg-slate-700 text-slate-700 dark:text-slate-300 rounded-lg hover:bg-slate-200 dark:hover:bg-slate-600 transition-colors">
                        <span class="material-symbols-outlined text-sm">arrow_back</span>
                        Back to Chat
                    </a>
                </div>
            </div>
        </header>

        <!-- Main Content -->
        <main class="p-6 space-y-6">
            <!-- Success/Error Messages -->
            <?php if ($message): ?>
            <div class="bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 rounded-lg p-4">
                <div class="flex items-center gap-2">
                    <span class="material-symbols-outlined text-green-600 dark:text-green-400">check_circle</span>
                    <p class="text-green-800 dark:text-green-200"><?php echo htmlspecialchars($message); ?></p>
                </div>
            </div>
            <?php endif; ?>

            <?php if ($error): ?>
            <div class="bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
                <div class="flex items-center gap-2">
                    <span class="material-symbols-outlined text-red-600 dark:text-red-400">error</span>
                    <p class="text-red-800 dark:text-red-200"><?php echo htmlspecialchars($error); ?></p>
                </div>
            </div>
            <?php endif; ?>

            <!-- WhatsApp Themes -->
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6">
                <h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">WhatsApp Themes</h2>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <?php foreach ($whatsappThemes as $key => $theme): ?>
                    <div class="border border-slate-200 dark:border-slate-700 rounded-lg p-4 hover:border-primary transition-colors cursor-pointer" onclick="applyWhatsAppTheme('<?php echo $key; ?>')">
                        <h3 class="font-medium text-slate-900 dark:text-slate-100 mb-3"><?php echo $theme['name']; ?></h3>
                        <div class="space-y-2">
                            <div class="flex items-center gap-2">
                                <div class="w-4 h-4 rounded" style="background-color: <?php echo $theme['background']; ?>"></div>
                                <span class="text-sm text-slate-600 dark:text-slate-400">Background</span>
                            </div>
                            <div class="flex items-center gap-2">
                                <div class="w-4 h-4 rounded" style="background-color: <?php echo $theme['message_sent']; ?>"></div>
                                <span class="text-sm text-slate-600 dark:text-slate-400">Sent Messages</span>
                            </div>
                            <div class="flex items-center gap-2">
                                <div class="w-4 h-4 rounded" style="background-color: <?php echo $theme['message_received']; ?>"></div>
                                <span class="text-sm text-slate-600 dark:text-slate-400">Received Messages</span>
                            </div>
                        </div>
                        <button class="mt-3 w-full px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors text-sm font-medium">
                            Apply Theme
                        </button>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Theme Form -->
            <form method="POST" class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6">
                <input type="hidden" name="action" value="update_theme">
                
                <h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">Custom Theme</h2>
                
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- Theme Name -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Theme Name</label>
                        <input type="text" name="theme_name" value="<?php echo $currentTheme['theme_name'] ?? 'default'; ?>" 
                               class="w-full px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-slate-700 dark:text-white"
                               placeholder="Enter theme name">
                    </div>
                    
                    <!-- Background Color -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Background Color</label>
                        <div class="flex gap-2">
                            <input type="color" name="background_color" value="<?php echo $currentTheme['background_color'] ?? '#ECE5DD'; ?>" 
                                   class="h-10 w-20 rounded-lg border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-slate-700">
                            <input type="text" value="<?php echo $currentTheme['background_color'] ?? '#ECE5DD'; ?>" 
                                   class="flex-1 px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-slate-700 dark:text-white"
                                   placeholder="#ECE5DD" id="bg-color-text">
                        </div>
                    </div>
                    
                    <!-- Message Color (Sent) -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Sent Message Color</label>
                        <div class="flex gap-2">
                            <input type="color" name="message_color" value="<?php echo $currentTheme['message_color'] ?? '#DCF8C6'; ?>" 
                                   class="h-10 w-20 rounded-lg border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-slate-700">
                            <input type="text" value="<?php echo $currentTheme['message_color'] ?? '#DCF8C6'; ?>" 
                                   class="flex-1 px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-slate-700 dark:text-white"
                                   placeholder="#DCF8C6" id="message-color-text">
                        </div>
                    </div>
                    
                    <!-- Text Color -->
                    <div>
                        <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Text Color</label>
                        <div class="flex gap-2">
                            <input type="color" name="text_color" value="<?php echo $currentTheme['text_color'] ?? '#111B21'; ?>" 
                                   class="h-10 w-20 rounded-lg border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-slate-700">
                            <input type="text" value="<?php echo $currentTheme['text_color'] ?? '#111B21'; ?>" 
                                   class="flex-1 px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-slate-700 dark:text-white"
                                   placeholder="#111B21" id="text-color-text">
                        </div>
                    </div>
                </div>
                
                <!-- Background Image -->
                <div class="mt-6">
                    <label class="block text-sm font-medium text-slate-700 dark:text-slate-300 mb-2">Background Image (Optional)</label>
                    <div class="flex items-center gap-4">
                        <input type="file" name="background_image" accept="image/*" 
                               class="flex-1 px-3 py-2 border border-slate-300 dark:border-slate-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-slate-700 dark:text-white">
                        <?php if ($currentTheme['background_image']): ?>
                        <div class="w-16 h-16 rounded-lg overflow-hidden border border-slate-300 dark:border-slate-600">
                            <img src="uploads/chat-backgrounds/<?php echo htmlspecialchars($currentTheme['background_image']); ?>" 
                                 alt="Background" class="w-full h-full object-cover">
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Submit Button -->
                <div class="mt-6 flex justify-end gap-3">
                    <a href="chat.php?user=<?php echo $chatUserId; ?>" class="px-4 py-2 text-slate-700 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-700 rounded-lg transition-colors">
                        Cancel
                    </a>
                    <button type="submit" class="px-6 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors font-medium">
                        Save Theme
                    </button>
                </div>
            </form>

            <!-- Theme Preview -->
            <div class="bg-white dark:bg-slate-800 rounded-xl border border-slate-200 dark:border-slate-700 p-6">
                <h2 class="text-lg font-semibold text-slate-900 dark:text-slate-100 mb-4">Theme Preview</h2>
                <div id="theme-preview" class="space-y-4">
                    <!-- Preview Messages -->
                    <div class="flex gap-3">
                        <div class="w-8 h-8 rounded-full bg-green-500 flex items-center justify-center text-white text-xs">
                            Y
                        </div>
                        <div class="flex-1">
                            <div class="bg-green-100 dark:bg-green-900/20 rounded-lg p-3 max-w-xs">
                                <p class="text-sm">This is a sent message preview</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="flex gap-3">
                        <div class="w-8 h-8 rounded-full bg-blue-500 flex items-center justify-center text-white text-xs">
                            F
                        </div>
                        <div class="flex-1">
                            <div class="bg-white dark:bg-slate-700 rounded-lg p-3 max-w-xs border border-slate-200 dark:border-slate-600">
                                <p class="text-sm">This is a received message preview</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<script>
// WhatsApp theme data
const whatsappThemes = {
    'whatsapp_default': {
        background: '#ECE5DD',
        message_sent: '#DCF8C6',
        message_received: '#FFFFFF',
        text_sent: '#111B21',
        text_received: '#111B21'
    },
    'whatsapp_dark': {
        background: '#111B21',
        message_sent: '#005C4B',
        message_received: '#1F2C36',
        text_sent: '#FFFFFF',
        text_received: '#FFFFFF'
    },
    'whatsapp_blue': {
        background: '#E5F3FF',
        message_sent: '#DCF8C6',
        message_received: '#FFFFFF',
        text_sent: '#111B21',
        text_received: '#111B21'
    },
    'whatsapp_green': {
        background: '#E8F5E8',
        message_sent: '#DCF8C6',
        message_received: '#FFFFFF',
        text_sent: '#111B21',
        text_received: '#111B21'
    }
};

// Apply WhatsApp theme
function applyWhatsAppTheme(themeKey) {
    const theme = whatsappThemes[themeKey];
    
    // Update form fields
    document.querySelector('input[name="background_color"]').value = theme.background;
    document.querySelector('input[name="message_color"]').value = theme.message_sent;
    document.querySelector('input[name="text_color"]').value = theme.text_sent;
    
    // Update text fields
    document.getElementById('bg-color-text').value = theme.background;
    document.getElementById('message-color-text').value = theme.message_sent;
    document.getElementById('text-color-text').value = theme.text_sent;
    
    // Update preview
    updatePreview();
    
    // Show success message
    const message = document.createElement('div');
    message.className = 'fixed top-4 right-4 bg-green-500 text-white px-4 py-2 rounded-lg shadow-lg z-50';
    message.innerHTML = `
        <div class="flex items-center gap-2">
            <span class="material-symbols-outlined">check_circle</span>
            <span>Theme applied! Click "Save Theme" to save changes.</span>
        </div>
    `;
    document.body.appendChild(message);
    
    setTimeout(() => {
        message.remove();
    }, 3000);
}

// Update preview
function updatePreview() {
    const bgColor = document.querySelector('input[name="background_color"]').value;
    const messageColor = document.querySelector('input[name="message_color"]').value;
    const textColor = document.querySelector('input[name="text_color"]').value;
    
    const preview = document.getElementById('theme-preview');
    preview.style.backgroundColor = bgColor;
    
    const sentMessage = preview.querySelector('.bg-green-100');
    const receivedMessage = preview.querySelector('.bg-white');
    
    sentMessage.style.backgroundColor = messageColor;
    receivedMessage.style.backgroundColor = '#FFFFFF';
    
    sentMessage.querySelector('p').style.color = textColor;
    receivedMessage.querySelector('p').style.color = textColor;
}

// Sync color inputs with text inputs
document.querySelector('input[name="background_color"]').addEventListener('input', function(e) {
    document.getElementById('bg-color-text').value = e.target.value;
    updatePreview();
});

document.getElementById('bg-color-text').addEventListener('input', function(e) {
    document.querySelector('input[name="background_color"]').value = e.target.value;
    updatePreview();
});

document.querySelector('input[name="message_color"]').addEventListener('input', function(e) {
    document.getElementById('message-color-text').value = e.target.value;
    updatePreview();
});

document.getElementById('message-color-text').addEventListener('input', function(e) {
    document.querySelector('input[name="message_color"]').value = e.target.value;
    updatePreview();
});

document.querySelector('input[name="text_color"]').addEventListener('input', function(e) {
    document.getElementById('text-color-text').value = e.target.value;
    updatePreview();
});

document.getElementById('text-color-text').addEventListener('input', function(e) {
    document.querySelector('input[name="text_color"]').value = e.target.value;
    updatePreview();
});

// Initialize preview
updatePreview();
</script>

<?php include 'includes/footer.php'; ?>
