<?php
// +-------------------------------------------------+
// | 2002-2011 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: custom_fields.class.php,v 1.2.4.14 2026/07/09 13:59:50 dbellamy Exp $

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

class custom_fields {

    protected static $type = '';

    protected static $is_repeatable = false;

    protected static $aggregator_context = false;

    public static function get_aff_values($field) {
        return ($field['VALUES'] ? $field['VALUES'] : array(""));
    }

    public static function get_formatted_value($field, $value) {
        return $value;
    }

    public static function get_display_value($field, $indice, $value) {
        return '';
    }

    public static function get_block_dnd($field, $indice, $html, $value='') {
        global $charset;

        $field_name = $field['NAME'];
        return "
		<div id='customfield_".static::$type."_".$field_name."_".$indice."'  class='row' dragtype='customfield_".static::$type."_".$field_name."' draggable='yes' recept='yes' recepttype='customfield_".static::$type."_".$field_name."' handler='customfield_".static::$type."_".$field_name."_".$indice."_handle'
			dragicon='".get_url_icon('icone_drag_notice.png')."' dragtext=\"".htmlentities($value, ENT_QUOTES, $charset)."\" downlight=\"customfield_downlight\" highlight=\"customfield_highlight\"
			order='".$indice."' style='' >
			<span id=\"customfield_".static::$type."_".$field_name."_".$indice."_handle\" style=\"float:left; padding-right : 7px\"><img src='".get_url_icon('sort.png')."' style='width:12px; vertical-align:middle' /></span>
			".$html."
		</div>";
    }

    public static function get_block_value($value='') {
        switch (static::$type) {
            case 'comment':
            case 'html':
            case 'list':
            case 'marclist':
            case 'query_auth':
            case 'query_list':
            case 'resolve':
            case 'text_i18n':
            case 'text':
            case 'url':
                return $value."<br />";
                //Pour le RGAA : prévoir une encapsulation dans une div
//                return "<div>".$value."</div>";
            default :
                return $value;
        }
    }

    public static function get_display_values($field) {
        $options = $field['OPTIONS'][0];
        $values = static::get_aff_values($field);
        $indice = 0;
        $display = '';
        foreach ($values as $value) {
            $formatted_value = static::get_formatted_value($field, $value);
            $display_temp = static::get_display_value($field, $indice, $formatted_value);
            if(isset($options['REPEATABLE'][0]['value']) && $options['REPEATABLE'][0]['value']) {
                $button_add = '';
                switch (static::$type) {
                    case 'date_inter':
                    case 'resolve':
                    case 'text_i18n':
                    case 'url':
                        if (!$indice) {
                            $button_add=static::get_button_add($field);
                        }
                        break;
                    case 'date_box':
                        if (end($values) == $value) {
                            $button_add=static::get_button_add($field, '', ['id' => 'button_add_'.$field['NAME'].'_'.$field['ID']]);
                        }
                        break;
                    default:
                        break;
                }
                $display .= static::get_block_value($display_temp.$button_add);
//                 $display .= static::get_block_dnd($field, $indice, $display_temp.$button_add, $formatted_value);
            } else {
                $display .= static::get_block_value($display_temp);
            }
            $indice++;
        }
        return $display;
    }

