<?php
namespace App\Components;

class Ajax
{
    protected string $url;
    protected string $method = 'POST';
    protected $data = [];
    protected string $target = '';
    protected ?string $onSuccess = null;
    protected ?string $onError = null;
    protected string $eventType = 'click'; // Default event

    public static function make(): self
    {
        return new self();
    }

    public function url(string $url): self
    {
        $this->url = $url;
        return $this;
    }

    public function method(string $method): self
    {
        $this->method = strtoupper($method);
        return $this;
    }

    public function data($data): self
    {
        $this->data = $data;
        return $this;
    }

    public function target(string $selector): self
    {
        $this->target = $selector;
        return $this;
    }

    public function event(string $type): self
    {
        $this->eventType = strtolower($type);
        return $this;
    }

    public function onSuccess(string $callbackJs): self
    {
        $this->onSuccess = $callbackJs;
        return $this;
    }

    public function onError(string $callbackJs): self
    {
        $this->onError = $callbackJs;
        return $this;
    }

    public function render(string $triggerSelector): string
    {
        $successJs = $this->onSuccess ?? "console.log('Success:', response);";
        $errorJs   = $this->onError   ?? "console.error('Error:', xhr.responseText);";

        // Determine how to handle data
        $dataOutput = '';

        if (is_array($this->data) && !empty($this->data)) {
            $dataJson = json_encode($this->data);
            $dataOutput = "data: {$dataJson},";
        } elseif (is_string($this->data) && trim($this->data) !== '') {
            $dataOutput = "data: {$this->data},";
        } elseif ($this->eventType === 'submit' && !empty($this->target)) {
            $dataOutput = "data: $('{$this->target}').serialize(),";
        }

        return <<<HTML
        <script>
        $(document).on('{$this->eventType}', '{$triggerSelector}', function(e) {
            e.preventDefault();
            $.ajax({
                url: '{$this->url}',
                method: '{$this->method}',
                {$dataOutput}
                success: function(response) {
                    {$successJs}
                },
                error: function(xhr) {
                    {$errorJs}
                }
            });
        });
        </script>
        HTML;
    }
}