<?php

namespace App\Models;

class Form
{
    public $id;
    public $name;
    public $fields;
    public $created_at;

    public function __construct($data = [])
    {
        $this->id = $data['id'] ?? null;
        $this->name = $data['name'] ?? '';
        $this->fields = isset($data['fields']) ? json_decode($data['fields'], true) : [];
        $this->created_at = $data['created_at'] ?? date('Y-m-d H:i:s');
    }

    /**
     * Generate complete embed code for the form
     */
    public function generateEmbedCode(): string
    {
        $baseUrl = $this->getBaseUrl();
        $formUrl = $this->getFormUrl($baseUrl);
        $formAttributes = $this->getFormAttributes();

        $html = $this->buildFormHeader();
        $html .= $this->buildHiddenFields();
        $html .= $this->generateFields();
        $html .= $this->buildSubmitButton();
        $html .= $this->buildFormFooter();
        $html .= $this->buildJavaScript($formUrl);

        return $html;
    }

    /**
     * Get base URL for form actions
     */
    private function getBaseUrl(): string
    {
        return "http://" . $_SERVER['HTTP_HOST'] . "/lead-management/public";
    }

    /**
     * Get form submission URL
     */
    private function getFormUrl(string $baseUrl): string
    {
        return $baseUrl . "/api/lead?form_id=" . $this->id;
    }

    /**
     * Get form attributes (like enctype for file uploads)
     */
    private function getFormAttributes(): string
    {
        $hasFileUpload = $this->hasFileUploadField();
        return $hasFileUpload ? 'enctype="multipart/form-data"' : '';
    }

    /**
     * Check if form contains any file upload fields
     */
    private function hasFileUploadField(): bool
    {
        foreach ($this->fields as $field) {
            if ($field['type'] === 'file') {
                return true;
            }
        }
        return false;
    }

    /**
     * Build form header HTML
     */
    private function buildFormHeader(): string
    {
        $formAttributes = $this->getFormAttributes();
        return '<!-- LeadManager AI Form: ' . $this->name . ' -->
<form action="#" method="POST" ' . $formAttributes . ' class="lmai-form" id="lmai-form-' . $this->id . '">';
    }

    /**
     * Build hidden form fields
     */
    private function buildHiddenFields(): string
    {
        return '
    <input type="hidden" name="form_id" value="' . $this->id . '">';
    }

    /**
     * Build submit button
     */
    private function buildSubmitButton(): string
    {
        return '
    <div class="lmai-submit-container">
        <button type="submit" class="lmai-submit-btn" id="lmai-submit-' . $this->id . '">
            <span class="btn-text">Submit</span>
            <span class="btn-loading" style="display: none;">Sending...</span>
        </button>
        <div class="lmai-message" id="lmai-message-' . $this->id . '" style="display: none;"></div>
    </div>';
    }

    /**
     * Build form footer
     */
    private function buildFormFooter(): string
    {
        return '
</form>';
    }

    /**
     * Generate all form fields
     */
    private function generateFields(): string
    {
        if (empty($this->fields)) {
            return '
    <div class="lmai-no-fields">No fields configured for this form.</div>';
        }

        $html = '';
        foreach ($this->fields as $field) {
            $html .= $this->generateField($field);
        }
        return $html;
    }

    /**
     * Generate individual form field
     */
    private function generateField(array $field): string
    {
        $name = htmlspecialchars($field['name']);
        $label = htmlspecialchars($field['label']);
        $type = htmlspecialchars($field['type']);
        $required = $this->isFieldRequired($field);
        $fieldId = 'lmai-' . $this->id . '-' . $name;

        $html = '
    <div class="lmai-field">';
        $html .= $this->generateFieldLabel($label, $fieldId);
        $html .= $this->generateFieldInput($field, $name, $type, $required, $fieldId);
        $html .= '
    </div>';

        return $html;
    }

    /**
     * Generate field label
     */
    private function generateFieldLabel(string $label, string $fieldId): string
    {
        return '
        <label for="' . $fieldId . '">' . $label . '</label>';
    }

