<?php

require('../config.php');
dol_include_once('/recouvrement/lib/recouvrement.lib.php');

if (!($user->rights->recouvrement->dossier->admin)) accessforbidden();

require('../class/etape.class.php');
require('../class/procedure.class.php');
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';

llxHeader('',$langs->trans('RecouvrementAdmin'));

$head = recouvrement_admin_prepare_head($_REQUEST['id'],$_REQUEST['fk_procedure']);

dol_fiche_head($head, 'etape', $langs->trans("Recouvrement"), 0, 'recouvrementico@recouvrement');

$ATMdb = new TPDOdb;
$tbs = new TTemplateTBS;
$etape = new TRecEtape;

$mesg = '';
$error=false;

$action = GETPOST('action');
if(!empty($_REQUEST['cancel'])) $action = 'cancel';

if(!empty($action)) {
	switch($action) {
		case 'list':
			_liste($ATMdb, $etape);
			break;
		case 'add':
		case 'new':
			
			$etape->set_values($_REQUEST);
			_fiche($ATMdb, $etape,'new');
			
			break;
		case 'edit'	:
			$etape->load($ATMdb, $_REQUEST['id']);
			
			_fiche($ATMdb, $etape,'edit');
			break;
			
		case 'save':
			
			$etape->load($ATMdb, $_REQUEST['id']);
			if (GETPOST('rang', 'int') > 0)
			{
				$etape->set_values($_REQUEST);

				// Si l'action n'est pas une pénalité alors je force le fk_service à 0 pour éviter de la saisie inutile
				if ($etape->fk_action !== 'penalty') $etape->fk_service = 0;

				// Si l'action est une pénalité alors le service est obligatoire
				if ($etape->fk_action === 'penalty' && empty($etape->fk_service))
				{
					setEventMessage($langs->trans('recouvrement_error_fk_service_empty'), 'errors');
					_fiche($ATMdb, $etape,'new');
				}
				else
				{
					if(isset($_FILES['tpl_doc']) && !empty($_FILES['tpl_doc']['name']) && $_REQUEST['fk_action'] == "doc"){
					    @mkdir($conf->recouvrement->multidir_output[$conf->entity].'/');
						//dol_add_file_process(dol_buildpath("/recouvrement/file/"),0,1,'tpl_doc');
						if(copy($_FILES['tpl_doc']['tmp_name'],$conf->recouvrement->multidir_output[$conf->entity].'/'.$etape->getId()."-".$_FILES['tpl_doc']['name'])) {
							$etape->tpl_doc = $etape->getId()."-".$_FILES['tpl_doc']['name'];	
						}
						else{
							setEventMessage("Impossible de charger le modèle","errors");
						}


					}

					$etape->save($ATMdb);

					_fiche($ATMdb, $etape, 'view');
				}
			}
			else
			{
				setEventMessage($langs->trans('reouvrement_warnings_rang_value_is_incorrect'), 'warnings');
				_fiche($ATMdb, $etape,'edit');
			}
			
			break;
			
		case 'delete':
			$etape->load($ATMdb, $_REQUEST['id']);
			$etape->delete($ATMdb);
			
			?>
			<script language="javascript">
				document.location.href= "procedure.php?id=<?php echo $_REQUEST['id']; ?>";
			</script>
			<?php
			
			break;
		case 'cancel':
			?>
			<script language="javascript">
				document.location.href= "procedure.php?id=<?php echo $_REQUEST['fk_procedure']; ?>";
			</script>
			<?php
			
			break;
	}
}
elseif(isset($_REQUEST['id'])) {
	$etape->load($ATMdb, $_REQUEST['id']);
	_fiche($ATMdb, $etape, 'view');
}
else {
	?>
	<script language="javascript">
		document.location.href="procedure.php?id=<?php echo $_REQUEST['fk_procedure']; ?>";
	</script>
	<?php
}

?>
<script type="text/javascript">
	$(document).ready(function(){
		switchAction('<?php echo $etape->fk_action; ?>');
	});
	
	$("#fk_action").change(function(){
		switchAction($(this).val());
	});
	
	function switchAction(action){
		switch(action){
			case "mail":
				$('#tpl_doc').parent().parent().hide();
				$('#tr_fk_service').hide();
				$('#titre_mail, #body_mail, #bcc_mail').parent().parent().show();
				
				break;
			case "doc":
				$('#titre_mail, #body_mail, #bcc_mail').parent().parent().hide();
				$('#tr_fk_service').hide();
				$('#tpl_doc').parent().parent().show();
				
				break;
			case "externaliser":
				$('#titre_mail, #body_mail, #bcc_mail').parent().parent().hide();
				$('#tr_fk_service').hide();
				$('#tpl_doc').parent().parent().hide();
				
				break;
			case 'penalty':
				$('#titre_mail, #body_mail, #tpl_doc, #bcc_mail').parent().parent().hide();
				$('#tr_fk_service').show();
				
				break;
			default:
				$('#titre_mail, #body_mail, #tpl_doc, #bcc_mail').parent().parent().hide();
				$('#tr_fk_service').hide();
				break;
		}
	}
