<?php

// +-------------------------------------------------+
// © 2002-2014 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: contribution_area_item.class.php,v 1.4.8.1 2025/08/08 13:03:28 qvarin Exp $
if (stristr($_SERVER ['REQUEST_URI'], ".class.php")) {
    die("no access");
}

require_once($class_path.'/contribution_area/contribution_area_store.class.php');

/**
 * class contribution_area_item
 * Represente un item de contribution
 */
class contribution_area_item
{
    public const RECORD_TYPE = 'http://www.pmbservices.fr/ontology#record';
    public const SERIAL_TYPE = 'http://www.pmbservices.fr/ontology#serial';
    public const BULLETIN_TYPE = 'http://www.pmbservices.fr/ontology#bulletin';
    public const AUTHOR_TYPE = 'http://www.pmbservices.fr/ontology#author';
    public const PUBLISHER_TYPE = 'http://www.pmbservices.fr/ontology#publisher';
    public const WORK_TYPE = 'http://www.pmbservices.fr/ontology#work';
    public const COLLECTION_TYPE = 'http://www.pmbservices.fr/ontology#collection';
    public const SUB_COLLECTION_TYPE = 'http://www.pmbservices.fr/ontology#subcollection';
    public const INDEXINT_TYPE = 'http://www.pmbservices.fr/ontology#indexint';
    public const SERIE_TYPE = 'http://www.pmbservices.fr/ontology#serie';
    public const AUTHPERSO_TYPE = 'http://www.pmbservices.fr/ontology#authperso';
    public const CONCEPT_TYPE = 'http://www.w3.org/2004/02/skos/core#Concept';
    public const CATEGORY_TYPE = 'http://www.pmbservices.fr/ontology#category';

    /**
     *
     * @var string
     */
    private $uri = "";

    /**
     *
     * @var array
     */
    private $linked_data = [];

    /**
     *
     * @var contribution_area_store
     */
    private $store;

    protected $uriType;

    protected $sub;

    protected $form_id;

    protected $form_uri;

    protected $has_contributor;

    protected $parent_scenario_uri;

    protected $last_edit;

    protected $area;

    protected $displayLabel;

    protected $additionnal_data;

    protected $dynamic_properties = [];

    /**
     * Constructor
     *
     * @param string $uri
     */
    public function __construct($uri)
    {
        $this->uri = $uri;
        $this->store = new contribution_area_store();
        $this->fetch_data();
    }

