<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: lib_import.class.php,v 1.2 2026/03/06 16:07:58 dbellamy Exp $

if (stristr($_SERVER['REQUEST_URI'], ".class.php")) {
    die("no access");
}

use Pmb\Common\Helper\DateHelper;

class lib_import
{
    /**
     * Insere la valeur d'un champ personnalise pour un objet donne.
     *
     * Prend en charge tous les types de champs perso connus, avec verification
     * de coherence du type et prevention des doublons avant chaque insertion.
     *
     * @param array  $fields      Tableau issu de get_subfield("900") :
     *                           'n' => nom du champ (cle d'identification)
     *                           'a' => valeur principale / libelle
     *                           'b' => libelle resolu (resolve)
     *                           'c' => identifiant technique (resolve, url, query_*)
     *                           't' => type declare dans le fichier source
     * @param int    $object_id Identifiant de l'objet cible (notice_id, etc.)
     * @param string $prefix   Prefixe des tables du module ('notices', 'author', 'categ', etc.)
     * @return bool  true si une valeur a ete inseree, false sinon
     */
    public static function processCustomFields(array $fields, int $object_id, string $prefix = 'notices'): bool
    {
        $nom     = isset($fields['n']) ? trim($fields['n']) : '';
        $value_a = isset($fields['a']) ? trim($fields['a']) : '';
        $value_b = isset($fields['b']) ? trim($fields['b']) : '';
        $value_c = isset($fields['c']) ? trim($fields['c']) : '';

        if (!$nom || !$object_id) {
            return false;
        }

        $req = "SELECT idchamp, type, datatype FROM " . $prefix . "_custom WHERE name='" . addslashes($nom) . "'";
        $res = pmb_mysql_query($req);
        if (!pmb_mysql_num_rows($res)) {
            return false;
        }

        $perso = pmb_mysql_fetch_object($res);
        if (!$perso->idchamp) {
            return false;
        }

        // Verification de coherence : le type encode en zone 900 doit correspondre au type defini en base
        $type = isset($fields['t']) ? trim($fields['t']) : '';
        if ($type && $perso->type !== $type) {
            return false;
        }

        // Normalise l'alias de datatype pour construire le nom de colonne SQL
        $col = ($perso->datatype === 'int') ? 'integer' : $perso->datatype;

        $p  = $prefix . '_custom';  // prefixe des colonnes et tables
        $cv = $p . '_values';       // table des valeurs
        $cl = $p . '_lists';        // table des listes

        switch ($perso->type) {

            case 'list':
                // Recherche du libelle $a dans la table des valeurs de liste du champ
                if (!$value_a) {
                    return false;
                }
                $rqt = "SELECT " . $p . "_list_value FROM " . $cl
                    . " WHERE " . $p . "_list_lib='" . addslashes($value_a) . "'"
                    . " AND " . $p . "_champ=" . $perso->idchamp;
                $result = pmb_mysql_query($rqt);
                if (pmb_mysql_num_rows($result)) {
                    $list_val = pmb_mysql_result($result, 0, 0);
                } else {
                    // Valeur absente de la liste : creation automatique avec le rang suivant
                    $n = (int) @pmb_mysql_result(
                        pmb_mysql_query("SELECT max(" . $p . "_list_value*1) FROM " . $cl . " WHERE " . $p . "_champ=" . $perso->idchamp),
                        0,
                        0
                    ) + 1;
                    if ($col === 'integer') {
                        pmb_mysql_query(
                            "INSERT INTO " . $cl . " (" . $p . "_champ, " . $p . "_list_value, " . $p . "_list_lib)"
                                . " VALUES(" . $perso->idchamp . ", $n, '" . addslashes($value_a) . "')"
                        );
                        $list_val = $n;
                    } else {
                        pmb_mysql_query(
                            "INSERT INTO " . $cl . " (" . $p . "_champ, " . $p . "_list_value, " . $p . "_list_lib)"
                                . " VALUES(" . $perso->idchamp . ", '" . addslashes($value_a) . "', '" . addslashes($value_a) . "')"
                        );
                        $list_val = $value_a;
                    }
                }
                $rqt_check = "SELECT 1 FROM " . $cv
                    . " WHERE " . $p . "_champ='" . $perso->idchamp . "'"
                    . " AND " . $p . "_origine='" . $object_id . "'"
                    . " AND " . $p . "_" . $col . "='" . addslashes($list_val) . "'";
                if (($res2 = pmb_mysql_query($rqt_check)) && !pmb_mysql_num_rows($res2)) {
                    pmb_mysql_query(
                        "INSERT INTO " . $cv . " (" . $p . "_champ, " . $p . "_origine, " . $p . "_" . $col . ")"
                            . " VALUES(" . $perso->idchamp . ", $object_id, '" . addslashes($list_val) . "')"
                    );
                    return true;
                }
                break;

            case 'url':
                // L'URL complete est dans $c, $a contient le libelle affiche
                $url_val = $value_c ?: $value_a;
                if (!$url_val) {
                    return false;
                }
                $rqt_check = "SELECT 1 FROM " . $cv
                    . " WHERE " . $p . "_champ='" . $perso->idchamp . "'"
                    . " AND " . $p . "_origine='" . $object_id . "'"
                    . " AND " . $p . "_" . $col . "='" . addslashes($url_val) . "'";
                if (($res2 = pmb_mysql_query($rqt_check)) && !pmb_mysql_num_rows($res2)) {
                    pmb_mysql_query(
                        "INSERT INTO " . $cv . " (" . $p . "_champ, " . $p . "_origine, " . $p . "_" . $col . ")"
                            . " VALUES(" . $perso->idchamp . ", $object_id, '" . addslashes($url_val) . "')"
                    );
                    return true;
                }
                break;

            case 'resolve':
                // $c = identifiant a stocker ; $b = libelle attendu pour valider la coherence
                if (!$value_c) {
                    return false;
                }
                $mes_pp = new parametres_perso($prefix);
                if ($mes_pp->get_formatted_output(array($value_c), $perso->idchamp) == $value_b) {
                    $rqt_check = "SELECT 1 FROM " . $cv
                        . " WHERE " . $p . "_champ='" . $perso->idchamp . "'"
                        . " AND " . $p . "_origine='" . $object_id . "'"
                        . " AND " . $p . "_" . $col . "='" . addslashes($value_c) . "'";
                    if (($res2 = pmb_mysql_query($rqt_check)) && !pmb_mysql_num_rows($res2)) {
                        pmb_mysql_query(
                            "INSERT INTO " . $cv . " (" . $p . "_champ, " . $p . "_origine, " . $p . "_" . $col . ")"
                                . " VALUES(" . $perso->idchamp . ", $object_id, '" . addslashes($value_c) . "')"
                        );
                        return true;
                    }
                }
                break;

            case 'query_list':
            case 'query_auth':
                // $c = identifiant a stocker ; $a = libelle attendu pour valider la coherence
                if (!$value_c) {
                    return false;
                }
                $mes_pp = new parametres_perso($prefix);
                if ($mes_pp->get_formatted_output(array($value_c), $perso->idchamp) == $value_a) {
                    $rqt_check = "SELECT 1 FROM " . $cv
                        . " WHERE " . $p . "_champ='" . $perso->idchamp . "'"
                        . " AND " . $p . "_origine='" . $object_id . "'"
                        . " AND " . $p . "_" . $col . "='" . addslashes($value_c) . "'";
                    if (($res2 = pmb_mysql_query($rqt_check)) && !pmb_mysql_num_rows($res2)) {
                        pmb_mysql_query(
                            "INSERT INTO " . $cv . " (" . $p . "_champ, " . $p . "_origine, " . $p . "_" . $col . ")"
                                . " VALUES(" . $perso->idchamp . ", $object_id, '" . addslashes($value_c) . "')"
                        );
                        return true;
                    }
                }
                break;

            case 'date_inter':
                // Type non gere dans l'import zone 900 : le stockage utilise {prefix}_custom_dates
                // (table dediee avec date_start/date_end) qui requiert un encodage specifique non standard.
                break;

            case 'text':
            case 'comment':
            case 'html':
            case 'marclist':
            case 'text_i18n':
            case 'q_txt_i18n':
                // Valeur texte stockee directement selon le datatype (small_text ou text)
                if (!$value_a) {
                    return false;
                }
                $rqt_check = "SELECT 1 FROM " . $cv
                    . " WHERE " . $p . "_champ='" . $perso->idchamp . "'"
                    . " AND " . $p . "_origine='" . $object_id . "'"
                    . " AND " . $p . "_" . $col . "='" . addslashes($value_a) . "'";
                if (($res2 = pmb_mysql_query($rqt_check)) && !pmb_mysql_num_rows($res2)) {
                    pmb_mysql_query(
                        "INSERT INTO " . $cv . " (" . $p . "_champ, " . $p . "_origine, " . $p . "_" . $col . ")"
                            . " VALUES(" . $perso->idchamp . ", $object_id, '" . addslashes($value_a) . "')"
                    );
                    return true;
                }
                break;

            case 'date_box':
                // Conversion de la date en format ISO AAAA-MM-JJ avant stockage
                if (!$value_a) {
                    return false;
                }
                $val_db = DateHelper::formatDate($value_a);
                $rqt_check = "SELECT 1 FROM " . $cv
                    . " WHERE " . $p . "_champ='" . $perso->idchamp . "'"
                    . " AND " . $p . "_origine='" . $object_id . "'"
                    . " AND " . $p . "_date='" . addslashes($val_db) . "'";
                if (($res2 = pmb_mysql_query($rqt_check)) && !pmb_mysql_num_rows($res2)) {
                    pmb_mysql_query(
                        "INSERT INTO " . $cv . " (" . $p . "_champ, " . $p . "_origine, " . $p . "_date)"
                            . " VALUES(" . $perso->idchamp . ", $object_id, '" . addslashes($val_db) . "')"
                    );
                    return true;
                }
                break;

            case 'date_flot':
                // Valeur numerique flottante avec normalisation virgule -> point
                if (!$value_a) {
                    return false;
                }
                $val_db = (string)(float) str_replace(',', '.', $value_a);
                $rqt_check = "SELECT 1 FROM " . $cv
                    . " WHERE " . $p . "_champ='" . $perso->idchamp . "'"
                    . " AND " . $p . "_origine='" . $object_id . "'"
                    . " AND " . $p . "_float='" . addslashes($val_db) . "'";
                if (($res2 = pmb_mysql_query($rqt_check)) && !pmb_mysql_num_rows($res2)) {
                    pmb_mysql_query(
                        "INSERT INTO " . $cv . " (" . $p . "_champ, " . $p . "_origine, " . $p . "_float)"
                            . " VALUES(" . $perso->idchamp . ", $object_id, '" . addslashes($val_db) . "')"
                    );
                    return true;
                }
                break;

            default:
                // Nouveau type non encore pris en charge : aucune action pour eviter une insertion incorrecte.
                break;
        }

        return false;
    }
}
