<?php

use Livewire\Volt\Component;
use Illuminate\Support\Facades\Config;
use Livewire\Attributes\Title;

new #[Title('Attachment Settings')] class extends Component {
    // Global settings
    public $enabled = true;
    public $max_file_size_mb = 10;
    public $max_files_per_ticket = 10;
    public $storage_quota_mb = 100;
    public $require_virus_scan = false;
    public $enable_thumbnails = true;
    public $thumbnail_width = 200;
    public $thumbnail_height = 200;
    public $signed_url_expiration_minutes = 60;
    public $retention_days = 30;
    public $extract_email_attachments = true;
    public $max_email_attachment_size_mb = 25;

    // File type settings
    public $allowedTypes = '';
    public $blockedTypes = '';

    public $showSuccess = false;

    public function mount(): void
    {
        $this->loadSettings();
    }

    public function loadSettings(): void
    {
        $this->enabled = config('attachments.enabled', true);
        $this->max_file_size_mb = config('attachments.max_file_size_mb', 10);
        $this->max_files_per_ticket = config('attachments.max_files_per_ticket', 10);
        $this->storage_quota_mb = config('attachments.storage_quota_mb', 100);
        $this->require_virus_scan = config('attachments.require_virus_scan', false);
        $this->enable_thumbnails = config('attachments.enable_thumbnails', true);
        $this->thumbnail_width = config('attachments.thumbnail_width', 200);
        $this->thumbnail_height = config('attachments.thumbnail_height', 200);
        $this->signed_url_expiration_minutes = config('attachments.signed_url_expiration_minutes', 60);
        $this->retention_days = config('attachments.retention_days', 30);
        $this->extract_email_attachments = config('attachments.extract_email_attachments', true);
        $this->max_email_attachment_size_mb = config('attachments.max_email_attachment_size_mb', 25);

        // Load file types as comma-separated strings
        $allowed = config('attachments.allowed_file_types', []);
        $this->allowedTypes = is_array($allowed) ? implode(', ', array_filter($allowed, fn($t) => !str_contains($t, '/'))) : '';

        $blocked = config('attachments.blocked_file_types', []);
        $this->blockedTypes = is_array($blocked) ? implode(', ', array_filter($blocked, fn($t) => !str_contains($t, '/'))) : '';
    }

    public function save(): void
    {
        $this->validate([
            'enabled' => 'boolean',
            'max_file_size_mb' => 'required|integer|min:1|max:1024',
            'max_files_per_ticket' => 'required|integer|min:1|max:100',
            'storage_quota_mb' => 'required|integer|min:10|max:10240',
            'require_virus_scan' => 'boolean',
            'enable_thumbnails' => 'boolean',
            'thumbnail_width' => 'required|integer|min:50|max:500',
            'thumbnail_height' => 'required|integer|min:50|max:500',
            'signed_url_expiration_minutes' => 'required|integer|min:5|max:1440',
            'retention_days' => 'required|integer|min:0|max:365',
            'extract_email_attachments' => 'boolean',
            'max_email_attachment_size_mb' => 'required|integer|min:1|max:100',
            'allowedTypes' => 'nullable|string',
            'blockedTypes' => 'nullable|string',
        ]);

        // Update .env file or configuration
        $this->updateEnvFile([
            'ATTACHMENTS_ENABLED' => $this->enabled ? 'true' : 'false',
            'ATTACHMENTS_MAX_FILE_SIZE_MB' => $this->max_file_size_mb,
            'ATTACHMENTS_MAX_FILES_PER_TICKET' => $this->max_files_per_ticket,
            'ATTACHMENTS_STORAGE_QUOTA_MB' => $this->storage_quota_mb,
            'ATTACHMENTS_REQUIRE_VIRUS_SCAN' => $this->require_virus_scan ? 'true' : 'false',
            'ATTACHMENTS_ENABLE_THUMBNAILS' => $this->enable_thumbnails ? 'true' : 'false',
            'ATTACHMENTS_THUMBNAIL_WIDTH' => $this->thumbnail_width,
            'ATTACHMENTS_THUMBNAIL_HEIGHT' => $this->thumbnail_height,
            'ATTACHMENTS_SIGNED_URL_EXPIRATION' => $this->signed_url_expiration_minutes,
            'ATTACHMENTS_RETENTION_DAYS' => $this->retention_days,
            'ATTACHMENTS_EXTRACT_EMAIL' => $this->extract_email_attachments ? 'true' : 'false',
            'ATTACHMENTS_MAX_EMAIL_SIZE_MB' => $this->max_email_attachment_size_mb,
        ]);

        // Clear config cache
        \Artisan::call('config:clear');

        $this->showSuccess = true;
        $this->dispatch('saved');
    }

    private function updateEnvFile(array $data): void
    {
        $envPath = base_path('.env');

        if (!file_exists($envPath)) {
            return;
        }

        $envContent = file_get_contents($envPath);

        foreach ($data as $key => $value) {
            // Escape special characters in value
            $value = is_bool($value) ? ($value ? 'true' : 'false') : $value;

            // Check if key exists
            if (preg_match("/^{$key}=/m", $envContent)) {
                // Update existing key
                $envContent = preg_replace(
                    "/^{$key}=.*/m",
                    "{$key}={$value}",
                    $envContent
                );
            } else {
                // Add new key at the end
                $envContent .= "\n{$key}={$value}";
            }
        }

        file_put_contents($envPath, $envContent);
    }

    public function resetToDefaults(): void
    {
        $this->enabled = true;
        $this->max_file_size_mb = 10;
        $this->max_files_per_ticket = 10;
        $this->storage_quota_mb = 100;
        $this->require_virus_scan = false;
        $this->enable_thumbnails = true;
        $this->thumbnail_width = 200;
        $this->thumbnail_height = 200;
        $this->signed_url_expiration_minutes = 60;
        $this->retention_days = 30;
        $this->extract_email_attachments = true;
        $this->max_email_attachment_size_mb = 25;
        $this->allowedTypes = '';
        $this->blockedTypes = 'exe, bat, cmd, com, sh, php, asp, aspx, dll, vbs';
    }

    public function checkClamAVStatus(): array
    {
        // Check if ClamAV socket exists
        $socketPath = config('attachments.clamav_socket', '/var/run/clamav/clamd.sock');
        $socketExists = file_exists($socketPath);

        // Check if clamscan command is available
        $clamscanAvailable = false;
        if (function_exists('shell_exec') && !in_array('shell_exec', explode(',', ini_get('disable_functions')))) {
            $output = shell_exec('which clamscan 2>/dev/null');
            $clamscanAvailable = !empty(trim($output));
        }

        // Try to connect to ClamAV daemon
        $daemonRunning = false;
        if ($socketExists) {
            $socket = @fsockopen('unix://' . $socketPath, -1, $errno, $errstr, 1);
            if ($socket) {
                $daemonRunning = true;
                fclose($socket);
            }
        }

        return [
            'installed' => $socketExists || $clamscanAvailable,
            'running' => $daemonRunning,
            'socket_path' => $socketPath,
            'socket_exists' => $socketExists,
            'clamscan_available' => $clamscanAvailable,
        ];
    }

    public function getStorageStats(): array
    {
        $totalBytes = \App\Models\Attachment::sum('size');
        $totalFiles = \App\Models\Attachment::count();

        return [
            'total_size' => \App\Services\AttachmentService::formatBytes($totalBytes),
            'total_files' => number_format($totalFiles),
            'total_bytes' => $totalBytes,
        ];
    }
}; ?>

