<?php

$res = 0;
if (!$res && file_exists("../main.inc.php")) {
    $res = @include("../main.inc.php");
}
if (!$res && file_exists("../../main.inc.php")) {
    $res = @include("../../main.inc.php");
}
if (!$res && file_exists("../../../main.inc.php")) {
    $res = @include("../../../main.inc.php");
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formpropal.class.php';
require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/modules/propale/modules_propale.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/propal.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
if (! empty($conf->projet->enabled))   require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
$res = 0;
if (!$res && file_exists(DOL_DOCUMENT_ROOT . "/echeancier/class/echeancier.class.php"))
    $res = include(DOL_DOCUMENT_ROOT . "/echeancier/class/echeancier.class.php");
if (!$res && file_exists("./class/echeancier.class.php"))
    $res = include("./class/echeancier.class.php");
if (!$res)
    die("Include of echeancier class fails");
$echeancier = new echeancier($db);
$echeancier->fetch(GETPOST('ide'));

$id=GETPOST('id','int');
$socid=GETPOST('socid','int');
$form = new Form($db);
$langs->load("echeancier@echeancier");
$langs->load('companies');
$langs->load('propal');
$langs->load('compta');
$langs->load('bills');
$langs->load('orders');
$langs->load('products');
if (! empty($conf->margin->enabled))
  $langs->load('margins');
$object = new Propal($db);




if (GETPOST('action') == 'supval') {
    $sql = "delete from " . MAIN_DB_PREFIX . "echeance where echeancier=" . $_POST['ide'];
    $db->query($sql);
    
    $sql = "delete from " . MAIN_DB_PREFIX . "echeancier where id=" . $_POST['ide'];
    $db->query($sql);
//header('location:'.DOL_URL_ROOT.'/compta/facture/list.php');
}

if ($id > 0 || ! empty($ref))
{
	if ($action != 'add')
	{
		$ret=$object->fetch($id, $ref);
		if ($ret == 0)
		{
			$langs->load("errors");
			setEventMessage($langs->trans('ErrorRecordNotFound'), 'errors');
			$error++;
		}
		else if ($ret < 0)
		{
			setEventMessage($object->error, 'errors');
			$error++;
		}
		else $object->fetch_thirdparty();
	}
}
else
{
	
	exit;
}
if (!$user->rights->facture->lire || !$user->rights->echeancier->propale)
    accessforbidden();
$css = array('/echeancier/css/styles.css');
llxHeader('', 'Echeancier', '', '', '', '', $js, $css);
print_fiche_titre($langs->trans("échéancier du client"));
//$head = societe_prepare_head($societe);
//dol_fiche_head($head, 'tabEcheancier', $langs->trans("ThirdParty"), 0, 'company');

if (GETPOST('action') == 'sup') {

    $echeancier->fetch($_POST['ide']);
    

        print $langs->trans('ConfirmSupEcheancierPropale') . ' ' . GETPOST('ref');
        print '<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">';
        print '<input type="hidden" name="action" value="supval">';
        print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
        print '<input type="hidden" name="ide" value="' . GETPOST('ide') . '">';

        print '<input type="submit" id="addelementbuton" class="button" value="' . $langs->trans("supprime") . '"> ';

        exit();
    
}

//
$form = new Form($db);
$formother = new FormOther($db);
$formfile = new FormFile($db);
$formpropal = new FormPropal($db);
$companystatic=new Societe($db);

$now=dol_now();

/*
 * Show object in view mode
 */

$soc = new Societe($db);
$soc->fetch($object->socid);

$head = propal_prepare_head($object);
dol_fiche_head($head, 'tabEcheancier', $langs->trans('Proposal'), 0, 'propal');

$formconfirm='';

print '<table class="border" width="100%">';

$linkback = '<a href="'.DOL_URL_ROOT.'/comm/propal/list.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';

// Ref
print '<tr><td>'.$langs->trans('Ref').'</td><td colspan="5">';
print $form->showrefnav($object, 'ref', $linkback, 1, 'ref', 'ref', '');
print '</td></tr>';

// Ref client
print '<tr><td>';
print '<table class="nobordernopadding" width="100%"><tr><td nowrap="nowrap">';
print $langs->trans('RefCustomer').'</td><td align="left">';
print '</td>';
if ($action != 'refclient' && ! empty($object->brouillon)) print '<td align="right"><a href="'.$_SERVER['PHP_SELF'].'?action=refclient&amp;id='.$object->id.'">'.img_edit($langs->trans('Modify')).'</a></td>';
print '</tr></table>';
print '</td><td colspan="5">';

	print $object->ref_client;

print '</td>';
print '</tr>';

// Company
print '<tr><td>'.$langs->trans('Company').'</td><td colspan="5">'.$soc->getNomUrl(1).'</td>';
print '</tr>';

// Ligne info remises tiers
print '<tr><td>'.$langs->trans('Discounts').'</td><td colspan="5">';
if ($soc->remise_client) print $langs->trans("CompanyHasRelativeDiscount",$soc->remise_client);
else print $langs->trans("CompanyHasNoRelativeDiscount");
print '. ';
$absolute_discount=$soc->getAvailableDiscounts('','fk_facture_source IS NULL');
$absolute_creditnote=$soc->getAvailableDiscounts('','fk_facture_source IS NOT NULL');
$absolute_discount=price2num($absolute_discount,'MT');
$absolute_creditnote=price2num($absolute_creditnote,'MT');
if ($absolute_discount)
{
	if ($object->statut > 0)
	{
		print $langs->trans("CompanyHasAbsoluteDiscount",price($absolute_discount),$langs->transnoentities("Currency".$conf->currency));
	}
	else
	{
		// Remise dispo de type non avoir
		$filter='fk_facture_source IS NULL';
		print '<br>';
		$form->form_remise_dispo($_SERVER["PHP_SELF"].'?id='.$object->id,0,'remise_id',$soc->id,$absolute_discount,$filter);
	}
}
if ($absolute_creditnote)
{
	print $langs->trans("CompanyHasCreditNote",price($absolute_creditnote),$langs->transnoentities("Currency".$conf->currency)).'. ';
}
if (! $absolute_discount && ! $absolute_creditnote) print $langs->trans("CompanyHasNoAbsoluteDiscount").'.';
print '</td></tr>';

// Date of proposal
print '<tr>';
print '<td>';
print '<table class="nobordernopadding" width="100%"><tr><td>';
print $langs->trans('Date');
print '</td>';
if ($action != 'editdate' && ! empty($object->brouillon)) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editdate&amp;id='.$object->id.'">'.img_edit($langs->trans('SetDate'),1).'</a></td>';
print '</tr></table>';
print '</td><td colspan="3">';
if (! empty($object->brouillon) && $action == 'editdate')
{
	print '<form name="editdate" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
	print '<input type="hidden" name="action" value="setdate">';
	$form->select_date($object->date,'re','','',0,"editdate");
	print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
	print '</form>';
}
else
{
	if ($object->date)
	{
		print dol_print_date($object->date,'daytext');
	}
	else
	{
		print '&nbsp;';
	}
}
print '</td>';

// Date end proposal
print '<tr>';
print '<td>';
print '<table class="nobordernopadding" width="100%"><tr><td>';
print $langs->trans('DateEndPropal');
print '</td>';
if ($action != 'editecheance' && ! empty($object->brouillon)) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editecheance&amp;id='.$object->id.'">'.img_edit($langs->trans('SetConditions'),1).'</a></td>';
print '</tr></table>';
print '</td><td colspan="3">';
if (! empty($object->brouillon) && $action == 'editecheance')
{
	print '<form name="editecheance" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
	print '<input type="hidden" name="action" value="setecheance">';
	$form->select_date($object->fin_validite,'ech','','','',"editecheance");
	print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
	print '</form>';
}
else
{
	if (! empty($object->fin_validite))
	{
		print dol_print_date($object->fin_validite,'daytext');
		if ($object->statut == 1 && $object->fin_validite < ($now - $conf->propal->cloture->warning_delay)) print img_warning($langs->trans("Late"));
	}
	else
	{
		print '&nbsp;';
	}
}
print '</td>';
print '</tr>';

// Payment term
print '<tr><td>';
print '<table class="nobordernopadding" width="100%"><tr><td>';
print $langs->trans('PaymentConditionsShort');
print '</td>';
if ($action != 'editconditions' && ! empty($object->brouillon)) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editconditions&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetConditions'),1).'</a></td>';
print '</tr></table>';
print '</td><td colspan="3">';
if ($action == 'editconditions')
{
    $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->cond_reglement_id,'cond_reglement_id');
}
else
{
    $form->form_conditions_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->cond_reglement_id,'none');
}
print '</td>';
print '</tr>';

