<?php

namespace Opencart\Extension\Alsendo\Handlers;

require_once(DIR_EXTENSION . 'alsendo/src/DTO/ConfigurationRequests/SaveSenderTemplateRequestDTO.php');
require_once(DIR_EXTENSION . 'alsendo/src/DTO/ConfigurationRequests/UpdateSenderTemplateRequestDTO.php');
require_once(DIR_EXTENSION . 'alsendo/src/Models/SenderAddressTemplate.php');
require_once(DIR_EXTENSION . 'alsendo/src/Repositories/SenderAddressRepository.php');

use Opencart\Extension\Alsendo\Repositories\SenderAddressRepository;
use Opencart\Extension\Alsendo\Models\SenderAddressTemplate;
use Opencart\Extension\Alsendo\DTO\ConfigurationRequests\SaveSenderTemplateRequestDTO;
use Opencart\Extension\Alsendo\DTO\ConfigurationRequests\UpdateSenderTemplateRequestDTO;

class SenderAddressHandler
{
    private SenderAddressRepository $repository;
    private object $language;
    private array $requiredFields = [
        'company_name', 'full_name', 'building_number',
        'postal_code', 'city', 'phone_number', 'email',
    ];

    public function __construct(SenderAddressRepository $repository, object $language)
    {
        $this->repository = $repository;
        $this->language = $language;
    }

    public function saveTemplate(SaveSenderTemplateRequestDTO $dto): array
    {
        $validationResult = $this->validateTemplateData($dto->toArray());
        if (!$validationResult['valid']) {
            return ['error' => $validationResult['message']];
        }

        if ($this->templateNameExists($dto->companyName)) {
            return ['error' => $this->language->get('text_templates_must_have_unique_names')];
        }

        try {
            $template = $this->createTemplateFromData($dto->toArray());
            $id = $this->repository->saveTemplate($template);
            
            return [
                'success' => $this->language->get('text_template_saved_successfully'),
                'id' => $id
            ];
        } catch (\Exception $e) {
            return ['error' => ''.$this->language->get('text_failed_to_save_template').': ' . $e->getMessage()];
        }
    }

    public function updateTemplate(UpdateSenderTemplateRequestDTO $dto): array
    {
        if (empty($dto->id)) {
            return ['error' => $this->language->get('text_template_id_is_required')];
        }

        $validationResult = $this->validateTemplateData($dto->toArray());
        if (!$validationResult['valid']) {
            return ['error' => $validationResult['message']];
        }

        $existingTemplate = $this->repository->getTemplateById($dto->id);
        if (!$existingTemplate) {
            return ['error' => $this->language->get('text_template_not_found')];
        }

        if ($existingTemplate->getCompanyName() !== $dto->companyName &&
            $this->templateNameExists($dto->companyName)) {
            return ['error' => $this->language->get('text_templates_must_have_unique_names')];
        }

        try {
            $template = $this->createTemplateFromData($dto->toArray());
            $template->setId($dto->id);
            $this->repository->updateTemplate($template);

            return ['success' => $this->language->get('text_template_saved_successfully')];
        } catch (\Exception $e) {
            return ['error' => $this->language->get('text_failed_to_update_template') . ': ' . $e->getMessage()];
        }
    }

    public function deleteTemplate(int $id): array
    {
        if ($id <= 0) {
            return ['error' => $this->language->get('text_invalid_template_id')];
        }

        try {
            $this->repository->deleteTemplate($id);
            return ['success' => $this->language->get('text_template_deleted_successfully')];
        } catch (\Exception $e) {
            return ['error' => $this->language->get('text_failed_to_delete_template') . ': ' . $e->getMessage()];
        }
    }

    public function setAsMain(int $id): array
    {
        if ($id <= 0) {
            return ['error' => $this->language->get('text_invalid_template_id')];
        }

        try {
            $this->repository->setAsMain($id);
            return ['success' => $this->language->get('text_template_set_as_main_successfully')];
        } catch (\Exception $e) {
            return ['error' => $this->language->get('text_failed_to_set_template_as_main') . ': ' . $e->getMessage()];
        }
    }

    private function validateTemplateData(array $data): array
    {
        foreach ($this->requiredFields as $field) {
            if (empty($data[$field])) {
                return [
                    'valid' => false,
                    'message' => sprintf($this->language->get('text_field_required'), strtolower($this->translateFieldToHuman($field))),
                ];
            }
        }

        if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
            return [
                'valid' => false,
                'message' => $this->language->get('text_invalid_email_address')
            ];
        }

        return ['valid' => true];
    }

    private function createTemplateFromData(array $data): SenderAddressTemplate
    {
        return new SenderAddressTemplate(
            null,
            $data['external_id'] ?? null,
            $data['address_type'] ?? 'company',
            $data['company_name'],
            $data['first_name'] ?? '',
            $data['last_name'] ?? '',
            $data['full_name'],
            !empty($data['street']) ? $data['street'] : null,
            $data['building_number'],
            !empty($data['apartment_number']) ? $data['apartment_number'] : null,
            !empty($data['block']) ? $data['block'] : null,
            !empty($data['entrance']) ? $data['entrance'] : null,
            !empty($data['floor']) ? $data['floor'] : null,
            $data['postal_code'],
            $data['city'],
            $data['country'],
            $data['contact_person'] ?? $data['full_name'] ?? '',
            $data['phone_number'],
            $data['email'],
            $data['bank_account_number'],
            $data['bank_code'] ?? null,
            $data['additional_bank_account_number'] ?? null,
            !empty($data['main']),
            $data['pickup_point'] ?? null
        );
    }

    private function translateFieldToHuman(string $fieldName): string {
        $translated = $this->language->get('field_' . $fieldName);
        if (!empty($translated) && $translated !== 'field_' . $fieldName) {
            return $translated;
        }

        $translated = $this->language->get('field_sender_' . $fieldName);
        if (!empty($translated) && $translated !== 'field_' . $fieldName) {
            return $translated;
        }

        return str_replace('_', ' ', $fieldName);
    }

    private function templateNameExists(string $companyName): bool
    {
        $templates = $this->repository->getAllTemplates();

        foreach ($templates as $template) {
            if ($template->getCompanyName() === $companyName) {
                return true;
            }
        }

        return false;
    }
} 