<?php
// app/View/Components/TinyMCE.php - FIXED VERSION WITH DYNAMIC DIRECTION

namespace App\View\Components;

use Illuminate\View\Component;

class TinyMCE extends Component
{
    public $name;
    public $value;
    public $height;
    public $required;
    public $placeholder;
    public $plugins;
    public $toolbar;
    public $config;
    public $locale;
    public $direction;
    public $language;
    public $uniqueId;

    /**
     * Create a new component instance.
     *
     * @return void
     */
    public function __construct(
        $name = 'content',
        $value = '',
        $height = 400,
        $required = false,
        $placeholder = null,
        $plugins = null,
        $toolbar = null,
        $config = [],
        $locale = null,
        $direction = null,
        $language = null
    ) {
        $this->name = $name;
        $this->value = old($name, $value);
        $this->height = $height;
        $this->required = $required;
        
        // Dynamic placeholder using admin_trans
        $this->placeholder = $placeholder ?: admin_trans('enter_content');
        
        // Auto-detect locale and direction from current app settings
        $this->locale = $locale ?: app()->getLocale();
        
        // FIXED: Enhanced RTL detection with better logic
        $isRTL = $direction === 'rtl' || 
                 in_array($this->locale, ['ar', 'he', 'fa', 'ur']) ||
                 (function_exists('get_current_direction') && get_current_direction() === 'rtl') ||
                 (session('direction') === 'rtl') ||
                 (config('app.direction') === 'rtl');
                 
        $this->direction = $direction ?: ($isRTL ? 'rtl' : 'ltr');
        $this->language = $language ?: ($this->direction === 'rtl' ? 'ar' : 'en');
        
        // Generate unique ID to prevent conflicts
        $this->uniqueId = 'tinymce_' . uniqid() . '_' . str_replace(['[', ']', '.'], '_', $name);
        
        // Default plugins with security focus - Enhanced for multi-language
        $this->plugins = $plugins ?: [
            'lists', 'link', 'paste', 'searchreplace', 
            'visualblocks', 'code', 'fullscreen', 'help', 'wordcount',
            'directionality' // Added for dynamic direction support
        ];
        
        // FIXED: Dynamic toolbar based on current direction with proper alignment
        $alignmentTools = $this->direction === 'rtl' 
            ? 'alignright aligncenter alignleft alignjustify'
            : 'alignleft aligncenter alignright alignjustify';
        
        $toolbarItems = [
            'undo redo',
            'styles',
            'fontsize',
            'bold italic underline',
            'forecolor backcolor',
            $alignmentTools,
            'bullist numlist',
            'link',
            'ltr rtl', // Direction toggle buttons
            'code fullscreen help'
        ];
        
        $this->toolbar = $toolbar ?: implode(' | ', $toolbarItems);
        $this->config = $config;
    }

    /**
     * Get raw content without any processing
     */
    public function getRawValue()
    {
        return $this->value;
    }

    /**
     * FIXED: Process content - prevent auto-paragraph wrapping
     */
    public function getProcessedValue()
    {
        if (empty($this->value)) {
            return '';
        }

        $content = $this->value;
        
        // ONLY basic security cleaning - NO content manipulation
        $content = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $content);
        $content = preg_replace('/on\w+="[^"]*"/i', '', $content);
        $content = preg_replace('/on\w+=\'[^\']*\'/i', '', $content);
        $content = preg_replace('/javascript:/i', '', $content);
        $content = preg_replace('/vbscript:/i', '', $content);
        
        return trim($content);
    }

    /**
     * Get dynamic translations with RTL support
     */
    public function getTranslations()
    {
        return [
            'loading_editor' => admin_trans('loading_editor'),
            'enter_content' => admin_trans('enter_content'),
            'bold' => admin_trans('bold'),
            'italic' => admin_trans('italic'),
            'underline' => admin_trans('underline'),
            'align_left' => admin_trans('align_left'),
            'align_center' => admin_trans('align_center'),
            'align_right' => admin_trans('align_right'),
            'align_justify' => admin_trans('align_justify'),
            'bullet_list' => admin_trans('bullet_list'),
            'numbered_list' => admin_trans('numbered_list'),
            'link' => admin_trans('link'),
            'code' => admin_trans('code'),
            'fullscreen' => admin_trans('fullscreen'),
            'help' => admin_trans('help'),
            'heading_main' => admin_trans('heading_main'),
            'heading_sub' => admin_trans('heading_sub'),
            'heading_small' => admin_trans('heading_small'),
            'paragraph' => admin_trans('paragraph'),
            'highlighted_text' => admin_trans('highlighted_text'),
            'left_to_right' => admin_trans('left_to_right'),
            'right_to_left' => admin_trans('right_to_left'),
        ];
    }

    /**
     * Check if current locale is RTL
     */
    public function isRTL()
    {
        return $this->direction === 'rtl';
    }

    /**
     * Get direction-aware CSS classes
     */
    public function getDirectionClasses()
    {
        return $this->isRTL() ? 'rtl text-right' : 'ltr text-left';
    }

    /**
     * Get content with proper direction attributes
     */
    public function getContentWithDirection()
    {
        $content = $this->getProcessedValue();
        
        // Add direction attribute to content if not present
        if (!empty($content) && !preg_match('/dir\s*=/', $content)) {
            // Wrap content in div with proper direction if it doesn't have direction set
            $direction = $this->direction;
            $content = "<div dir=\"{$direction}\">{$content}</div>";
        }
        
        return $content;
    }

    /**
     * Get toolbar configuration based on direction
     */
    public function getToolbarConfig()
    {
        if ($this->toolbar) {
            return $this->toolbar;
        }

        // Dynamic toolbar based on direction
        $alignmentTools = $this->direction === 'rtl' 
            ? 'alignright aligncenter alignleft alignjustify'
            : 'alignleft aligncenter alignright alignjustify';
        
        $toolbarItems = [
            'undo redo',
            'styles',
            'fontsize',
            'bold italic underline',
            'forecolor backcolor',
            $alignmentTools,
            'bullist numlist',
            'link',
            'ltr rtl', // Direction toggle buttons
            'code fullscreen help'
        ];
        
        return implode(' | ', $toolbarItems);
    }

    /**
     * Get editor configuration array
     */
    public function getEditorConfig()
    {
        $baseConfig = [
            'height' => $this->height,
            'direction' => $this->direction,
            'language' => $this->language,
            'locale' => $this->locale,
            'plugins' => $this->plugins,
            'toolbar' => $this->getToolbarConfig(),
            'required' => $this->required,
            'placeholder' => $this->placeholder,
        ];

        return array_merge($baseConfig, $this->config);
    }

    /**
     * Get unique editor ID
     */
    public function getUniqueId()
    {
        return $this->uniqueId;
    }

    /**
     * Get the view / contents that represent the component.
     *
     * @return \Illuminate\Contracts\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.tinymce');
    }
}