<?php
// +-------------------------------------------------+
// © 2002-2004 PMB Services / www.sigb.net pmb@sigb.net et contributeurs (voir www.sigb.net)
// +-------------------------------------------------+
// $Id: entities_analysis_controller.class.php,v 1.5.8.3 2026/06/02 07:53:44 dgoron Exp $

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

global $class_path;
require_once ($class_path."/entities/entities_records_controller.class.php");

class entities_analysis_controller extends entities_records_controller {

	protected $url_base = './catalog.php?categ=serials&sub=analysis';

	protected $analysis_id = 0;

	protected $bulletin_id = 0;

	protected $serial_id = 0;

	protected $model_class_name = 'analysis';

	public function get_object_instance() {
		$model_class_name = $this->get_model_class_name();
		$object_instance = new $model_class_name($this->id, $this->bulletin_id);
		if(method_exists($model_class_name, 'set_controller')) {
			$model_class_name::set_controller($this);
		}
		return $object_instance;
	}

	/**
	 * 8 = droits de modification
	 */
	protected function get_acces_m() {
		global $PMBuserid;
		$acces_m=1;
		$acces_j = $this->dom_1->getJoin($PMBuserid, 8, 'bulletin_notice');
		if ($this->bulletin_id) {
    		$q = "select count(1) from bulletins $acces_j where bulletin_id=".$this->bulletin_id;
    		$r = pmb_mysql_query($q);
    		if(pmb_mysql_result($r,0,0)==0) {
    			$acces_m=0;
    			if (!$this->analysis_id) {
    				$this->error_message = 'mod_bull_error';
    			} else {
    				$this->error_message = 'mod_depo_error';
    			}
    		}
		} else {
		    // On tente de fournir un identifiant d'article sans fournir l'identifiant du bulletin => interdit
		    if ($this->id || $this->analysis_id) {
		        $acces_m=0;
		        $this->error_message = 'mod_depo_error';
		    }
		}
		return $acces_m;
	}

	protected function get_page_title($duplicate=false) {
		global $msg, $serial_header;

		if(!$this->id) {
			// pas d'id, c'est une création
			return str_replace('!!page_title!!', $msg[4000].$msg[1003].$msg[4022], $serial_header);
		} else {
			if($duplicate) {
				return str_replace('!!page_title!!', $msg[4000].$msg[1003].$msg['analysis_duplicate'], $serial_header);
			} else {
				return str_replace('!!page_title!!', $msg[4000].$msg[1003].$msg[4023], $serial_header);
			}
		}
	}

	public function proceed_form() {
	    global $charset;

		print $this->get_page_title();
		$myAnalysis = $this->get_object_instance();
        print "<div class='row'><div class='perio-barre'>".$this->get_link_parent();
        if (!empty($myAnalysis->tit1)) {
            print "<h3>".htmlentities($myAnalysis->tit1, ENT_QUOTES, $charset)."</h3>";
		}
		print "</div></div><br />";
		print "<div class='row'>".$myAnalysis->analysis_form()."</div>";
	}

	public function proceed_duplicate() {
	    global $charset;

		print $this->get_page_title(true);
		$myAnalysis = $this->get_object_instance();
		$myAnalysis->id = 0;
		$myAnalysis->duplicate_from_id = $this->id;
		print "<div class='row'><div class='perio-barre'>".$this->get_link_parent()."<h3>".htmlentities($myAnalysis->tit1, ENT_QUOTES, $charset)."</h3></div></div><br />";

		print "<div class='row'>".$myAnalysis->analysis_form()."</div>";
	}

	protected function get_serialized_data_form() {
	    $tab = new stdClass();
	    $tab->POST = addslashes_array($_POST);
	    $tab->GET = addslashes_array($_GET);
	    return urlencode(serialize($tab));
	}
	
	protected function get_action_forcing_form() {
	    return "./catalog.php?categ=serials&sub=analysis&action=update&bul_id=".$this->bulletin_id."&analysis_id=".$this->id;
	}
	
