<?php
namespace App\Components;

use Core\Component;
use Core\View;

class SweetAjax extends Component
{
    protected string $url;
    protected string $method = 'POST';
    protected $data = [];
    protected string $target = '';
    protected string $eventType = 'click';
    protected bool $showLoading = true;
    protected bool $enableConsoleLog = false;

    protected string $successTitle = 'Success';
    protected string $successText  = 'Operation completed successfully!';
    protected string $errorTitle   = 'Error';
    protected string $errorText    = 'Something went wrong. Please try again.';

    protected string $successCallback = '';
    protected string $errorCallback = '';
    protected ?string $redirectUrl = null;
    protected bool $refreshPage = false; // 🔹 New property

    protected static bool $assetsLoaded = false;

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

    public function url(string $url): static { $this->url = $url; return $this; }
    public function method(string $method): static { $this->method = strtoupper($method); return $this; }
    public function data($data): static { $this->data = $data; return $this; }
    public function target(string $selector): static { $this->target = $selector; return $this; }
    public function event(string $type): static { $this->eventType = strtolower($type); return $this; }
    public function showLoading(bool $flag = true): static { $this->showLoading = $flag; return $this; }
    public function successMessage(string $title, string $text = ''): static { $this->successTitle = $title; $this->successText = $text; return $this; }
    public function errorMessage(string $title, string $text = ''): static { $this->errorTitle = $title; $this->errorText = $text; return $this; }

    // Extra methods
    public function log(bool $flag = true): static { $this->enableConsoleLog = $flag; return $this; }
    public function onSuccess(string $js): static { $this->successCallback = $js; return $this; }
    public function onError(string $js): static { $this->errorCallback = $js; return $this; }
    public function redirect(string $url): static { $this->redirectUrl = $url; return $this; }
    public function refresh(bool $flag = true): static { $this->refreshPage = $flag; return $this; } // 🔹 New method

    public function render(string $triggerSelector): string
    {
        if (!self::$assetsLoaded) {
            View::addHead('<link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">');
            View::addScript('<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>');
            self::$assetsLoaded = true;
        }

        // Prepare AJAX data
        if ($this->eventType === 'submit' && !empty($this->target)) {
            $dataJs = "let ajaxData = \$('{$this->target}').serialize();";
        } elseif (is_array($this->data) && !empty($this->data)) {
            $dataJson = json_encode($this->data);
            $dataJs = "let ajaxData = {$dataJson};";
        } elseif (is_string($this->data) && trim($this->data) !== '') {
            $dataJs = "let ajaxData = {$this->data};";
        } else {
            $dataJs = "let ajaxData = $(this).data();"; // fallback
        }

        $loadingJs = $this->showLoading
            ? "Swal.fire({title: 'Please wait...', text: 'Processing request', allowOutsideClick: false, didOpen: () => {Swal.showLoading();}});"
            : '';

        $logSuccess = $this->enableConsoleLog ? "console.log('AJAX success:', response);" : '';
        $logError = $this->enableConsoleLog ? "console.log('AJAX error:', xhr);" : '';

        // Success / error callbacks
        $onSuccessJs = '';
        if ($this->redirectUrl) {
            $onSuccessJs .= "setTimeout(function() { window.location.href = '{$this->redirectUrl}'; }, 1500);";
        }
        if ($this->refreshPage) {
            $onSuccessJs .= "setTimeout(function() { window.location.reload(); }, 1500);"; // 🔹 Refresh
        }
        if ($this->successCallback) {
            $onSuccessJs .= "({$this->successCallback})(response);";
        }
        $onErrorJs = $this->errorCallback ? "({$this->errorCallback})(xhr);" : '';

        // URL handling
        $urlJs = <<<JS
            let url = '{$this->url}';
            if (!url) {
                if ($(this).is('form')) {
                    url = $(this).attr('action') || '';
                } else {
                    console.error('SweetAjax Error: No URL provided and trigger is not a form with an action attribute.');
                }
            }

            url = url.replace(/\\{(\\w+)\\}/g, function(_, key) {
                return $(this).data(key);
            }.bind(this));
        JS;

        return <<<HTML
<script>
$(document).on('{$this->eventType}', '{$triggerSelector}', function(e) {
    e.preventDefault();
    {$loadingJs}
    {$dataJs}
    {$urlJs}

    $.ajax({
        url: url,
        method: '{$this->method}',
        data: ajaxData,
        success: function(response) {
            {$logSuccess}
            Swal.close();
            try {
                if (typeof response === "string") response = JSON.parse(response);
            } catch(err) { console.error("Invalid JSON response", err); }

            if (response && (response.status === "success" || response.success === true || response.status === true)) {
                Swal.fire({
                    icon: 'success',
                    title: '{$this->successTitle}',
                    text: response.message || '{$this->successText}'
                });
                {$onSuccessJs}
            } else {
                Swal.fire({
                    icon: 'error',
                    title: '{$this->errorTitle}',
                    text: (response && response.message) ? response.message : '{$this->errorText}'
                });
                {$onErrorJs}
            }
        },
        error: function(xhr) {
            {$logError}
            Swal.close();
            Swal.fire({
                icon: 'error',
                title: '{$this->errorTitle}',
                text: xhr.responseJSON?.message || '{$this->errorText}'
            });
            {$onErrorJs}
        }
    });
});
</script>
HTML;
    }
}
