<?PHP

namespace Classe;

use OverflowException;
use Views\ParametresHtml;

class Parametres
{

    private $conn;
    public $idUrl;
    public $nomUrl;
    public $comUrl;
    public $lastmod;
    public $lastvisit;
    public function __construct($conn)
    {
        $this->conn = $conn;
    }

    public function afficheParametres($conn)
    {
        $conn = $this->conn;
        $msgParam = "";
        $msgParam2 = "";
        $logoFile = null;

        if (isset($_POST['nom_etablissement'])) {
            $nom_etablissement = $_POST['nom_etablissement'] ?? '';
            $nom_etablissement_anglais = $_POST['nom_etablissement_anglais'] ?? '';
            $adresse_etablissement = $_POST['adresse_etablissement'] ?? '';
            $chemin_imprimante = $_POST['chemin_imprimante'] ?? '';
            $noms_bornes = $_POST['noms_bornes'] ?? '';
            $allowedonmaintenance = $_POST['allowedonmaintenance'] ?? '';

            $nom_service = $_POST['nom_service'] ?? '';
            $email_support = $_POST['email_support'] ?? '';
            $tel_support = $_POST['tel_support'] ?? '';

            $utiliser_mulitlangue = isset($_POST['utiliser_mulitlangue']) ? 1 : 0;
            $afficher_sidebar = isset($_POST['afficher_sidebar']) ? 1 : 0;
            $utiliser_mode_dark = isset($_POST['utiliser_mode_dark']) ? 1 : 0;
            $en_maintenance = isset($_POST['en_maintenance']) ? 1 : 0;
            $regrouper_menu = isset($_POST['regrouper_menu']) ? 1 : 0;
            $inactivity_time = $_POST['inactivity_time'] ?? '15';
            $utiliser_etape = isset($_POST['utiliser_etape']) ? 1 : 0;
            $utiliser_seul_date_debut = isset($_POST['utiliser_seul_date_debut']) ? 1 : 0;
            $affi_fraphe_stat_mon = isset($_POST['affi_fraphe_stat_mon']) ? 1 : 0;
            $affi_fraphe_stat_annu = isset($_POST['affi_fraphe_stat_annu']) ? 1 : 0;


            $ldap_enabled = isset($_POST['ldap_enabled']) ? 1 : 0;
            $import_user_from_ldap = isset($_POST['import_user_from_ldap']) ? 1 : 0;
            $ldap_host = $_POST['ldap_host'] ?? '';
            $ldap_port = $_POST['ldap_port'] ?? '';
            $bind_dn = $_POST['bind_dn'] ?? '';
            $bind_password = $_POST['bind_password'] ?? '';
            $base_dn = $_POST['base_dn'] ?? '';

            if (isset($_FILES['logo_site']) && $_FILES['logo_site']['error'] === UPLOAD_ERR_OK) {
                $uploadDir = __DIR__ . '/../assets/images/';

                $fileTmpPath = $_FILES['logo_site']['tmp_name'];
                $fileName = $_FILES['logo_site']['name'];
                $fileSize = $_FILES['logo_site']['size'];
                $fileType = $_FILES['logo_site']['type'];
                $fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

                $msgParam2 .=  "";
                $allowedTypes = ['png', 'jpg', 'jpeg'];
                if (in_array($fileExt, $allowedTypes)) {
                    $newFileName = 'logo_' . time() . '.' . $fileExt;
                    $destPath = $uploadDir . $newFileName;

                    if (move_uploaded_file($fileTmpPath, $destPath)) {
                        // ✅ Save filename to database or config
                        $logoFile = $newFileName;

                        // Example MySQL save (assumes you have a parameters table):
                        $conn->exec("UPDATE parametres SET logo_file = '" . $logoFile . "' ;");

                        $msgParam2 .=  "✅ Logo mis à jour.";
                    } else {
                        $msgParam2 .=  "❌ Erreur lors du déplacement du fichier.";
                    }
                } else {
                    $msgParam2 .=  "❌ Format de fichier invalide. Seuls les PNG et JPG sont autorisés.";
                }
            }

            $configFile = __DIR__ . '/../config.php';

            if (file_exists($configFile)) {

                $config = file_get_contents($configFile);
                //echo 'configFile = ' . $config; 

                //$config = preg_replace("/define\('NOM_ETABLISSEMENT',\s*'.*?'\);/", "define('NOM_ETABLISSEMENT', '{$nom_etablissement}');", $config);
                $this->updateOrInsertDefine($config, 'SHOW_PARAM', 'false');
                
                if (!empty($logoFile)){
                    $this->updateOrInsertDefine($config, 'LOGO', $logoFile);
                }

                $this->updateOrInsertDefine($config, 'NOM_ETABLISSEMENT', $nom_etablissement);
                $this->updateOrInsertDefine($config, 'NOM_ETABLISSEMENT_ANGLAIS', value: $nom_etablissement_anglais);
                $this->updateOrInsertDefine($config, 'NOM_SERVICE', $nom_service);
                $this->updateOrInsertDefine($config, 'EMAIL_SUPPORT', $email_support);
                $this->updateOrInsertDefine($config, 'TEL_SUPPORT', $tel_support);
                $this->updateOrInsertDefine($config, 'CHEMIN_IMPRIMANTE', $chemin_imprimante);

                $this->updateOrInsertDefine($config, 'NOMS_BORNES', $noms_bornes);
                $this->updateOrInsertDefine($config, 'ALLOWED_MACHINE_ON_MAINTENANCE', $allowedonmaintenance);

                $this->updateOrInsertDefine($config, 'UTILISER_MULITLANGUE', $utiliser_mulitlangue);
                $this->updateOrInsertDefine($config, 'AFFICHER_SIDEBAR', $afficher_sidebar);
                $this->updateOrInsertDefine($config, 'UTILISER_MODE_DARK', $utiliser_mode_dark);
                $this->updateOrInsertDefine($config, 'EN_MAINTENANCE', $en_maintenance);
                $this->updateOrInsertDefine($config, 'REGROUPER_MENU', $regrouper_menu);
                $this->updateOrInsertDefine($config, 'INACTIVITY_TIME', $inactivity_time);    
                $this->updateOrInsertDefine($config, 'UTILISER_ETAPE', $utiliser_etape);
                $this->updateOrInsertDefine($config, 'UTILISER_SEUL_DATE_DEBUT', $utiliser_seul_date_debut);
                $this->updateOrInsertDefine($config, 'AFFI_FRAPHE_STAT_MON', $affi_fraphe_stat_mon);
                $this->updateOrInsertDefine($config, 'AFFI_FRAPHE_STAT_ANNU', $affi_fraphe_stat_annu);

                $this->updateOrInsertDefine($config, 'LDAP_ENABLED', $ldap_enabled);
                $this->updateOrInsertDefine($config, 'IMPORT_USER_FROM_LDAP', $import_user_from_ldap);
                $this->updateOrInsertDefine($config, 'LDAP_HOST', $ldap_host);
                $this->updateOrInsertDefine($config, 'LDAP_PORT', $ldap_port);
                $this->updateOrInsertDefine($config, 'BIND_DN', $bind_dn);
                $this->updateOrInsertDefine($config, 'BIND_PASSWORD', $bind_password);
                $this->updateOrInsertDefine($config, 'BASE_DN', value: $base_dn);

                file_put_contents($configFile, $config);
            }


            $batFile =  __DIR__ . '\printpdf.bat';
            $pdfPath =  __DIR__ . '\generated_pdf.pdf';
            if (file_exists($batFile)) {
                $newContent = "@echo off" . PHP_EOL;
                $newContent .= "\"C:\\Program Files\\SumatraPDF\\SumatraPDF.exe\" -print-to \"$chemin_imprimante\" \"$pdfPath\"";
                file_put_contents($batFile, $newContent);
            }
            $this->updateOrInsertDefine($config, 'NOMS_BORNES', $noms_bornes);
            $this->updateOrInsertDefine($config, 'ALLOWED_MACHINE_ON_MAINTENANCE', $allowedonmaintenance);

            $sql = "UPDATE parametres SET 
            nom_etablissement = '" . addslashes($nom_etablissement) . "',
            nom_etablissement_anglais = '" . addslashes($nom_etablissement_anglais) . "',
            adresse_etablissement = '" . addslashes($adresse_etablissement) . "',
            chemin_imprimante = '" . addslashes($chemin_imprimante) . "',
            noms_bornes = '" . addslashes($noms_bornes) . "',
            allowedonmaintenance = '" . addslashes($allowedonmaintenance) . "',
            nom_service = '" . addslashes($nom_service) . "',
            email_support = '" . addslashes($email_support) . "',
            tel_support = '" . addslashes($tel_support) . "',
            utiliser_mulitlangue = $utiliser_mulitlangue,
            afficher_sidebar = $afficher_sidebar,
            utiliser_mode_dark = $utiliser_mode_dark,
            en_maintenance = $en_maintenance,
            regrouper_menu = $regrouper_menu,
            inactivity_time = $inactivity_time,
            utiliser_etape = $utiliser_etape,
            utiliser_seul_date_debut = $utiliser_seul_date_debut,
            affi_fraphe_stat_mon = $affi_fraphe_stat_mon,
            affi_fraphe_stat_annu = $affi_fraphe_stat_annu ,
            ldap_enabled = $ldap_enabled ,
            import_user_from_ldap = $import_user_from_ldap ,
            ldap_host = '" . addslashes($ldap_host) . "' ,
            ldap_port = '" . addslashes($ldap_port) . "' ,
            bind_dn = '" . addslashes($bind_dn) . "' ,
            bind_password = '" . addslashes($bind_password) . "' ,
            base_dn = '" . addslashes($base_dn) . "' ";

            $conn->exec($sql);

            $msgParam .= "updated";
        } else {
            $msgParam .= null;
        }

        $sql2 = "SELECT `nom_etablissement`, `nom_etablissement_anglais`, `adresse_etablissement`, `chemin_imprimante`, `noms_bornes`, `allowedonmaintenance`, `utiliser_mulitlangue`, `afficher_sidebar`, 
        `utiliser_mode_dark`, `en_maintenance`, `regrouper_menu`, `inactivity_time`, `nom_service`, `email_support`, `tel_support`, `utiliser_etape`, `utiliser_seul_date_debut`, `affi_fraphe_stat_mon`, 
        `affi_fraphe_stat_annu`, `logo_file`, `ldap_enabled`, `import_user_from_ldap`, `ldap_host`, `ldap_port`, `bind_dn`, `bind_password`, `base_dn`
        FROM `parametres` 
        WHERE 1";
        $conn->exec($sql2);
        $resultParam = $conn->data[0];


        ParametresHtml::AfficherParametres($resultParam, $msgParam, $msgParam2);
    }
    function updateOrInsertDefine(&$config, $name, $value, $isBool = false)
    {
        if (!$isBool) {
            // Escape single quotes for safe insertion in single-quoted string
            $value = str_replace("'", "\\'", $value);
            $replacement = "define('{$name}', '{$value}');";
        } else {
            $replacement = "define('{$name}', " . ($value ? 'true' : 'false') . ");";
        }

        $pattern = "/define\(\s*'{$name}'\s*,\s*(.*?)\s*\);/";

        if (preg_match($pattern, $config)) {
            $config = preg_replace($pattern, $replacement, $config);
        } else {
            $config .= "\n$replacement";
        }
    }
}
