<?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');
    }

    public function generateEmbedCode()
    {
        $url = "http://" . $_SERVER['HTTP_HOST'] . "/api/lead?form_id=" . $this->id;

        return <<<HTML
<form action="$url" method="POST">
    <input type="hidden" name="form_id" value="{$this->id}">
    {$this->generateFields()}
    <button type="submit">Submit</button>
</form>
<script>
// Simple form submission
document.querySelector('form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const formData = new FormData(e.target);
    
    try {
        const response = await fetch('$url', {
            method: 'POST',
            body: formData
        });
        const result = await response.json();
        alert(result.success ? 'Thank you!' : 'Error: ' + result.error);
    } catch (error) {
        alert('Submission failed');
    }
});
</script>
HTML;
    }

    private function generateFields()
    {
        $html = '';
        foreach ($this->fields as $field) {
            $html .= "<div>";
            $html .= "<label>{$field['label']}</label>";
            $html .= "<input type='{$field['type']}' name='{$field['name']}' required>";
            $html .= "</div>";
        }
        return $html;
    }
}
