<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\ParametreSociete;

final class ParametreSocieteService extends BaseService
{
    public function __construct(
        private readonly ParametreSociete $settings = new ParametreSociete()
    ) {
    }

    public function get(): array
    {
        return $this->settings->get();
    }

    public function save(array $data): void
    {
        if (trim((string)($data['raison_sociale'] ?? '')) === '') {
            throw new \RuntimeException(
                'La raison sociale est obligatoire.'
            );
        }

        $this->settings->save($data);
    }

    public function saveDocuments(array $data): void
    {
        $allowedFields = [
            'logo_path',
            'couleur_principale',
            'couleur_secondaire',
            'conditions_reglement',
			'conditions_devis',
			'conditions_bl',
			'conditions_facture',
			'conditions_avoir',
            'penalites_retard',
            'reserve_propriete',
            'mentions_legales',
            'pied_de_page',
            'signature_document',
            'banque',
            'rib',
            'iban',
            'swift',

        ];

        $documentSettings = [];

        foreach ($allowedFields as $field) {
            if (array_key_exists($field, $data)) {
                $documentSettings[$field] = $data[$field];
            }
        }

        $this->settings->savePartial($documentSettings);
    }

    public function removeLogo(): void
    {
        $settings = $this->settings->get();
        $storedLogoPath = trim(
            (string)($settings['logo_path'] ?? '')
        );

        $rootPath = dirname(__DIR__, 2);

        $publicPath = $rootPath
            . DIRECTORY_SEPARATOR
            . 'public';

        $filesToDelete = [];

        if ($storedLogoPath !== '') {
            $relativePath = (string)(
                parse_url($storedLogoPath, PHP_URL_PATH) ?? ''
            );

            $relativePath = ltrim(
                $relativePath,
                '/\\'
            );

            if (str_starts_with($relativePath, 'public/')) {
                $relativePath = substr($relativePath, 7);
            }

            $physicalPath = $publicPath
                . DIRECTORY_SEPARATOR
                . str_replace(
                    ['/', '\\'],
                    DIRECTORY_SEPARATOR,
                    $relativePath
                );

            $filesToDelete[] = $physicalPath;
        }

        $logoDirectory = $publicPath
            . DIRECTORY_SEPARATOR
            . 'assets'
            . DIRECTORY_SEPARATOR
            . 'img';

        foreach (['png', 'jpg', 'jpeg'] as $extension) {
            $filesToDelete[] = $logoDirectory
                . DIRECTORY_SEPARATOR
                . 'logo_societe.'
                . $extension;
        }

        $filesToDelete = array_unique($filesToDelete);

        foreach ($filesToDelete as $filePath) {
            if (!is_file($filePath)) {
                continue;
            }

            if (!unlink($filePath)) {
                throw new \RuntimeException(
                    'Impossible de supprimer le fichier : '
                    . basename($filePath)
                );
            }
        }

        $this->settings->savePartial([
            'logo_path' => '',
        ]);
    }
}