// Delivery date
$langs->load('deliveries');
print '<tr><td>';
print '<table class="nobordernopadding" width="100%"><tr><td>';
print $langs->trans('DeliveryDate');
print '</td>';
if ($action != 'editdate_livraison' && ! empty($object->brouillon)) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editdate_livraison&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetDeliveryDate'),1).'</a></td>';
print '</tr></table>';
print '</td><td colspan="3">';
if ($action == 'editdate_livraison')
{
	print '<form name="editdate_livraison" action="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'" method="post">';
	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
	print '<input type="hidden" name="action" value="setdate_livraison">';
	$form->select_date($object->date_livraison,'liv_','','','',"editdate_livraison");
	print '<input type="submit" class="button" value="'.$langs->trans('Modify').'">';
	print '</form>';
}
else
{
	print dol_print_date($object->date_livraison,'daytext');
}
print '</td>';
print '</tr>';

// Delivery delay
print '<tr><td>';
print '<table class="nobordernopadding" width="100%"><tr><td>';
print $langs->trans('AvailabilityPeriod');
if (! empty($conf->commande->enabled)) print ' ('.$langs->trans('AfterOrder').')';
print '</td>';
if ($action != 'editavailability' && ! empty($object->brouillon)) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editavailability&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetAvailability'),1).'</a></td>';
print '</tr></table>';
print '</td><td colspan="3">';
if ($action == 'editavailability')
{
	$form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id,$object->availability_id,'availability_id',1);
}
else
{
	$form->form_availability($_SERVER['PHP_SELF'].'?id='.$object->id,$object->availability_id,'none',1);
}

