<?php

namespace Opencart\Extension\Alsendo\Handlers;

require_once(DIR_EXTENSION . 'alsendo/src/DTO/ConfigurationRequests/SaveAdditionalSettingsRequestDTO.php');
require_once(DIR_EXTENSION . 'alsendo/src/Models/AdditionalSettings.php');
require_once(DIR_EXTENSION . 'alsendo/src/Repositories/AdditionalSettingsRepository.php');

use Opencart\Extension\Alsendo\Repositories\AdditionalSettingsRepository;
use Opencart\Extension\Alsendo\Models\AdditionalSettings;
use Opencart\Extension\Alsendo\DTO\ConfigurationRequests\SaveAdditionalSettingsRequestDTO;

class AdditionalSettingsHandler
{
    private AdditionalSettingsRepository $repository;

    public function __construct(AdditionalSettingsRepository $repository)
    {
        $this->repository = $repository;
    }

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

        try {
            $settings = $this->createSettingsFromData($dto->toArray());
            $id = $this->repository->saveSettings($settings);
            
            return [
                'success' => 'Settings saved successfully',
                'id' => $id
            ];
        } catch (\Exception $e) {
            error_log('Exception in saveSettings: ' . $e->getMessage());
            return ['error' => 'Failed to save settings: ' . $e->getMessage()];
        }
    }

    private function validateSettingsData(array $data): array
    {
        if (!empty($data['pickup_hour_from']) && !empty($data['pickup_hour_to'])) {
            $from = strtotime($data['pickup_hour_from']);
            $to = strtotime($data['pickup_hour_to']);
            
            if ($from >= $to) {
                return [
                    'valid' => false,
                    'message' => 'pickup_hour_from_must_be_earlier'
                ];
            }
            
            $diff = ($to - $from) / 3600;
            if ($diff < 2) {
                return [
                    'valid' => false,
                    'message' => 'pickup_hour_range_too_small'
                ];
            }
        }

        return ['valid' => true];
    }

    private function createSettingsFromData(array $data): AdditionalSettings
    {
        $existingSettings = $this->repository->getSettings();
        $id = $existingSettings ? $existingSettings->getId() : null;

        return new AdditionalSettings(
            $id,
            !empty($data['inpost_default_point']) ? json_decode(htmlspecialchars_decode($data['inpost_default_point']), true) : null,
            !empty($data['dhl_default_point']) ? json_decode(htmlspecialchars_decode($data['dhl_default_point']), true) : null,
            !empty($data['orlen_default_point']) ? json_decode(htmlspecialchars_decode($data['orlen_default_point']), true) : null,
            !empty($data['poczta_polska_default_point']) ? json_decode(htmlspecialchars_decode($data['poczta_polska_default_point']), true) : null,
            !empty($data['dpd_default_point']) ? json_decode(htmlspecialchars_decode($data['dpd_default_point']), true) : null,
            !empty($data['ups_default_point']) ? json_decode(htmlspecialchars_decode($data['ups_default_point']), true) : null,
            !empty($data['balikovna_default_point']) ? json_decode(htmlspecialchars_decode($data['balikovna_default_point']), true) : null,
            !empty($data['gls_default_point']) ? json_decode(htmlspecialchars_decode($data['gls_default_point']), true) : null,
            !empty($data['ppl_default_point']) ? json_decode(htmlspecialchars_decode($data['ppl_default_point']), true) : null,
            !empty($data['zasilkovna_default_point']) ? json_decode(htmlspecialchars_decode($data['zasilkovna_default_point']), true) : null,
            !empty($data['sameday_default_point']) ? json_decode(htmlspecialchars_decode($data['sameday_default_point']), true) : null,
            !empty($data['fan_courier_default_point']) ? json_decode(htmlspecialchars_decode($data['fan_courier_default_point']), true) : null,
            !empty($data['cargus_default_point']) ? json_decode(htmlspecialchars_decode($data['cargus_default_point']), true) : null,
            !empty($data['pickup_hour_from']) ? $data['pickup_hour_from'] : null,
            !empty($data['pickup_hour_to']) ? $data['pickup_hour_to'] : null,
            !empty($data['auto_declared_value']) && (bool)$data['auto_declared_value'],
            !empty($data['sameday_dispatch']) && (bool)$data['sameday_dispatch']
        );
    }
} 