	protected function get_display_doublon($entity = []) {
	    if($entity['niveau_biblio'] != 's' && $entity['niveau_biblio'] != 'a') {
	        // notice de monographie
	        $nt = new mono_display($entity['id'],1,notice::get_permalink($entity['id']));
	    } elseif($entity['niveau_biblio'] == 's'){
	        // on a affaire à un périodique
	        $nt = new serial_display($entity['id'],1,serial::get_permalink($entity['id']));
	    }else{
	        // on a affaire à un article
	        $bulletin_id = analysis::getBulletinIdFromAnalysisId($entity['id']);
	        $nt = new serial_display($entity['id'],1,'',bulletinage::get_permalink($bulletin_id));
	    }
	    return "
		<div class='row'>
            $nt->result
 	    </div>
		<script>document.getElementById('el".$entity['id']."Child').setAttribute('startOpen','Yes');</script>
		<script type='text/javascript'>document.forms['dummy'].elements['ok'].focus();</script>";
	}
	
	protected function duplication_control() {
	    global $pmb_notice_controle_doublons;
	    global $ret_url, $forcage;
	    
	    if ($forcage == 1) {
	        $tab= unserialize( urldecode($ret_url) );
	        foreach($tab->GET as $key => $val){
	            $GLOBALS[$key] = $val;
	        }
	        foreach($tab->POST as $key => $val){
	            $GLOBALS[$key] = $val;
	        }
	    } elseif ($pmb_notice_controle_doublons != 0 && !$this->id) {
	        //Si control de dédoublonnage activé
	        $requete="select signature, niveau_biblio ,notice_id from notices where signature='".$this->signature."'";
	        if($this->serial_id)	$requete.= " and notice_id != '".$this->id."' ";
	        //$requete.= " limit 1 ";
	        
	        $result=pmb_mysql_query($requete);
	        if (pmb_mysql_num_rows($result)) {
	            //affichage de l'erreur, en passant tous les param postés (serialise) pour l'éventuel forcage
	            print $this->get_display_forcing_form();
	            $entities = [];
	            while ($row = pmb_mysql_fetch_object($result)) {
	                $entities[] = ['id' => $row->notice_id, 'niveau_biblio' => $row->niveau_biblio];
	            }
	            print $this->get_display_doublons($entities);
	            exit();
	        }
	    }
	} //fin du controle de dedoublonage
	
	// Methode provisoire : devrait se faire dans proceed_update
	public function proceed_duplication_control() {
	    $sign = new notice_doublon();
	    $this->signature = $sign->gen_signature();
	    $this->duplication_control();
	}
	
	public function proceed_update() {
	    global $pmb_synchro_rdf, $synchro_rdf;
	    
// 	    $sign = new notice_doublon();
// 	    $this->signature = $sign->gen_signature();
// 	    $this->duplication_control();

        //Traitement des périos et bulletins
	    global $perio_type, $bull_type;
	    global  $f_perio_new, $f_perio_new_issn;
	    global  $f_bull_new_num, $f_bull_new_date, $f_bull_new_mention, $f_bull_new_titre;
	    //Perios
	    if($perio_type == 'insert_new' && !$this->serial_id){
	        $new_serial = new serial();
	        $values = array();
	        $values['tit1'] = $f_perio_new;
	        $values['code'] = $f_perio_new_issn;
	        $values['niveau_biblio'] = "s";
	        $values['niveau_hierar'] = "1";
	        $this->serial_id =  $new_serial->update($values);
	        if($pmb_synchro_rdf){
	            $synchro_rdf->addRdf($this->serial_id,0);
	        }
	    }
	    //Bulletin
	    if($bull_type == 'insert_new' && !$this->bulletin_id) {
	        $req = "insert into bulletins set bulletin_numero='".$f_bull_new_num."',
			  mention_date='".$f_bull_new_mention."',
			  date_date='".$f_bull_new_date."',
			  bulletin_titre='".$f_bull_new_titre."',
			  bulletin_notice='".$this->serial_id."'";
	        pmb_mysql_query($req);
	        $this->bulletin_id = pmb_mysql_insert_id();
	        if($pmb_synchro_rdf){
	            $synchro_rdf->addRdf(0,$this->bulletin_id);
	        }
	    }
	    if($this->id && $this->bulletin_id) {
	        //Assurons-nous que la relation dans analysis existe
	        //Traité pour le cas des articles de périodique orphelins
	        import_records::insert_relation_analysis_bulletin($this->id, $this->bulletin_id);
	    }
	    $myAnalysis = new analysis($this->id, $this->bulletin_id);
	    $myAnalysis->signature = $this->signature;
	    $myAnalysis->set_properties_from_form();
	    $myAnalysis->save();
	    $this->id = $myAnalysis->id;

	    return $myAnalysis->id;
	}

