<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

final class ParametreSociete extends Model
{
    public function get(): array
    {
        if (!$this->tableExists('parametres_societe')) {
            return $this->defaults();
        }

        $row = $this->db->query('SELECT * FROM parametres_societe WHERE id = 1 LIMIT 1')->fetch(PDO::FETCH_ASSOC);
        return $row ?: $this->defaults();
    }

    public function save(array $data): void
    {
        if (!$this->tableExists('parametres_societe')) {
            throw new \RuntimeException('La table parametres_societe est absente. Importez database/migrations/013_parametres_societe.sql.');
        }

        // Phoenix P2.5.5.1 : répare automatiquement les installations
        // dont le code a été mis à jour sans exécution de la migration 028.
        $this->ensureDocumentConditionColumns();

        $data = $this->normalize($data);
        $exists = (int)$this->db->query('SELECT COUNT(*) FROM parametres_societe WHERE id = 1')->fetchColumn() > 0;

        if (!$exists) {
            $columns = array_keys($data);
            $sql = 'INSERT INTO parametres_societe (id, ' . implode(', ', $columns) . ') VALUES (1, :' . implode(', :', $columns) . ')';
            $this->db->prepare($sql)->execute($data);
            return;
        }

        $sets = [];
        foreach (array_keys($data) as $column) {
            $sets[] = $column . ' = :' . $column;
        }

        $sql = 'UPDATE parametres_societe SET ' . implode(', ', $sets) . ' WHERE id = 1';
        $this->db->prepare($sql)->execute($data);
    }
		public function savePartial(array $data): void
		{
			$current = $this->get();

			unset(
				$current['id'],
				$current['date_creation'],
				$current['date_modification']
			);

			$merged = array_replace($current, $data);

			$this->save($merged);
		}
	private function normalize(array $data): array
    {
		$textFields = [
			'raison_sociale',
			'nom_commercial',
			'adresse',
			'code_postal',
			'ville',
			'pays',
			'telephone',
			'mobile',
			'email',
			'site_web',
			'ice',
			'identifiant_fiscal',
			'registre_commerce',
			'patente',
			'banque',
			'rib',
			'iban',
			'swift',
			'devise',
			'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',
			'logo_path',
		];

        $normalized = [];
        foreach ($textFields as $field) {
            $normalized[$field] = trim((string)($data[$field] ?? ''));
        }

        $normalized['raison_sociale'] = $normalized['raison_sociale'] !== '' ? $normalized['raison_sociale'] : 'Darlink ERP';
        $normalized['pays'] = $normalized['pays'] !== '' ? $normalized['pays'] : 'Maroc';
        $normalized['devise'] = $normalized['devise'] !== '' ? strtoupper($normalized['devise']) : 'MAD';
        $normalized['couleur_principale'] = $normalized['couleur_principale'] !== '' ? $normalized['couleur_principale'] : '#123A5A';
		$normalized['couleur_secondaire'] = $normalized['couleur_secondaire'] !== '' ? $normalized['couleur_secondaire'] : '#6C757D';

        return $normalized;
    }

    private function defaults(): array
    {
        return [
            'id' => 1,
            'raison_sociale' => 'Darlink ERP',
            'nom_commercial' => '',
            'adresse' => '',
            'code_postal' => '',
            'ville' => '',
            'pays' => 'Maroc',
            'telephone' => '',
            'mobile' => '',
            'email' => '',
            'site_web' => '',
            'ice' => '',
            'identifiant_fiscal' => '',
            'registre_commerce' => '',
            'patente' => '',
            'banque' => '',
            'rib' => '',
            'iban' => '',
            'swift' => '',
            'devise' => 'MAD',
            'couleur_principale' => '#123A5A',
            'couleur_secondaire' => '#6C757D',
            'conditions_reglement' => '',
            'conditions_devis' => '',
            'conditions_bl' => '',
            'conditions_facture' => '',
            'conditions_avoir' => '',
            'penalites_retard' => '',
            'reserve_propriete' => '',
            'mentions_legales' => '',
            'pied_de_page' => 'Document généré par Darlink ERP',
            'signature_document' => '',
            'logo_path' => '',
        ];
    }

    /**
     * Garantit la présence des colonnes de conditions par type de document.
     *
     * Certaines anciennes installations Phoenix peuvent avoir enregistré la
     * migration 028 comme traitée sans que les quatre colonnes aient été
     * réellement créées. Le contrôle est volontairement idempotent : seules
     * les colonnes absentes sont ajoutées, sans toucher aux données existantes.
     */
    private function ensureDocumentConditionColumns(): void
    {
        $columns = [
            'conditions_devis' => 'conditions_reglement',
            'conditions_bl' => 'conditions_devis',
            'conditions_facture' => 'conditions_bl',
            'conditions_avoir' => 'conditions_facture',
        ];

        $stmt = $this->db->prepare(
            'SELECT COLUMN_NAME FROM information_schema.columns '
            . 'WHERE table_schema = DATABASE() AND table_name = :table'
        );
        $stmt->execute(['table' => 'parametres_societe']);

        $existing = array_fill_keys(
            array_map('strval', $stmt->fetchAll(PDO::FETCH_COLUMN)),
            true
        );

        foreach ($columns as $column => $after) {
            if (isset($existing[$column])) {
                continue;
            }

            // Les identifiants proviennent exclusivement de la liste interne
            // ci-dessus ; aucune valeur utilisateur n'est injectée dans le SQL.
            $sql = sprintf(
                'ALTER TABLE `parametres_societe` ADD COLUMN `%s` TEXT NULL AFTER `%s`',
                $column,
                $after
            );
            $this->db->exec($sql);
            $existing[$column] = true;
        }
    }

    private function tableExists(string $table): bool
    {
        $stmt = $this->db->prepare('SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = :table');
        $stmt->execute(['table' => $table]);
        return (int)$stmt->fetchColumn() > 0;
    }
	public function removeLogo(): void
{
    $rootPath = dirname(__DIR__, 2);

    $logoDirectory = $rootPath
        . DIRECTORY_SEPARATOR
        . 'public'
        . DIRECTORY_SEPARATOR
        . 'assets'
        . DIRECTORY_SEPARATOR
        . 'img';

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

        if (is_file($filePath) && !unlink($filePath)) {
            throw new \RuntimeException(
                'Impossible de supprimer le fichier du logo.'
            );
        }
    }

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