<?php

namespace App\Livewire;

use Livewire\Component;

class CustomFormWidget extends Component
{
    public \App\Models\CustomForm $customForm;
    public array $data = [];
    public bool $isSubmitted = false;
    public ?string $redirectUrl = null;

    public function mount($formId)
    {
        $this->customForm = \App\Models\CustomForm::findOrFail($formId);
        
        // Initialize data array to avoid undefined index errors
        if (is_array($this->customForm->fields)) {
            foreach ($this->customForm->fields as $field) {
                if (isset($field['key'])) {
                    $this->data[$field['key']] = '';
                }
            }
        }
    }

    public function submit()
    {
        if (!$this->customForm->is_active) {
            return;
        }

        // 1. Build validation rules dynamically
        $rules = [];
        $messages = [];
        
        if (is_array($this->customForm->fields)) {
            foreach ($this->customForm->fields as $field) {
                if (!isset($field['key'])) continue;
                
                $fieldRules = [];
                if (!empty($field['is_required'])) {
                    $fieldRules[] = 'required';
                    $messages['data.' . $field['key'] . '.required'] = 'حقل ' . ($field['name'] ?? 'مطلوب') . ' إلزامي.';
                } else {
                    $fieldRules[] = 'nullable';
                }

                if (($field['type'] ?? '') === 'email') {
                    $fieldRules[] = 'email';
                }
                
                $rules['data.' . $field['key']] = implode('|', $fieldRules);
            }
        }

        if (!empty($rules)) {
            $this->validate($rules, $messages);
        }

        // 2. Save Submission to DB
        $submission = \App\Models\CustomFormSubmission::create([
            'custom_form_id' => $this->customForm->id,
            'data' => $this->data,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
        ]);

        // 3. Send Email (if enabled)
        if ($this->customForm->send_email && $this->customForm->email_to) {
            try {
                $content = "تلقيت رد جديد من النموذج: {$this->customForm->name}\n\n";
                foreach ($this->customForm->fields ?? [] as $field) {
                    $key = $field['key'] ?? null;
                    if($key && isset($this->data[$key])) {
                        $content .= "{$field['name']}: {$this->data[$key]}\n";
                    }
                }
                
                \Illuminate\Support\Facades\Mail::raw($content, function ($message) {
                    $message->to($this->customForm->email_to)
                            ->subject($this->customForm->email_subject ?: 'رد جديد على النموذج');
                });
            } catch (\Exception $e) {
                // Log exception silently
                \Illuminate\Support\Facades\Log::error('Form Mail Error: ' . $e->getMessage());
            }
        }

        // 4. Send Webhook (if enabled)
        if ($this->customForm->send_webhook && $this->customForm->webhook_url) {
            try {
                \Illuminate\Support\Facades\Http::post($this->customForm->webhook_url, [
                    'form_name' => $this->customForm->name,
                    'submission_id' => $submission->id,
                    'submitted_at' => now()->toDateTimeString(),
                    'data' => $this->data,
                ]);
            } catch (\Exception $e) {
                \Illuminate\Support\Facades\Log::error('Form Webhook Error: ' . $e->getMessage());
            }
        }

        // 5. WhatsApp Redirect (if enabled)
        if ($this->customForm->send_whatsapp && $this->customForm->whatsapp_number) {
            $messageTemplate = $this->customForm->whatsapp_message_template ?? '';
            
            if (empty($messageTemplate)) {
                // Default message
                $messageTemplate = "مرحباً، أود الاستفسار بخصوص:\n";
                foreach ($this->customForm->fields ?? [] as $field) {
                    $key = $field['key'] ?? null;
                    if($key && isset($this->data[$key])) {
                        $messageTemplate .= "{$field['name']}: {$this->data[$key]}\n";
                    }
                }
            } else {
                // Parse template {key} variables
                foreach ($this->data as $key => $value) {
                    $messageTemplate = str_replace("{{$key}}", $value, $messageTemplate);
                }
            }
            
            $whatsappUrl = 'https://wa.me/' . ltrim($this->customForm->whatsapp_number, '+') . '?text=' . urlencode(trim($messageTemplate));
            $this->redirectUrl = $whatsappUrl;
        }

        $this->isSubmitted = true;
    }

    public function render()
    {
        return view('livewire.custom-form-widget');
    }
}