print '</td>';
print '</tr>';

// Payment mode
print '<tr>';
print '<td width="25%">';
print '<table class="nobordernopadding" width="100%"><tr><td>';
print $langs->trans('PaymentMode');
print '</td>';
if ($action != 'editmode' && ! empty($object->brouillon)) print '<td align="right"><a href="'.$_SERVER["PHP_SELF"].'?action=editmode&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetMode'),1).'</a></td>';
print '</tr></table>';
print '</td><td colspan="3">';
if ($action == 'editmode')
{
	$form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->mode_reglement_id,'mode_reglement_id');
}
else
{
	$form->form_modes_reglement($_SERVER['PHP_SELF'].'?id='.$object->id,$object->mode_reglement_id,'none');
}
print '</td></tr>';

// Project
if (! empty($conf->projet->enabled))
{
	$langs->load("projects");
	print '<tr><td>';
	print '<table class="nobordernopadding" width="100%"><tr><td>';
	print $langs->trans('Project').'</td>';
	if ($user->rights->propal->creer)
	{
		if ($action != 'classify') print '<td align="right"><a href="'.$_SERVER['PHP_SELF'].'?action=classify&amp;id='.$object->id.'">'.img_edit($langs->transnoentitiesnoconv('SetProject')).'</a></td>';
		print '</tr></table>';
		print '</td><td colspan="3">';
		if ($action == 'classify')
		{
			$form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'projectid');
		}
		else
		{
			$form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, 'none');
		}
		print '</td></tr>';
	}
	else
	{
		print '</td></tr></table>';
		if (! empty($object->fk_project))
		{
			print '<td colspan="3">';
			$proj = new Project($db);
			$proj->fetch($object->fk_project);
			print '<a href="../projet/fiche.php?id='.$object->fk_project.'" title="'.$langs->trans('ShowProject').'">';
			print $proj->ref;
			print '</a>';
			print '</td>';
		}
		else {
			print '<td colspan="3">&nbsp;</td>';
		}
	}
	print '</tr>';
}

// Other attributes
$parameters=array('colspan' => ' colspan="3"');
$reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action);    // Note that $action and $object may have been modified by hook
if (empty($reshook) && ! empty($extrafields->attribute_label))
{
    foreach($extrafields->attribute_label as $key=>$label)
    {
        $value=(isset($_POST["options_".$key])?$_POST["options_".$key]:$object->array_options["options_".$key]);
   		print '<tr><td';
   		if (! empty($extrafields->attribute_required[$key])) print ' class="fieldrequired"';
   		print '>'.$label.'</td><td colspan="3">';
        print $extrafields->showInputField($key,$value);
        print '</td></tr>'."\n";
    }
}

// Amount HT
print '<tr><td height="10">'.$langs->trans('AmountHT').'</td>';
print '<td align="right" nowrap><b>'.price($object->total_ht).'</b></td>';
print '<td>'.$langs->trans("Currency".$conf->currency).'</td>';

// Margin Infos
if (! empty($conf->margin->enabled)) {
  print '<td valign="top" width="50%" rowspan="4">';
  print $object->displayMarginInfos;
  print '</td>';
}
print '</tr>';

// Amount VAT
print '<tr><td height="10">'.$langs->trans('AmountVAT').'</td>';
print '<td align="right" nowrap>'.price($object->total_tva).'</td>';
print '<td>'.$langs->trans("Currency".$conf->currency).'</td></tr>';