	public function proceed_delete() {
		global $msg;
		global $pmb_archive_warehouse;

		$myAnalysis = $this->get_object_instance();
		if ($pmb_archive_warehouse) {
			analysis::save_to_agnostic_warehouse(array(0=>$this->analysis_id),$pmb_archive_warehouse);
		}
		$result = $myAnalysis->analysis_delete();
		if($result) {
			print "<div class=\"row\"><div class=\"msg-perio\" size=\"+2\">".$msg['catalog_notices_suppression']."</div></div>";
			print $this->get_redirection_form();
		} else {
				error_message(	$msg['catalog_serie_supp_depouill'] ,
						$msg['catalog_serie_supp_depouill_imp'],
						1,
						$this->get_permalink()."&serial_id=".$this->serial_id);
		}
	}

	public function proceed_move() {
		global $msg, $serial_header;
		global $to_bul;

		$myAnalysis = $this->get_object_instance();
		if(!$to_bul) {
			// affichage d'un form pour déplacer un article de périodique
			echo str_replace('!!page_title!!', $msg['4000'].$msg['1003'].$msg['analysis_move'], $serial_header);
			print "<div class='row'><div class='perio-barre'>".$this->get_link_parent()."<h3>".$myAnalysis->tit1."</h3></div></div><br />";
			print "<div class='row'>".$myAnalysis->move_form()."</div>";
		} else {
			$myAnalysis->move($to_bul);
			//Redirection
			print "<script>document.location='".$this->get_permalink($to_bul)."'</script>";
		}
	}

	public function proceed_orphan_form() {
	    global $charset;

	    print $this->get_page_title();
	    $myAnalysis = $this->get_object_instance();
	    print "<div class='row'><div class='perio-barre'>".$this->get_link_parent()."<h3>".htmlentities($myAnalysis->tit1, ENT_QUOTES, $charset)."</h3></div></div><br />";

	    print "<div class='row'>".$myAnalysis->analysis_form(true)."</div>";
	}

	protected function get_permalink($id=0) {
	    if(!$id) {
	        $id = $this->bulletin_id;
	    }
		return $this->url_base."&sub=bulletinage&action=view&bul_id=" . intval($id);
	}

	protected function get_link_parent() {
	    global $msg, $charset;

		$myBul = new bulletinage($this->bulletin_id);
		// lien vers la notice chapeau
		$link_parent = "<a href=\"".$this->url_base."\">";
		$link_parent .= $msg[4010]."</a>";
		$link_parent .= "<img src='".get_url_icon('d.gif')."' class='align_middle' >";
		$link_parent .= "<a href=\"".$this->url_base."&sub=view&serial_id=";
		$link_parent .= $myBul->bulletin_notice."\">".htmlentities($myBul->get_serial()->tit1, ENT_QUOTES, $charset).'</a>';
		$link_parent .= "<img src='".get_url_icon('d.gif')."' class='align_middle' >";
		$link_parent .= "<a href=\"".$this->get_permalink()."\">";
		if ($myBul->bulletin_numero) $link_parent .= $myBul->bulletin_numero." ";
		if ($myBul->mention_date) $link_parent .= " (".$myBul->mention_date.") ";
		$link_parent .= "[".$myBul->aff_date_date."]";
		$link_parent .= "</a> <img src='".get_url_icon('d.gif')."' class='align_middle' >";
		return $link_parent;
	}

	public function get_display_view($id=0) {
	    global $msg, $current_module;
	    global $id_form;
	    
	    $myAnalysis = new analysis($id, $this->bulletin_id);
	    $retour = bulletinage::get_permalink($myAnalysis->get_bulletinage()->bulletin_id);
	    return "
        <div class='row'><div class='msg-perio'>".$msg['maj_encours']."</div></div>
		<form class='form-$current_module' name=\"dummy\" method=\"post\" action=\"$retour\" style=\"display:none\">
			<input type=\"hidden\" name=\"id_form\" value=\"$id_form\">
		</form>
		<script type=\"text/javascript\">document.dummy.submit();</script>";
	}
	
	public function get_serial_id() {
	    return $this->serial_id;
	}
	
	public function set_serial_id($serial_id=0) {
	    $this->serial_id = (int) $serial_id;
	}

	public function get_bulletin_id() {
	    return $this->bulletin_id;
	}
	
	public function set_bulletin_id($bulletin_id=0) {
	    $this->bulletin_id = (int) $bulletin_id;
	}
}