    /**
     * Fetch data from the store for the current uri
     *
     * @return void
     */
    private function fetch_data()
    {
        if (!empty($this->uri)) {
            $query = "SELECT * WHERE {
                    <$this->uri> ?p ?o
                }";
            $this->store->get_datastore()->query($query);
            if ($this->store->get_datastore()->num_rows()) {
                $results = $this->store->get_datastore()->get_result();
                foreach ($results as $result) {
                    if ($result->o_type !== "uri") {
                        $prop = str_replace("http://www.pmbservices.fr/ontology#", "", $result->p);
                        $this->{$prop} = $result->o;
                    }

                    if ($result->p === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type") {
                        $this->uriType = $result->o;
                    }
                }
            }
        }
    }

    /**
     * Get linked data (can be called by __get)
     *
     * @return array
     */
    protected function get_linked_data()
    {
        if (!empty($this->linked_data)) {
            return $this->linked_data;
        }
        if (!empty($this->uri)) {
            $query = "SELECT * WHERE {
                    <$this->uri> ?p ?o
                }";
            $this->store->get_datastore()->query($query);
            if ($this->store->get_datastore()->num_rows()) {
                $results = $this->store->get_datastore()->get_result();
                foreach ($results as $result) {
                    if ($result->o_type === "uri") {
                        $prop = str_replace("http://www.pmbservices.fr/ontology#", "", $result->p);
                        if (!is_array($this->linked_data[$prop])) {
                            $this->linked_data[$prop] = [];
                        }
                        $this->linked_data[$prop][] = new contribution_area_item($result->o);
                    }
                }
            }
        }
        return $this->linked_data;
    }

    /**
     * Update item in the datastore
     *
     * @param integer $id
     * @param string $uriType
     * @return void
     */
    public static function update_item(int $id, string $uriType)
    {
        $store = new contribution_area_store();

        $query = 'SELECT * WHERE {
            ?uri pmb:identifier "' . $id . '" .
            ?uri rdf:type <' . $uriType . '> .
            ?uri pmb:displayLabel ?displayLabel .
        }';

        $store->get_datastore()->query($query);
        if ($store->get_datastore()->num_rows()) {
            $results = $store->get_datastore()->get_result();
            foreach ($results as $result) {
                $item = new contribution_area_item($result->uri);
                $item->update_display_label($item->computed_display_label($id));
            }
        }
    }

    /**
     * Update display label of the item in the datastore
     *
     * @param string $label
     * @return bool
     */
    public function update_display_label(string $label)
    {
        if (empty($label)) {
            return false;
        }

        $query = 'DELETE {
            <' . $this->uri . '> pmb:displayLabel ?o
        }';

        $success = $this->store->get_datastore()->query($query);
        if ($success) {
            $query = 'INSERT INTO <pmb> {
                <' . $this->uri . '> pmb:displayLabel "' . addslashes($label) . '" .
            }';
            return $this->store->get_datastore()->query($query);
        }
        return false;
    }

    /**
     * Check if the entity exists in the database
     *
     * @param integer $id
     * @return bool
     */
    public function entityExist(int $id)
    {
        switch ($this->uriType) {
            case contribution_area_item::SERIAL_TYPE:
            case contribution_area_item::RECORD_TYPE:
                $query = "SELECT 1 FROM notices WHERE notice_id = " . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::BULLETIN_TYPE:
                $query = "SELECT 1 FROM bulletins WHERE bulletin_id=" . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::AUTHOR_TYPE:
                $query = "SELECT 1 FROM authors WHERE author_id = " . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::PUBLISHER_TYPE:
                $query = "SELECT 1 FROM publishers WHERE ed_id = " . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::WORK_TYPE:
                $query = "SELECT 1 FROM titres_uniformes WHERE tu_id = " . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::COLLECTION_TYPE:
                $query = "SELECT 1 from collections where collection_id = " . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::SUB_COLLECTION_TYPE:
                $query = "SELECT 1 from sub_collections where sub_coll_id = " . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::INDEXINT_TYPE:
                $query = "SELECT 1 from indexint where indexint_id = " . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::SERIE_TYPE:
                $query = "SELECT 1 from series where serie_id=" . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::AUTHPERSO_TYPE:
                $query = "SELECT 1 from authperso where authperso_id = " . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::CONCEPT_TYPE:
                $query = "SELECT 1 from skos_fields_global_index where code_champ = 1 and code_ss_champ = 1 and value = " . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            case contribution_area_item::CATEGORY_TYPE:
                $query = "SELECT 1 from categories where category_id = " . $id;
                $result = pmb_mysql_query($query);
                return pmb_mysql_num_rows($result) == 1;

            default:
                return false;
        }
    }


    /**
     * Get the computed display label for an item
     *
     * @param int $id
     * @return string
     */
    public function computed_display_label(int $id)
    {
        switch ($this->uriType) {
            case contribution_area_item::SERIAL_TYPE:
            case contribution_area_item::RECORD_TYPE:
                $query = "SELECT IF(serie_name IS NOT NULL,IF(tnvol IS NOT NULL,concat(serie_name,', ',tnvol,'. ',tit1),concat(serie_name,'. ',tit1)),tit1) AS notice_name FROM notices";
                $query .= " LEFT JOIN series ON serie_id=tparent_id";
                $query .= " WHERE notice_id = " . $id;
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    return $r['notice_name'];
                }
                return '';

            case contribution_area_item::BULLETIN_TYPE:
                $query = "SELECT IF(bulletin_titre IS NOT NULL AND bulletin_titre != '',concat(bulletin_titre,' - ',bulletin_numero),bulletin_numero) AS bull_title FROM bulletins WHERE bulletin_id=" . $id;
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    return $r['bull_title'];
                }
                return '';

            case contribution_area_item::AUTHOR_TYPE:
                $query = "SELECT IF(author_rejete is not null and author_rejete!='',concat(author_name,', ',author_rejete),author_name) as author_name FROM authors WHERE author_id = " . $id;
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    return $r['author_name'];
                }
                return '';

            case contribution_area_item::PUBLISHER_TYPE:
                $query = "SELECT concat(
					ed_name,
					IF((ed_ville IS NOT NULL AND ed_ville!='') OR (ed_pays IS NOT NULL AND ed_pays!=''),' (',''),
					IF(ed_ville IS NOT NULL AND ed_ville!='',ed_ville,''),
					IF(ed_ville IS NOT NULL AND ed_ville!='' AND ed_pays IS NOT NULL AND ed_pays!='',' - ',''),
					IF(ed_pays IS NOT NULL AND ed_pays!='',ed_pays,''),
					IF((ed_ville IS NOT NULL AND ed_ville!='') OR (ed_pays IS NOT NULL AND ed_pays!=''),')','')
                ) AS ed FROM publishers WHERE ed_id = " . $id;
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    return $r['ed'];
                }
                return '';

            case contribution_area_item::WORK_TYPE:
                $query = "SELECT IF(tu_comment IS NOT NULL AND tu_comment!='',concat(tu_name,' : ',tu_comment),tu_name) as titres_uniforme_name FROM titres_uniformes WHERE tu_id = " . $id;
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    return $r['titres_uniforme_name'];
                }
                return '';

            case contribution_area_item::COLLECTION_TYPE:
                $query = "SELECT IF(collection_issn IS NOT NULL AND collection_issn!='',concat(collection_name,', ',collection_issn),collection_name) as collection_name from collections where collection_id = " . $id;
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    return $r['collection_name'];
                }
                return '';

            case contribution_area_item::SUB_COLLECTION_TYPE:
                $query = "SELECT IF(sub_coll_issn IS NOT NULL AND sub_coll_issn!='',concat(sub_coll_name,', ',sub_coll_issn),sub_coll_name) as subcoll_name from sub_collections where sub_coll_id = " . $id;
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    return $r['subcoll_name'];
                }
                return '';

            case contribution_area_item::INDEXINT_TYPE:
                $query = "SELECT IF(indexint_comment IS NOT NULL AND indexint_comment!='',concat(indexint_name,' : ',indexint_comment),indexint_name) as indexint_name from indexint where indexint_id = " . $id;
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    return $r['indexint_name'];
                }
                return '';

            case contribution_area_item::SERIE_TYPE:
                $query = "SELECT serie_name FROM series WHERE serie_id=" . $id;
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    return $r['serie_name'];
                }
                return '';

            case contribution_area_item::CONCEPT_TYPE:
                global $opac_default_lang;

                $query = "SELECT DISTINCT value as concept_name";
                $query .= " FROM skos_fields_global_index";
                $query .= " WHERE code_champ = code_ss_champ and code_champ = 1";
                $query .= " AND id_item=" . $id;
                $query .= " AND lang in ('" . addslashes($opac_default_lang) . "', '')";
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    return $r['concept_name'];
                }
                return '';

            case contribution_area_item::CATEGORY_TYPE:
                global $opac_categories_show_only_last;
                global $opac_default_lang;

                $query = "SELECT noeuds.id_noeud, categories.langue, num_renvoi_voir FROM noeuds";
                $query .= " JOIN categories ON noeuds.id_noeud = categories.num_noeud";
                $query .= " WHERE noeuds.id_noeud = " . intval($id);
                $query .= " AND categories.langue = '" . addslashes($opac_default_lang) . "'";
                $query .= " AND noeuds.not_use_in_indexation = 0";

                $displayLabel = '';
                $result = pmb_mysql_query($query);
                if (pmb_mysql_num_rows($result)) {
                    $r = pmb_mysql_fetch_assoc($result);
                    $category = new categories($r['id_noeud'], $r['langue']);

                    if ($r['num_renvoi_voir']) {
                        $category_see = new categories($r['num_renvoi_voir'], $r['langue']);
                        $displayLabel = $category->libelle_categorie." -> ";
                        $chemin=categories::listAncestorNames($category_see->num_noeud, $category_see->langue);
                        if ($opac_categories_show_only_last){
                            $displayLabel .= $category_see->libelle_categorie;
                        }else{
                            $displayLabel .= $chemin;
                        }
                        $displayLabel .= "@";
                    } else {
                        $chemin = categories::listAncestorNames($category->num_noeud, $category->langue);
                        if ($opac_categories_show_only_last) {
                            $displayLabel .= $category->libelle_categorie;
                        } else {
                            $displayLabel .= $chemin;
                        }
                    }

                    if (preg_match("#:~|^~#i",$chemin)) {
                        return '';
                    }

                    $thesaurus = thesaurus::getByEltId($r['id_noeud']);
                    if (null !== $thesaurus) {
                        $displayLabel = '[' . $thesaurus->get_translated_libelle_thesaurus() . '] ' . $displayLabel;
                    }
                }
                return $displayLabel;

            default:
                if (strpos($this->uriType, contribution_area_item::AUTHPERSO_TYPE) === 0) {
                    return entities::get_isbd($id, TYPE_AUTHPERSO);
                }
                return '';
        }
    }

    /**
     * Magic method to get properties
     *
     * @param string $name
     * @return mixed
     */
    public function __get($name)
    {
        if (method_exists($this, "get_".$name)) {
            return $this->{"get_".$name}();
        } elseif (isset($this->{$name})) {
            return $this->{$name};
        } elseif (isset($this->dynamic_properties[$name])) {
            return $this->dynamic_properties[$name];
        }
        return null;
    }

    /**
     * Magic method to set properties
     *
     * @param string $name
     * @param mixed $value
     */
    public function __set($name, $value)
    {
        if (property_exists($this, $name)) {
            $this->{$name} = $value;
        } else {
            $this->dynamic_properties[$name] = $value;
        }
    }
}