    public static function aff($field,&$check_scripts) {
        global $msg;

        $options = $field['OPTIONS'][0];
        $values = static::get_aff_values($field);
        $afield_name = $field["ID"];
        $ret = "";
        if(isset($options['REPEATABLE'][0]['value']) && $options['REPEATABLE'][0]['value']) {
            switch (static::$type) {
                case 'resolve':
                case 'text_i18n':
                case 'url':
                    $ret .= get_js_function_dnd(static::$type, $field['NAME']);
                    $ret .= static::get_button_add($field);
                    break;
//                 default:
//                     $ret .= static::get_button_add($field);
//                     break;
                case "multimedia":
                	//Le bouton d'ajout est géré ultérieurement
                	break;
            }
        }
        $ret .= static::get_display_values($field);

        if (isset($options['REPEATABLE'][0]['value']) && $options['REPEATABLE'][0]['value']) {
            $ret .= '<input id="customfield_'.static::$type.'_'.$afield_name.'" type="hidden" name="customfield_'.static::$type.'_'.$afield_name.'" value="'.(count($values)).'">';
            $cleaned_type = str_replace('_', '', static::$type);
            $ret .= '<div id="spaceformorecustomfield'.$cleaned_type.'_'.$afield_name.'"></div>';
            $ret .= get_custom_dnd_on_add();
            $ret .= static::get_js_function_add($field);
        }
        switch (static::$type) {
            case 'text':
            case 'comment':
                if ($field['MANDATORY']==1) {
                    $element_name = $field['NAME']."[]";
                    $mandatory_message = sprintf($msg["parperso_field_is_needed"], $field['ALIAS']);

                    //Champ repetable : elements["nom[]"] renvoie une RadioNodeList dont le getter
                    //.value vaut toujours "", meme si une occurrence est remplie.
                    //On boucle donc sur toutes les occurrences et on ne bloque que si aucune n'est remplie.
                    $check_scripts .= "
                        if ((function(el) {
                            if (!el) {
                                return true;
                            }
                            if (el.length === undefined) {
                                return el.value == \"\";
                            }
                            for (let i = 0; i < el.length; i++) {
                                if (el[i].value != \"\") {
                                    return false;
                                }
                            }
                            return true;
                        })(document.forms[0].elements[\"$element_name\"])) {
                            return cancel_submit(\"$mandatory_message\");
                        }
                    ";
                }
                break;
            case 'html':
                $check_scripts.= "if(document.forms[0].elements['".$field['NAME']."[]']) document.forms[0].elements['".$field['NAME']."[]'].value = dijit.byId('".$field['NAME']."').get('value');";
                if ($field['MANDATORY']==1) {
                    $caller = get_form_name();
                    $element_name = $field['NAME']."[]";
                    $mandatory_message = sprintf($msg["parperso_field_is_needed"], $field['ALIAS']);

                    //Champ repetable : elements["nom[]"] renvoie une RadioNodeList dont le getter
                    //.value vaut toujours "", meme si une occurrence est remplie.
                    //On boucle donc sur toutes les occurrences et on ne bloque que si aucune n'est remplie.
                    $check_scripts .= "
                        if ((function(el) {
                            if (!el) {
                                return true;
                            }
                            if (el.length === undefined) {
                                return el.value == \"\";
                            }
                            for (let i = 0; i < el.length; i++) {
                                if (el[i].value != \"\") {
                                    return false;
                                }
                            }
                            return true;
                        })(document.forms[\"$caller\"].elements[\"$element_name\"])) {
                            return cancel_submit(\"$mandatory_message\");
                        }
                    ";
                }
                break;
            default:
                if ($field['MANDATORY'] == 1) {
                    $caller = get_form_name();
                    $element_name = $field['NAME']."[]";
                    $mandatory_message = sprintf($msg["parperso_field_is_needed"], $field['ALIAS']);

                    //Champ repetable : elements["nom[]"] renvoie une RadioNodeList dont le getter
                    //.value vaut toujours "", meme si une occurrence est remplie.
                    //On boucle donc sur toutes les occurrences et on ne bloque que si aucune n'est remplie.
                    $check_scripts .= "
                        if ((function(el) {
                            if (!el) {
                                return true;
                            }
                            if (el.length === undefined) {
                                return el.value == \"\";
                            }
                            for (let i = 0; i < el.length; i++) {
                                if (el[i].value != \"\") {
                                    return false;
                                }
                            }
                            return true;
                        })(document.forms[\"$caller\"].elements[\"$element_name\"])) {
                            return cancel_submit(\"$mandatory_message\");
                        }
                    ";
                }
                break;
        }
        return $ret;
    }

    protected static function is_repeatable_field($field) {
        $options = $field['OPTIONS'][0];
        if (!empty($options['REPEATABLE'][0]['value'])) {
            return true;
        }
        if ($options["AUTORITE"][0]["value"] == "yes" && !empty($options['MULTIPLE'][0]['value']) && $options['MULTIPLE'][0]['value']=="yes") {
            return true;
        }
        return false;
    }

    public static function aff_aggregator($field,&$check_scripts) {
        $aff = array();
        if (static::is_repeatable_field($field)) {
            static::$aggregator_context = true;
            $aff['ADD_EVENT'] = static::get_event_button_add($field);
            $aff['DISPLAY'] = static::aff($field, $check_scripts);
            static::$aggregator_context = false;
        } else {
            $aff['ADD_EVENT'] = '';
            $aff['DISPLAY'] = static::aff($field, $check_scripts);
        }
        return $aff;
    }

    protected static function get_chk_values($name) {
        global ${$name};
        return ${$name};
    }

    protected static function has_chk_mandatory() {
        return false;
    }

    public static function chk($field,&$check_message) {
        global $msg;

        $name=$field['NAME'];
        global ${$name};
        $val=static::get_chk_values($name);

        if(static::has_chk_mandatory()) {
            if ($field['MANDATORY']==1) {
                if ((empty($val))||(!count($val))||((count($val)==1)&&($val[0]==""))) {
                    $check_message=sprintf($msg["parperso_field_is_needed"],$field['ALIAS']);
                    return 0;
                }
            }
        }

        $check_datatype_message = "";
        $val_1 = chk_datatype($field, $val, $check_datatype_message);
        if (!empty($check_datatype_message)) {
            $check_message = $check_datatype_message;
            return 0;
        }
        ${$name} = $val_1;
        return 1;
    }

//     public static function val($field, $value) {

//     }

    public static function get_formatted_label_aff_filter($label) {
        return $label;
    }

    public static function aff_filter($field,$varname,$multiple) {
        global $charset;

        $ret="<select id=\"".$varname."\" name=\"".$varname;
        $ret.="[]";
        $ret.="\" ";
        if ($multiple) $ret.="size=5 multiple";
        $ret.=" data-form-name='".$varname."' >\n";

        $values=$field['VALUES'];
        if ($values=="") $values=array();
        $options=$field['OPTIONS'][0];
        if (($options['UNSELECT_ITEM'][0]['VALUE']!="")||($options['UNSELECT_ITEM'][0]['value']!="")) {
            $ret.="<option value=\"".htmlentities($options['UNSELECT_ITEM'][0]['VALUE'],ENT_QUOTES,$charset)."\"";
            if ($options['UNSELECT_ITEM'][0]['VALUE']==$options['DEFAULT_VALUE'][0]['value']) $ret.=" selected";
            $ret.=">".htmlentities($options['UNSELECT_ITEM'][0]['value'],ENT_QUOTES,$charset)."</option>\n";
        }
        $resultat=pmb_mysql_query($options['QUERY'][0]['value']);
        while ($r=pmb_mysql_fetch_row($resultat)) {
            $ret.="<option value=\"".htmlentities($r[0],ENT_QUOTES,$charset)."\"";
            $as=array_search($r[0],$values);
            if (($as!==FALSE)&&($as!==NULL)) $ret.=" selected";
            $ret.=">".htmlentities(static::get_formatted_label_aff_filter($r[0]),ENT_QUOTES,$charset)."</option>\n";

        }
        $ret.= "</select>\n";
        return $ret;
    }

    public static function get_rgaa_label($field, $varname) {
        return '';
    }

    public static function get_button_browse($field, $link) {
        global $msg;

        $onclick_event = "openPopUp('".$link."', 'select_perso_".$field['ID']."', 700, 500, -2, -2, 'toolbar=no, dependent=yes, resizable=yes, scrollbars=yes')";
//         return "<input type='button' class='bouton' value='...' onclick=\"".$onclick_event."\" />";
        $interface_node_button = new interface_node_button();
        $interface_node_button->set_value($msg['custom_fields_browse_button'])
        ->set_onclick($onclick_event)
        ->set_aria_label(sprintf($msg['custom_fields_browse_aria_label'], $field['ALIAS']));
        return $interface_node_button->get_display();
    }

    protected static function get_event_button_add($field) {
        return '';
    }

    public static function get_button_add($field, $onclick_event='', $attrs=[]){
        global $msg;

        if (static::$aggregator_context == true) {
            return '';
        }
        if (empty($onclick_event)) {
            $onclick_event = static::get_event_button_add($field);
        }
//         return "<input type='button' class='bouton' value='+' onclick=\"".$onclick_event."\" />";
        $interface_node_button = new interface_node_button();
        $interface_node_button->set_value($msg['custom_fields_add_button'])
        ->set_onclick($onclick_event)
        ->set_aria_label(sprintf($msg['custom_fields_add_aria_label'], $field['ALIAS']));
        if (!empty($attrs['id'])) {
            $interface_node_button->set_id($attrs['id']);
        }
        return $interface_node_button->get_display();
    }

    public static function get_button_raz($field, $onclick_event='') {
        global $msg;

//         return "<input type='button' class='bouton' value='X' onclick=\"".$onclick_event."\" />";
        $interface_node_button = new interface_node_button();
        $interface_node_button->set_value($msg['custom_fields_raz_button'])
        ->set_onclick($onclick_event)
        ->set_aria_label(sprintf($msg['custom_fields_raz_aria_label'], $field['ALIAS']));
        return $interface_node_button->get_display();
    }

    /**
     * Methode a redefinir dans les classes derivees.
     * Une interface eut-ete souhaitable
     *
     * @param $field
     * @return string
     */
    protected static function get_js_function_add($field) {
        return '';
    }
}