<?php

namespace App\Config\Repository;

use App\Config\Entity\SiteConfig;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class SiteConfigRepository extends ServiceEntityRepository
{
    // Default values returned when a key is missing from DB
    private const DEFAULTS = [
        // financial engine
        'appointment_commission_enabled' => '0',
        'upgrade_commission_enabled'     => '0',
        'upgrade_commission_percent'     => '20',
        'tax_enabled'                    => '0',
        'tax_percent'                    => '10',
        'sms_panel_fee_rials'            => '150',
        'appointment_fee_rials'          => '15000',
        'site_name'                  => 'ClinicPro',
        'support_phone'              => '',
        'max_cancel_hours_before'    => '24',
        'appointment_reminder_hours' => '2',
        // logging (0 = نگهداری نامحدود)
        'log_retention_days'         => '90',
        // payment gateways
        'payment_test_mode'          => '0',
        'mellat_terminal_id'         => '',
        'mellat_username'            => '',
        'mellat_password'            => '',
        'sep_terminal_id'            => '',
    ];

    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, SiteConfig::class);
    }

    public function get(string $key): ?string
    {
        $row = $this->find($key);
        if ($row !== null) {
            return $row->getValue();
        }
        return self::DEFAULTS[$key] ?? null;
    }

    public function getAll(): array
    {
        $rows = $this->findAll();
        $map  = [];
        foreach ($rows as $row) {
            $map[$row->getKey()] = $row->getValue();
        }
        // Fill missing keys with defaults
        foreach (self::DEFAULTS as $key => $default) {
            if (!isset($map[$key])) {
                $map[$key] = $default;
            }
        }
        return $map;
    }

    public function set(string $key, ?string $value): void
    {
        $row = $this->find($key);
        if ($row === null) {
            $row = new SiteConfig($key, $value);
            $this->getEntityManager()->persist($row);
        } else {
            $row->setValue($value);
        }
    }
}
