<?php
/**
 * Gestion du formulaire de d'enregistrerment de requête
 *
 * @plugin     Biodiv
 * @copyright  2024
 * @author     Renaud LAURETTE
 * @licence    GNU/GPL
 * @package    SPIP\Biodiv\Formulaires
 */

if (!defined('_ECRIRE_INC_VERSION')) {
	return;
}

include_spip('inc/actions');
include_spip('inc/editer');


function formulaires_enregistrer_requete_charger($requete=null) {
	if(is_numeric($requete)&&($requete == intval($requete))) return false;
	spip_log("RQ -- Charger $requete","rq."._LOG_INFO_IMPORTANTE);
	$valeurs = array();
	$valeurs['requete'] = $requete;
	return $valeurs;
}

function formulaires_enregistrer_requete_verifier($requete=null) {
	spip_log("RQ -- vérifier $requete","rq."._LOG_INFO_IMPORTANTE);
	return array();
}


function formulaires_enregistrer_requete_traiter($requete=null) {
	include_spip('action/ajouter_documents');
	include_spip('action/editer_objet');
	$ajouter_un_document = charger_fonction('ajouter_un_document', 'action');

	$upload_dir = _DIR_TMP . "requetes/";	
	$file = $upload_dir . "$requete.json";
	$ida = session_get('id_auteur');
	$fcible = "rq$ida". '_' .time() . '.requete';
	$autdata = sql_fetsel(array('nom'),'spip_auteurs',"id_auteur=".intval($ida));

	spip_log("RQ -- Traiter $requete","rq."._LOG_INFO_IMPORTANTE);
	spip_log("RQ -- Source $file Cible $fcible","rq."._LOG_INFO_IMPORTANTE);
	$download = array(
		'name' => $fcible,
		'tmp_name' => $file,
		'type' => 'application/json',
		'size' => filesize($file),
		'error' => UPLOAD_ERR_OK
		);	
	
	 $status = array();
	 if($docid = $ajouter_un_document('new',$download,null, null,'document')) {
	 	 objet_modifier('document', $docid, array(
	 	 	 'titre' => $_POST['titre'] ?? '',
	 	 	 'descriptif' => $_POST['descriptif'] ?? '',
	 	 	 'credits' => $autdata['nom'],
	 	 	 'statut' => 'publie'
	 	 	 ));
	 	 $status['message_ok'] = _T('requete:succes_enregistrement',array('doc'=>$docid));
	 	 $status['redirect'] = generer_url_public('observation_resultat',array('rq'=>$docid),false, false);
	 } else {
	 	 $status['message_erreur'] = _T('requete:echec_enregistrement',array('rq'=>$requete));
	 }
	return $status;
}

