<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: ChunkPMB.php,v 1.6.2.2 2025/06/27 14:21:07 rtigero Exp $

namespace Pmb\ImportExport\Models\Chunks\ChunkPMB;

use authorities_caddie;
use authorities_collection;
use authority;
use authperso;
use authperso_authority;
use caddie_root;
use Pmb\Common\Helper\HelperEntities;
use Pmb\ImportExport\Library\RdfConverter;
use Pmb\ImportExport\Models\Chunks\Chunk;
use Pmb\ImportExport\Models\Ontology\Store;
use Pmb\ImportExport\Models\Profiles\ProfileExport;
use rdf_entities_converter_controller;

class ChunkPMB extends Chunk
{
    private const EXPORT_TYPE_ALL = 1;
    private const EXPORT_TYPE_CART = 2;

    private array $entities = array();
    private Store $store;
    private RdfConverter $rdfConverter;
    private array $depthByEntities = array();

    protected function initialize()
    {
        if (!$this->isInitialized) {
            global $opac_url_base;

            $this->isInitialized = true;

            if (isset($this->parameters["profile"]) && is_numeric($this->parameters["profile"])) {
                $profile = new ProfileExport($this->parameters["profile"]);
                $this->depthByEntities = $profile->getDepthByEntities();
            }

            $this->store = new Store("rdfstore");
            $depth = ($this->parameters["exportType"] == self::EXPORT_TYPE_ALL) ? RdfConverter::MIN_DEPTH : RdfConverter::MAX_DEPTH;
            $this->rdfConverter = new RdfConverter(array(), $opac_url_base, $depth, $this->store, $this->depthByEntities);
            authorities_collection::setOptimizer(authorities_collection::OPTIMIZE_MEMORY);

            switch (intval($this->parameters["exportType"])) {
                case self::EXPORT_TYPE_ALL:
                    foreach (HelperEntities::get_entities_namespace() as $namespace) {
                        $this->entities[$namespace] = array();
                        $converterClass = rdf_entities_converter_controller::get_entity_converter_name_from_type($namespace);
                        if (! empty($converterClass) && ! empty($converterClass::$table_key) && ! empty($converterClass::$table_name)) {
                            $query = "SELECT " . $converterClass::$table_key . " FROM " . $converterClass::$table_name;
                            //Traitement particulier pour les notices pour reprendre le paramétrage de l'ancien export
                            if ($namespace == "record" && ($this->parameters["owner"] || ! empty($this->parameters["typdoc"]) || ! empty($this->parameters["statutes"]))) {
                                $query .= ", exemplaires WHERE expl_notice = notice_id";
                                if ($this->parameters["owner"]) {
                                    $query .= " AND expl_owner = '" . $this->parameters["owner"] . "'";
                                }
                                if (! empty($this->parameters["typdoc"])) {
                                    $query .= " AND expl_typdoc IN (" . implode(",", $this->parameters["typdoc"]) . ")";
                                }
                                if (! empty($this->parameters["statutes"])) {
                                    $query .= " AND expl_statut IN (" . implode(",", $this->parameters["statutes"]) . ")";
                                }
                                $query .= " GROUP BY " . $converterClass::$table_key;
                            }
                            $result = pmb_mysql_query($query);
                            if (pmb_mysql_num_rows($result)) {
                                while ($row = pmb_mysql_fetch_assoc($result)) {
                                    $this->entities[$namespace][] = $row[$converterClass::$table_key];
                                }
                                pmb_mysql_free_result($result);
                            }
                        }
                    }
                    break;
                case self::EXPORT_TYPE_CART:
                    $entitiesNamespaces = array_flip(HelperEntities::get_entities_namespace());
                    $caddieSettings = explode("|", $this->parameters["exportCartSelect"]);
                    $caddieType = $caddieSettings[0];
                    $caddieId = $caddieSettings[1];
                    $caddie = caddie_root::get_instance_from_object_type($caddieType, $caddieId);
                    $type = $this->getTypeFromCaddieType($caddieType);
                    $this->entities[$type] = array();

                    if ($type != "") {
                        if ($caddie instanceof authorities_caddie && array_key_exists($type, $entitiesNamespaces)) {
                            $authorityType = authority::$type_table[$entitiesNamespaces[$type]];
                            $query = "SELECT num_object FROM authorities WHERE id_authority IN (" . implode(",", $caddie->get_cart()) . ") AND type_object = '$authorityType'";
                            $result = pmb_mysql_query($query);
                            if (pmb_mysql_num_rows($result)) {
                                while ($row = pmb_mysql_fetch_assoc($result)) {
                                    $this->entities[$type][] = $row["num_object"];
                                }
                            }
                        } else {
                            $this->entities[$type] = $caddie->get_cart();
                        }
                    }
                    break;
            }
            $this->rdfConverter->setRootEntities($this->entities);
        }
    }

    private function getTypeFromCaddieType($caddieType)
    {
        switch ($caddieType) {
            case "NOTI":
                return "record";
            case "EXPL":
                return "expl";
            case "AUTHORS":
                return "author";
            case "CATEGORIES":
                return "category";
            case "PUBLISHERS":
                return "publisher";
            case "COLLECTIONS":
                return "collection";
            case "SUBCOLLECTIONS":
                return "subcollection";
            case "SERIES":
                return "serie";
            case "TITRES_UNIFORMES":
                return "work";
            case "INDEXINT":
                return "indexint";
            case "AUTHPERSO":
                return "authperso";
            case "CONCEPTS":
                return "concept";
            default:
                return "";
        }
    }


    public function next()
    {
        $this->initialize();
        foreach ($this->entities as $entityType => $entities) {
            $type = $entityType;
            foreach ($entities as $entityId) {
                if ($entityType == "authperso") {
                    $authperso = new authperso_authority($entityId);
                    $type = "authperso_" . $authperso->get_authperso_num();
                }
                $this->rdfConverter->addEntities(array(array("type" => $type, "id" => $entityId)));
                $this->rdfConverter->run();
                $rdf = $this->rdfConverter->generateRdf("compact");
                $this->rdfConverter->clear();

                yield $rdf;
            }
        }
    }
}