// Amount Local Taxes
if ($mysoc->localtax1_assuj=="1") //Localtax1
{
	print '<tr><td height="10">'.$langs->transcountry("AmountLT1",$mysoc->country_code).'</td>';
	print '<td align="right" nowrap>'.price($object->total_localtax1).'</td>';
	print '<td>'.$langs->trans("Currency".$conf->currency).'</td></tr>';
}
if ($mysoc->localtax2_assuj=="1") //Localtax2
{
	print '<tr><td height="10">'.$langs->transcountry("AmountLT2",$mysoc->country_code).'</td>';
	print '<td align="right" nowrap>'.price($object->total_localtax2).'</td>';
	print '<td>'.$langs->trans("Currency".$conf->currency).'</td></tr>';
}


// Amount TTC
print '<tr><td height="10">'.$langs->trans('AmountTTC').'</td>';
print '<td align="right" nowrap>'.price($object->total_ttc).'</td>';
print '<td>'.$langs->trans("Currency".$conf->currency).'</td></tr>';

// Statut
print '<tr><td height="10">'.$langs->trans('Status').'</td><td align="left" colspan="2">'.$object->getLibStatut(4).'</td></tr>';

print '</table><br>';

if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB))
{
	$blocname = 'contacts';
	$title = $langs->trans('ContactsAddresses');
	include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
}

if (! empty($conf->global->MAIN_DISABLE_NOTES_TAB))
{
	$blocname = 'notes';
	$title = $langs->trans('Notes');
	include DOL_DOCUMENT_ROOT.'/core/tpl/bloc_showhide.tpl.php';
}




if ($echeancier->GetEcheancesFromFacture($object->id,1)) {
    print '<table id="ticket" class="noborder" width="100%" >';
    print '<thead><tr class="liste_titre"><th>' . $langs->trans('montant') . '</th><th>' . $langs->trans('écheance') . '</th><th>' . $langs->trans('LastEcheance') . '</th><th></th></tr></thead>';
    $echeancier->fetch($echeancier->id);
    print '<tr>';
    print '<form action="modif_echeancier_propal.php"" method="post">';
    print '<input type="hidden" name="action" value="modifie">';
    print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
    print '<input type="hidden" name="ide" value="' . $echeancier->id . '">';
    print '<input type="hidden" name="montant" value="' . $echeancier->montant . '">';
    print '<input type="hidden" name="id_client" value="' . GETPOST('id_client') . '">';
    print '<input type="hidden" name="redirect" value="' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'] . '">';
    print '<td align="center">' . price($echeancier->montant) . '</td>';
    print '<td align="center">' .  $echeancier->nombre_echeance . '</td>';
    print '<td align="center">' . dol_print_date($echeancier->echeances[$echeancier->nombre_echeance - 1]['date_reglement']) . '</td>';
    print '<td width="200px" align="right"><input type="submit" id="addelementbuton" class="button" value="' . $langs->trans("modifier") . '"></form>';
    
    
    print '<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">';
    print '<input type="hidden" name="action" value="sup">';
    print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
    print '<input type="hidden" name="ide" value="' . $echeancier->id . '">';
    print '<input type="hidden" name="ref" value="' . $object->ref . '">';
    print '<input type="submit" id="addelementbuton" class="button" value="' . $langs->trans("supprime") . '"></td>';
    print '</tr>';



    print '</table>';




    print '<table  class="noborder semi"  >';
    print '<thead><tr class="liste_titre"><th>' . $langs->trans('Date de reglement') . '</th><th>' . $langs->trans('Montant') . '</th></tr></thead>';


    $i = 0;
    foreach ($echeancier->echeances as $echeance_row) {
        $var = !$var;


        print '<tr ' . $bc[$var] . ' id="row' . $i . '">';
        print '<td align="center">' . dol_print_date($echeance_row['date_reglement']) . '</td>';
        print '<td align="center">' . $echeance_row['montant'] . '</td>';
        
        print '</tr>';
        $i++;
    }


    print '</table>';
    print '</div>';




    print '</div>';
}else{
    
    if ( $object->mode_reglement_code == 'ECH'){
    
     print '<div class="tabsAction" ><form action="simul_propal.php" method="post">';
        print '<input type="hidden" name="action" value="create">';
        print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
        print '<input type="hidden" name="id" value="' . $object->id . '">';
        print '<input type="hidden" name="montant" value="' . $object->total_ttc . '">';
        print '<input type="hidden" name="ref" value="' . $object->ref . '">';
        print '<input type="hidden" name="id_client" value="' . $object->socid . '">';
        print '<input type="submit" id="addelementbuton" class="button" value="' . $langs->trans("Créer") . '">';
        print '</form></div>';
}
}







dol_htmloutput_errors($errmess);
// End of page
llxFooter();
$db->close();
