<?php

namespace Opencart\Extension\Alsendo\Models;

class WrapperResult
{
    private bool $success;
    private string $message;
    private array $data;
    private ?string $error;
    private array $errors;

    public function __construct(bool $success, string $message, array $data = [], ?string $error = null, array $errors = [])
    {
        $this->success = $success;
        $this->message = $message;
        $this->data = $data;
        $this->errors = $errors;

        if ($error) {
            $decoded = json_decode($error, true);

            if (json_last_error() === JSON_ERROR_NONE) {

                $parsed = [];
                foreach ($decoded['errors'] ?? [] as $key => $jsonError) {
                    if (!array_key_exists('message', $jsonError)) {
                        foreach ($jsonError as $singleJsonError) {
                            if (is_string($singleJsonError)) {
                                $parsed[] = $singleJsonError;
                            }
                        }
                        continue;
                    }

                    $parsed[] = $jsonError['message'];
                }
                $error = implode(', ', $parsed);
            }
        }

        $this->error = $error;
    }

    public function isSuccess(): bool
    {
        return $this->success;
    }

    public function isErroredPossiblyCausedByPickupDate(): bool
    {
        if ($this->success) {
            return false;
        }

        return true;
    }

    public function getMessage(): string
    {
        return $this->message;
    }

    public function getData(): array
    {
        return $this->data;
    }

    public function getError(): ?string
    {
        return $this->error;
    }

    public function getErrors(): array
    {
        return $this->errors;
    }

    public function toArray(): array
    {
        $result = [
            'success' => $this->success,
            'message' => $this->message
        ];

        if ($this->success) {
            $result['data'] = $this->data;
        } else {
            $result['error'] = $this->error ?? $this->message;
            if (!empty($this->errors)) {
                $result['errors'] = $this->errors;
            }
        }

        return $result;
    }
} 