</script>
<?php

llxFooter();


/*
 * View
 */

function _fiche(&$ATMdb, &$etape, $mode) {
	global $db, $langs, $user, $conf;
	
	/*
	 * FICHE PROCEDURE
	 */
	
	$procedure = new TRecProcedure();
	$procedure->load($ATMdb,($etape->fk_procedure > 0 ) ? $etape->fk_procedure : $_REQUEST['fk_procedure']);
	
	$formDoli = new Form($db);
	$form=new TFormCore($_SERVER['PHP_SELF'],'formscore','POST',TRUE);
	$form->Set_typeaff($mode);
	
	echo $form->hidden('id', $etape->getId());
	echo $form->hidden('action', 'save');
	echo $form->hidden('entity', $conf->entity);
	echo $form->hidden('fk_procedure', $procedure->getId());

	$TBS=new TTemplateTBS();
	$buttons = '';
	if($mode == 'view') {
		$buttons .= '<br><a href="procedure.php?id='.$procedure->getId().'" class="butAction">'.$langs->trans('Retour').'</a>';
		$buttons .= '<a href="'.$_SERVER['SELF'].'?action=edit&id='.$etape->getId().'" class="butAction">'.$langs->trans('Modify').'</a>';
		$buttons .= '<a href="'.$_SERVER['SELF'].'?action=delete&id='.$etape->getId().'" class="butActionDelete">'.$langs->trans('Delete').'</a>';
	} else {
		$buttons .= $form->btsubmit($langs->trans('Save'), 'save');
		$buttons .= $form->btsubmit($langs->trans('Cancel'), 'cancel');
	}
	
	if($mode == 'edit')
		$title = $langs->trans("EditRecEtape");
	elseif($mode == 'new')
		$title = $langs->trans("NewRecEtape");
	else
		$title = $langs->trans("FicheRecEtape");
	
	$TOrder = array('rang'=>'ASC');
	
	if ($mode == 'view')
	{
		if (!empty($etape->fk_service))
		{
			$service = new product($db);
			$service->fetch($etape->fk_service);
			$showService = $service->getNomUrl(1);
		}
		else
		{
			$showService = '';
		}
	}
	else
	{
		ob_start();
		$formDoli->select_produits($etape->fk_service, 'fk_service', '', 200, 0, -1, 2, '', 1);
		$showService = ob_get_clean();
	}
	
	print $TBS->render('../tpl/etape.tpl.php'
		,array(
			
		)
		,array(
			'etape'=>array(
				'fk_action'=>$etape->fk_action
				,'title'=>$title
				,'id'=>$etape->getId()
				,'rang'=>$form->texte('', 'rang', ($etape->rang > 0) ? $etape->rang : $procedure->getLastRang($ATMdb), 5)
				,'title_rang'=>$langs->trans('RecEtapeTitleRang')
				,'procedure'=>$procedure->name
				,'title_procedure'=>$langs->trans('RecProcedureTitleName')
				,'delais'=>$form->texte('', 'delais', $etape->delais, 20)
				,'title_delais'=>$langs->trans('RecEtapeTitleDelais')
				,'name'=>$form->texte('', 'name', $etape->name, 50)
				,'title_name'=>$langs->trans('RecEtapeTitleName')
				,'action'=>($mode == 'view') ? $etape->TAction[$etape->fk_action] : $form->combo('', 'fk_action', $etape->TAction, $etape->fk_action)
			    ,'title_action'=>$langs->trans('RecEtapeTitleAction')
			    ,'description'=>$form->zonetexte('', 'description', $etape->description, 50)
				,'title_description'=>$langs->trans('RecEtapeTitleDescription')
				,'titre_mail'=>$form->texte('', 'titre_mail', $etape->titre_mail, 50)
				,'title_titre_mail'=>$langs->trans('RecProcedureTitleMail')
				,'body_mail'=>$form->zonetexte('', 'body_mail', $etape->body_mail, 100)
				,'title_body_mail'=>$langs->trans('RecProcedureTitleBodyMail')
				,'tpl_doc'=>($mode == 'view') ? '<a href="'.dol_buildpath('document.php',1).'?modulepart=recouvrement&entity='.$conf->entity.'&file='.$etape->tpl_doc.'">'.$etape->tpl_doc.'</a>' : $form->fichier('', 'tpl_doc', $etape->tpl_doc, 50)." ".$etape->tpl_doc
				,'title_tpl_doc'=>$langs->trans('RecProcedureTitleDoc').' (<a href="../exempleTemplate/tpl_lettre.odt">Fichier exemple</a>)'
				,'buttons'=>$buttons
				,'title_bcc_mail'=>$langs->trans('BccMail')
				,'bcc_mail'=>$form->texte('', 'bcc_mail', $etape->bcc_mail, 50)
				,'showService'=>$showService
			)
			,'view'=>array(
				'mode'=>$mode
			)
			,'langs'=>$langs
		)
	);
	
	echo $form->end_form();
	
	global $mesg, $error;
	dol_htmloutput_mesg($mesg, '', ($error ? 'error' : 'ok'));
}