<div>
    <style>
        /* Scope checkbox styling to attachment settings only */
        #attachment-settings-form {
            --color-accent: #6366f1 !important;
            --color-accent-content: #6366f1 !important;
        }

        /* Make checkboxes indigo - consistent with Ticaga styling */
        #attachment-settings-form input[type="checkbox"],
        #attachment-settings-form input[type="checkbox"].fi-checkbox-input,
        #attachment-settings-form [data-flux-checkbox] input[type="checkbox"],
        #attachment-settings-form ui-checkbox input[type="checkbox"] {
            accent-color: #6366f1 !important;
            color: #6366f1 !important;
            width: 20px !important;
            height: 20px !important;
            min-width: 20px !important;
            min-height: 20px !important;
            cursor: pointer !important;
            border-radius: 4px !important;
        }

        /* Thicker border for unchecked checkboxes */
        #attachment-settings-form input[type="checkbox"]:not(:checked),
        #attachment-settings-form input[type="checkbox"].fi-checkbox-input:not(:checked),
        #attachment-settings-form [data-flux-checkbox] input[type="checkbox"]:not(:checked),
        #attachment-settings-form ui-checkbox input[type="checkbox"]:not(:checked) {
            border: 1.5px solid #d1d5db !important;
        }

        /* Target Flux checkbox wrapper for consistent styling */
        #attachment-settings-form [data-flux-checkbox],
        #attachment-settings-form ui-checkbox {
            opacity: 1 !important;
            --color-accent: #6366f1 !important;
        }

        /* Ensure checked state shows indigo */
        #attachment-settings-form input[type="checkbox"]:checked,
        #attachment-settings-form input[type="checkbox"]:checked::before,
        #attachment-settings-form [data-flux-checkbox] input[type="checkbox"]:checked,
        #attachment-settings-form ui-checkbox input[type="checkbox"]:checked {
            background-color: #6366f1 !important;
            border-color: #6366f1 !important;
        }

        /* Override Flux's default checkbox colors */
        #attachment-settings-form [data-flux-checkbox]:has(input:checked) {
            --color-accent: #6366f1 !important;
        }
    </style>

    <section class="w-full" id="attachment-settings-form">
        @include('partials.settings-heading')

    <x-settings.layout
        :heading="__('Attachment Settings')"
        :subheading="__('Configure global file attachment settings for Ticaga')"
        :fullWidth="true">

        {{-- Department Overrides Info --}}
        <div class="mb-6 p-4 rounded-lg bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800">
            <div class="flex items-start gap-3">
                <svg class="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd"/>
                </svg>
                <div class="flex-1">
                    <h3 class="text-sm font-semibold text-blue-900 dark:text-blue-200 mb-1">
                        Department-Specific Settings
                    </h3>
                    <p class="text-sm text-blue-800 dark:text-blue-300">
                        You can override these global settings on a per-department basis. Go to <strong>Departments → Edit Department</strong> to configure department-specific attachment settings. Department settings take precedence over global settings.
                    </p>
                </div>
            </div>
        </div>

        <flux:card class="max-w-none">
            @if($showSuccess)
                <div class="mb-4 p-4 rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800">
                    <p class="text-sm font-medium text-green-800 dark:text-green-200">
                        Settings saved successfully! Configuration cache has been cleared.
                    </p>
                </div>
            @endif

            <form wire:submit="save" class="space-y-6">
                {{-- Master Toggle --}}
                <flux:fieldset>
                    <flux:legend>General Settings</flux:legend>

                    <flux:field>
                        <flux:checkbox wire:model="enabled" label="Enable File Attachments" />
                        <flux:description>Master toggle for file attachment functionality system-wide</flux:description>
                    </flux:field>
                </flux:fieldset>

                {{-- File Size & Limits --}}
                <flux:fieldset>
                    <flux:legend>File Limits</flux:legend>

                    <flux:field>
                        <flux:label>Maximum File Size (MB)</flux:label>
                        <flux:input type="number" wire:model="max_file_size_mb" min="1" max="1024" />
                        <flux:error name="max_file_size_mb" />
                        <flux:description>Maximum allowed file size per upload</flux:description>
                    </flux:field>

                    <flux:field>
                        <flux:label>Maximum Files Per Ticket</flux:label>
                        <flux:input type="number" wire:model="max_files_per_ticket" min="1" max="100" />
                        <flux:error name="max_files_per_ticket" />
                        <flux:description>Maximum number of attachments allowed per ticket</flux:description>
                    </flux:field>

                    <flux:field>
                        <flux:label>Storage Quota Per User (MB)</flux:label>
                        <flux:input type="number" wire:model="storage_quota_mb" min="10" max="10240" />
                        <flux:error name="storage_quota_mb" />
                        <flux:description>Default storage quota for each user (can be overridden per user or department)</flux:description>
                    </flux:field>
                </flux:fieldset>

                {{-- File Type Restrictions --}}
                <flux:fieldset>
                    <flux:legend>File Type Restrictions</flux:legend>

                    <flux:field>
                        <flux:label>Allowed File Types (Whitelist)</flux:label>
                        <flux:textarea wire:model="allowedTypes" rows="3" placeholder="jpg, png, pdf, doc, docx, zip..." />
                        <flux:error name="allowedTypes" />
                        <flux:description>Comma-separated list of allowed file extensions. Leave empty to allow all types (except blocked ones). Example: jpg, png, pdf, docx</flux:description>
                    </flux:field>

                    <flux:field>
                        <flux:label>Blocked File Types (Blacklist)</flux:label>
                        <flux:textarea wire:model="blockedTypes" rows="3" placeholder="exe, bat, sh, php..." />
                        <flux:error name="blockedTypes" />
                        <flux:description>Comma-separated list of blocked file extensions (recommended for security). Example: exe, bat, sh, php</flux:description>
                    </flux:field>
                </flux:fieldset>

                {{-- Security Settings --}}
                <flux:fieldset>
                    <flux:legend>Security & Scanning</flux:legend>

                    @php
                        $clamavStatus = $this->checkClamAVStatus();
                    @endphp

                    <flux:field>
                        <flux:checkbox
                            wire:model="require_virus_scan"
                            label="Require Virus Scanning"
                            :disabled="!$clamavStatus['installed']"
                        />
                        <flux:description>
                            @if(!$clamavStatus['installed'])
                                <span class="text-yellow-600 dark:text-yellow-400 font-medium">⚠️ ClamAV must be installed to enable virus scanning.</span>
                            @else
                                Enable virus scanning with ClamAV (requires ClamAV to be installed and configured)
                            @endif
                        </flux:description>
                    </flux:field>

                    {{-- ClamAV Status Indicator --}}
                    @if($require_virus_scan)
                        <div class="p-4 rounded-lg border {{ $clamavStatus['running'] ? 'bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800' : 'bg-yellow-50 dark:bg-yellow-900/20 border-yellow-200 dark:border-yellow-800' }}">
                            <div class="flex items-start gap-3">
                                @if($clamavStatus['running'])
                                    <svg class="w-5 h-5 text-green-600 dark:text-green-400 flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                                    </svg>
                                @else
                                    <svg class="w-5 h-5 text-yellow-600 dark:text-yellow-400 flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
                                    </svg>
                                @endif
                                <div class="flex-1">
                                    <p class="text-sm font-medium {{ $clamavStatus['running'] ? 'text-green-800 dark:text-green-200' : 'text-yellow-800 dark:text-yellow-200' }}">
                                        ClamAV Status: {{ $clamavStatus['running'] ? 'Running' : ($clamavStatus['installed'] ? 'Installed but not running' : 'Not installed') }}
                                    </p>
                                    <div class="mt-1 text-xs {{ $clamavStatus['running'] ? 'text-green-700 dark:text-green-300' : 'text-yellow-700 dark:text-yellow-300' }}">
                                        @if($clamavStatus['socket_exists'])
                                            <div>✓ Socket found at: <code class="bg-white/50 dark:bg-black/20 px-1 py-0.5 rounded">{{ $clamavStatus['socket_path'] }}</code></div>
                                        @endif
                                        @if($clamavStatus['clamscan_available'])
                                            <div>✓ clamscan command available</div>
                                        @endif
                                        @if(!$clamavStatus['installed'])
                                            <div class="mt-2">
                                                <strong>Installation required:</strong> Install ClamAV on your server:
                                                <ul class="mt-1 ml-4 list-disc">
                                                    <li>Ubuntu/Debian: <code class="bg-white/50 dark:bg-black/20 px-1 py-0.5 rounded">sudo apt-get install clamav clamav-daemon</code></li>
                                                    <li>macOS: <code class="bg-white/50 dark:bg-black/20 px-1 py-0.5 rounded">brew install clamav</code></li>
                                                </ul>
                                            </div>
                                        @elseif(!$clamavStatus['running'])
                                            <div class="mt-2">
                                                <strong>Service not running:</strong> Start ClamAV daemon:
                                                <ul class="mt-1 ml-4 list-disc">
                                                    <li>Ubuntu/Debian: <code class="bg-white/50 dark:bg-black/20 px-1 py-0.5 rounded">sudo systemctl start clamav-daemon</code></li>
                                                    <li>macOS: <code class="bg-white/50 dark:bg-black/20 px-1 py-0.5 rounded">brew services start clamav</code></li>
                                                </ul>
                                            </div>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endif

                    <flux:field>
                        <flux:label>Signed URL Expiration (Minutes)</flux:label>
                        <flux:input type="number" wire:model="signed_url_expiration_minutes" min="5" max="1440" />
                        <flux:error name="signed_url_expiration_minutes" />
                        <flux:description>How long download links remain valid (1440 = 24 hours)</flux:description>
                    </flux:field>
                </flux:fieldset>

                {{-- Image Settings --}}
                <flux:fieldset>
                    <flux:legend>Image Processing</flux:legend>

                    <flux:field>
                        <flux:checkbox wire:model="enable_thumbnails" label="Generate Thumbnails" />
                        <flux:description>Automatically create thumbnail previews for image attachments</flux:description>
                    </flux:field>

                    <div class="grid grid-cols-2 gap-4">
                        <flux:field>
                            <flux:label>Thumbnail Width (px)</flux:label>
                            <flux:input type="number" wire:model="thumbnail_width" min="50" max="500" />
                            <flux:error name="thumbnail_width" />
                        </flux:field>

                        <flux:field>
                            <flux:label>Thumbnail Height (px)</flux:label>
                            <flux:input type="number" wire:model="thumbnail_height" min="50" max="500" />
                            <flux:error name="thumbnail_height" />
                        </flux:field>
                    </div>
                </flux:fieldset>

                {{-- Email Attachments --}}
                <flux:fieldset>
                    <flux:legend>Email Integration</flux:legend>

                    <flux:field>
                        <flux:checkbox wire:model="extract_email_attachments" label="Extract Email Attachments" />
                        <flux:description>Automatically save attachments from incoming emails to tickets</flux:description>
                    </flux:field>

                    <flux:field>
                        <flux:label>Max Email Attachment Size (MB)</flux:label>
                        <flux:input type="number" wire:model="max_email_attachment_size_mb" min="1" max="100" />
                        <flux:error name="max_email_attachment_size_mb" />
                        <flux:description>Maximum size for attachments extracted from emails</flux:description>
                    </flux:field>
                </flux:fieldset>

                {{-- Retention Policy --}}
                <flux:fieldset>
                    <flux:legend>Retention Policy</flux:legend>

                    <flux:field>
                        <flux:label>Retention Days</flux:label>
                        <flux:input type="number" wire:model="retention_days" min="0" max="365" />
                        <flux:error name="retention_days" />
                        <flux:description>Number of days to keep soft-deleted attachments (0 = keep forever)</flux:description>
                    </flux:field>
                </flux:fieldset>

                {{-- Storage Statistics --}}
                <flux:fieldset>
                    <flux:legend>Storage Statistics</flux:legend>

                    @php
                        $stats = $this->getStorageStats();
                    @endphp

                    <div class="grid grid-cols-2 gap-4 text-sm">
                        <div>
                            <div class="text-zinc-500 dark:text-zinc-400">Total Files</div>
                            <div class="text-lg font-semibold">{{ $stats['total_files'] }}</div>
                        </div>
                        <div>
                            <div class="text-zinc-500 dark:text-zinc-400">Total Storage Used</div>
                            <div class="text-lg font-semibold">{{ $stats['total_size'] }}</div>
                        </div>
                    </div>
                </flux:fieldset>

                {{-- Action Buttons --}}
                <div class="flex items-center gap-3 pt-4">
                    <flux:button type="submit" variant="primary" class="!bg-indigo-700 hover:!bg-indigo-500 !text-white">
                        Save Settings
                    </flux:button>

                    <flux:button type="button" wire:click="resetToDefaults" variant="ghost">
                        Reset to Defaults
                    </flux:button>
                </div>
            </form>
        </flux:card>
    </x-settings.layout>
    </section>
</div>
