<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: demandes_theme.class.php,v 1.2.4.2 2026/02/12 14:35:06 dbellamy Exp $

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

global $include_path;
require_once $include_path . "/templates/liste_simple.tpl.php";

class demandes_theme
{

    public $id = 0;

    public $libelle = '';

    protected $types = [];

    protected $allowed_types = '[]';

    protected $used_types = [];

    protected $default_type = 0;


    public function __construct($id = 0)
    {
        $this->id = intval($id);
        $this->getData();
    }

    /**
     * Recuperation des proprietes
     *
     */
    public function getData()
    {
        if (!$this->id) return;

        $requete = 'SELECT * FROM demandes_theme WHERE id_theme=' . $this->id;
        $result = pmb_mysql_query($requete);
        if (!pmb_mysql_num_rows($result)) {
            pmb_error::get_instance(static::class)->add_message("not_found", "not_found_object");
            return;
        }
        $data = pmb_mysql_fetch_object($result);
        $this->libelle = $data->libelle_theme;
        $this->allowed_types = encoding_normalize::json_decode($data->allowed_types, true);

        $this->fetchTypes();
    }

    public function getAllowedTypes()
    {
        return $this->allowed_types;
    }

    /**
     * Recupere la liste des types de demandes
     *
     * @return array(id_type => libelle_type)
     */
    protected function fetchTypes()
    {
        $requete = 'SELECT id_type, libelle_type FROM demandes_type order by libelle_type';
        $result = pmb_mysql_query($requete);
        if (pmb_mysql_num_rows($result)) {
            while ($row = pmb_mysql_fetch_assoc($result)) {
                $this->types[$row['id_type']] = $row['libelle_type'];
            }
        }
        return $this->types;
    }

    /**
     * Recupere les types de demandes utilises pour le theme courant
     *
     * @return array(id_type => 1)
     */
    protected function fetchUsedTypes()
    {
        $this->used_types = [];
        $requete = "SELECT distinct(type_demande) FROM demandes WHERE theme_demande = " . $this->id;
        $result = pmb_mysql_query($requete);
        if (pmb_mysql_num_rows($result)) {
            while ($row = pmb_mysql_fetch_row($result)) {
                $this->used_types[$row[0]] = 1;
            }
        }
        return $this->used_types;
    }

    public function get_content_form()
    {
        $interface_content_form = new interface_content_form(static::class);
        $interface_content_form->add_element('libelle', '103')
            ->add_input_node('text', $this->libelle);

        $interface_content_form->add_element('actions')
            ->add_html_node($this->get_actions_form());

        return $interface_content_form->get_display();
    }

    public function get_form()
    {
        global $msg;

        $interface_form = new interface_admin_form('simple_list_form');
        if (!$this->id) {
            $interface_form->set_label($msg['demandes_ajout_theme']);
        } else {
            $interface_form->set_label($msg['demandes_modif_theme']);
        }
        $interface_form->set_object_id($this->id)
            ->set_confirm_delete_msg($msg['demandes_del_theme'])
            ->set_content_form($this->get_content_form())
            ->set_table_name('demandes_theme')
            ->set_field_focus('libelle');
        return $interface_form->get_display();
    }

    public function get_actions_form()
    {
        global $msg, $charset;

        $form = "
        <table class='demandes-actions-themes'>
            <tr>
                <th>" . $msg['demandes_action_theme_type'] . "</th>
                <th>" . $msg['demandes_action_theme_allow_type'] . "</th>
                <th>" . $msg['demandes_action_theme_default_type'] . "</th>
            </tr>";

        $used_types = $this->fetchUsedTypes();

        foreach ($this->types as $id => $type) {

            $used = false;
            if (!empty($used_types[$id])) {
                $used = true;
            }

            $checked = false;
            if ($used || is_null($this->allowed_types) || (1 == $this->allowed_types[$id])) {
                $checked = true;
            }

            $form .= "
            <tr>
                <td>" . htmlentities($type, ENT_QUOTES, $charset) . "</td>
                <td>
                    <label for='type_" . $id . "_1'>" . $msg['40'] . "</label>&nbsp;
                    <input type='radio' id='type_" . $id . "_1' name='types[" . $id . "]' value='1'" . ($checked ? " checked" : "") . ($used ? " disabled" : "") . " />
                    <label for='type_" . $id . "_0'>" . $msg['39'] . "</label>&nbsp;
                    <input type='radio' id='type_" . $id . "_0' name='types[" . $id . "]' value='0'" . (!$checked ? " checked" : "") . ($used ? " disabled" : "") . " />
                </td>
                <td><input type='radio' name='default_type' value='" . $id . "'" . (($this->allowed_types['default'] == $id) ? " checked" : "") . "/></td>
            </tr>";
        }

        $form .= "
        </table>";
        return $form;
    }

    public function set_properties_from_form()
    {
        global $libelle, $types, $default_type;

        $this->libelle = stripslashes($libelle);

        // On recupere les types deja utilises afin de ne pas les supprimer des valeurs possibles
        $this->allowed_types = $this->fetchUsedTypes();

        foreach ($types as $id => $type) {
            $this->allowed_types[$id] = intval($type);
        }
        $this->default_type = 0;
        if (isset($default_type) && ($this->allowed_types[$default_type] == 1)) {
            $this->default_type = intval($default_type);
        }
    }

    public function save()
    {
        $allowed_types = $this->allowed_types;
        $allowed_types['default'] = $this->default_type;

        $json_allowed_types = encoding_normalize::json_encode($allowed_types);
        if ($this->id) {
            $requete = "UPDATE demandes_theme set libelle_theme='" . addslashes($this->libelle) . "' , allowed_types = '" . addslashes($json_allowed_types) . "' where id_theme='" . $this->id . "'";
            pmb_mysql_query($requete);
        } else {
            $requete = "INSERT INTO demandes_theme set libelle_theme='" . addslashes($this->libelle) . "', allowed_types = '" . addslashes($json_allowed_types) . "'";
            pmb_mysql_query($requete);
            $this->id = pmb_mysql_insert_id();
        }
    }

    public static function check_data_from_form()
    {
        global $libelle;

        if (empty($libelle)) {
            return false;
        }
        return true;
    }

    public static function delete($id)
    {
        $id = intval($id);
        if ($id) {
            $total = pmb_mysql_num_rows(pmb_mysql_query("select * from demandes where theme_demande = '" . $id . "'"));
            if ($total == 0) {
                $requete = "DELETE FROM demandes_theme where id_theme='" . $id . "'";
                pmb_mysql_query($requete);
                return true;
            } else {
                pmb_error::get_instance(static::class)->add_message("321", 'demandes_used_theme');
                return false;
            }
        }
        return true;
    }
}