    /**
     * Generate appropriate input based on field type
     */
    private function generateFieldInput(array $field, string $name, string $type, string $required, string $fieldId): string
    {
        switch ($type) {
            case 'textarea':
                return $this->generateTextarea($name, $required, $fieldId);

            case 'select':
                return $this->generateSelect($field, $name, $required, $fieldId);

            case 'file':
                return $this->generateFileInput($field, $name, $required, $fieldId);

            default:
                return $this->generateBasicInput($name, $type, $required, $fieldId);
        }
    }

    /**
     * Generate textarea field
     */
    private function generateTextarea(string $name, string $required, string $fieldId): string
    {
        return '
        <textarea name="' . $name . '" id="' . $fieldId . '" ' . $required . ' rows="4"></textarea>';
    }

    /**
     * Generate select dropdown
     */
    private function generateSelect(array $field, string $name, string $required, string $fieldId): string
    {
        $html = '
        <select name="' . $name . '" id="' . $fieldId . '" ' . $required . '>';

        if (isset($field['options']) && is_array($field['options'])) {
            foreach ($field['options'] as $option) {
                $optionValue = htmlspecialchars($option);
                $html .= '
            <option value="' . $optionValue . '">' . $optionValue . '</option>';
            }
        }

        $html .= '
        </select>';
        return $html;
    }

    /**
     * Generate file input
     */
    private function generateFileInput(array $field, string $name, string $required, string $fieldId): string
    {
        $accept = isset($field['accept']) ? ' accept="' . htmlspecialchars($field['accept']) . '"' : '';
        return '
        <input type="file" name="' . $name . '" id="' . $fieldId . '" ' . $required . $accept . '>';
    }

    /**
     * Generate basic input field
     */
    private function generateBasicInput(string $name, string $type, string $required, string $fieldId): string
    {
        return '
        <input type="' . $type . '" name="' . $name . '" id="' . $fieldId . '" ' . $required . '>';
    }

    /**
     * Check if field is required
     */
    private function isFieldRequired(array $field): string
    {
        return (isset($field['required']) && $field['required']) ? 'required' : '';
    }

    /**
     * Build JavaScript for form handling
     */
    private function buildJavaScript(string $formUrl): string
    {
        return '

<script>
document.addEventListener("DOMContentLoaded", function() {
    const form = document.getElementById("lmai-form-' . $this->id . '");
    const submitBtn = document.getElementById("lmai-submit-' . $this->id . '");
    const messageDiv = document.getElementById("lmai-message-' . $this->id . '");
    const btnText = submitBtn.querySelector(".btn-text");
    const btnLoading = submitBtn.querySelector(".btn-loading");
    
    form.addEventListener("submit", async function(e) {
        e.preventDefault();
        await handleFormSubmission(this);
    });
    
    async function handleFormSubmission(form) {
        // Show loading state
        setLoadingState(true);
        
        try {
            const formData = new FormData(form);
            const response = await fetch("' . $formUrl . '", {
                method: "POST",
                body: formData
            });
            
            const result = await response.json();
            
            if (result.success) {
                showMessage("Thank you! Your submission has been received.", "success");
                form.reset();
            } else {
                showMessage("Error: " + (result.error || "Submission failed"), "error");
            }
        } catch (error) {
            console.error("Form submission error:", error);
            showMessage("Network error: Please check your connection and try again.", "error");
        } finally {
            setLoadingState(false);
        }
    }
    
    function setLoadingState(loading) {
        submitBtn.disabled = loading;
        btnText.style.display = loading ? "none" : "inline";
        btnLoading.style.display = loading ? "inline" : "none";
    }
    
    function showMessage(text, type) {
        messageDiv.textContent = text;
        messageDiv.className = "lmai-message " + type;
        messageDiv.style.display = "block";
        
        // Auto-hide success messages
        if (type === "success") {
            setTimeout(() => {
                messageDiv.style.display = "none";
            }, 5000);
        }
    }
});
</script>';
    }
}
