<?php
require('config.php');
require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';

$langs->load('companies');
$langs->load('bills');
$langs->load('banks');

$ATMdb = new TPDOdb;

$action		= GETPOST('action');
$confirm	= GETPOST('confirm');

$facid		= GETPOST('facid','int');
$socid		= GETPOST('socid');
$accountid	= GETPOST('accountid');
$paymentnum	= GETPOST('num_paiement');

$sortfield	= GETPOST('sortfield','alpha');
$sortorder	= GETPOST('sortorder','alpha');
$page		= GETPOST('page','int');

$amounts=array();
$amountsresttopay=array();

// Initialize technical object to manage hooks of paiements. Note that conf->hooks_modules contains array array
$hookmanager = new HookManager($db);
$hookmanager->initHooks(array('paiementcard'));

$parameters=array('socid' => $socid);
$reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks 

/*
 * Action add_paiement et confirm_paiement
 */
if ($action == 'add_paiement' || ($action == 'confirm_paiement' && $confirm=='yes')) {
    $error = 0;

    $datepaye = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
    $paiement_id = 0;
    $totalpaiement = 0;
    $atleastonepaymentnotnull = 0;

    // Verifie si des paiements sont superieurs au montant facture
    foreach ($_POST as $key => $value) {
        if (substr($key,0,7) == 'amount_') {
            $cursorfacid = substr($key, 7);
			
			$amount = price2num(trim($_POST[$key]));
			
			if (abs($amount) > 0) {
				$amounts[$cursorfacid] = price2num(trim($_POST[$key]));
			}
			
            $totalpaiement += $amounts[$cursorfacid];
			
            if (!empty($amounts[$cursorfacid])) $atleastonepaymentnotnull++;
			
            $tmpfacture=new Facture($db);
            $tmpfacture->fetch($cursorfacid);
			
            $amountsresttopay[$cursorfacid]=price2num($tmpfacture->total_ttc-$tmpfacture->getSommePaiement()-$tmpfacture->getSumCreditNotesUsed()-$tmpfacture->getSumDepositsUsed());
			
            if ($amounts[$cursorfacid] && (abs($amounts[$cursorfacid]) > abs($amountsresttopay[$cursorfacid]))) {
                $addwarning=1;
                $formquestion['text'] = img_warning($langs->trans("PaymentHigherThanReminderToPay")).' '.$langs->trans("HelpPaymentHigherThanReminderToPay");
            }

            $formquestion[$i++] = array('type' => 'hidden','name' => $key,  'value' => $_POST[$key]);
        }
    }

    // Check parameters
    if (!GETPOST('paiementcode')) {
        $fiche_erreur_message = '<div class="error">'.$langs->trans('ErrorFieldRequired',$langs->transnoentities('PaymentMode')).'</div>';
        $error++;
    }

    if (! empty($conf->banque->enabled)) {
        // If bank module is on, account is required to enter a payment
        if (GETPOST('accountid') <= 0) {
            $fiche_erreur_message = '<div class="error">'.$langs->trans('ErrorFieldRequired',$langs->transnoentities('AccountToCredit')).'</div>';
            $error++;
        }
    }

    if (empty($totalpaiement) && empty($atleastonepaymentnotnull)) {
        $fiche_erreur_message = '<div class="error">'.$langs->transnoentities('ErrorFieldRequired',$langs->trans('PaymentAmount')).'</div>';
        $error++;
    }

    if (empty($datepaye)) {
        $fiche_erreur_message = '<div class="error">'.$langs->trans('ErrorFieldRequired',$langs->transnoentities('Date')).'</div>';
        $error++;
    }
}

/*
 * Action add_paiement
 */
if ($action == 'add_paiement')
{
    if ($error)
    {
        $action = 'create';
    }
    // Le reste propre à cette action s'affiche en bas de page.
}

/*
 * Action confirm_paiement
 */
if ($action == 'confirm_paiement' && $confirm == 'yes')
{
    $error = 0;

    $datepaye = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);

    $db->begin();

    // Clean parameters amount if payment is for a credit note
    if (GETPOST('type') == 2) {
	    foreach ($amounts as $key => $value) { // How payment is dispatch
	    	$newvalue = price2num($value,'MT');
	    	$amounts[$key] = -$newvalue;
	    }
    }

    if (!empty($conf->banque->enabled)) {
    	// Si module bank actif, un compte est obligatoire lors de la saisie d'un paiement
    	if (GETPOST('accountid') <= 0) {
    		$fiche_erreur_message = '<div class="error">'.$langs->trans('ErrorFieldRequired',$langs->transnoentities('AccountToCredit')).'</div>';
    		$error++;
    	}
    }
	
	foreach ($amounts as $facid => $amount) {
		// Creation of payment line
	    $paiement = new Paiement($db);
	    $paiement->datepaye     = $datepaye;
	    $paiement->amounts      = array($facid => $amount);   // Array with all payments dispatching
	    $paiement->paiementid   = dol_getIdFromCode($db,$_POST['paiementcode'],'c_paiement');
	    $paiement->num_paiement = $_POST['num_paiement'];
	    $paiement->note         = $_POST['comment'];
	
	    if (!$error) {
	    	$paiement_id = $paiement->create($user, (GETPOST('closepaidinvoices') == 'on' ? 1 : 0));
			
	    	if ($paiement_id < 0) {
	            $errmsg=$paiement->error;
	            $error++;
	        }
	    }
	
	    if (!$error) {
	    	$label = '(CustomerInvoicePayment)';
			
	    	if (GETPOST('type') == 2) $label='(CustomerInvoicePaymentBack)';
	
	        $result = $paiement->addPaymentToBank($user, 'payment', $label, GETPOST('accountid'), GETPOST('chqemetteur'), GETPOST('chqbank'));
			
	        if ($result < 0) {
	            $errmsg = $paiement->error;
	            $error++;
	        }
	    }
	}

    if (!$error) {
        $db->commit();
		
      	$loc = DOL_URL_ROOT . '/compta/paiement/liste.php?leftmenu=customers_bills_payments';

        header('Location: ' . $loc);
        exit;
    } else {
        $db->rollback();
    }
}

/*
 * View
 */

llxHeader();

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

$form=new Form($db);

// Initialize data for confirmation (this is used because data can be change during confirmation)
if ($action == 'add_paiement')
{
	$i=0;

	$formquestion[$i++]=array('type' => 'hidden','name' => 'facid', 'value' => $facture->id);
	$formquestion[$i++]=array('type' => 'hidden','name' => 'socid', 'value' => $facture->socid);
	$formquestion[$i++]=array('type' => 'hidden','name' => 'type',  'value' => $facture->type);
}

print '<form id="payment_form" name="add_paiement" action="'.$_SERVER["PHP_SELF"].'" method="POST">';
print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
print '<input type="hidden" name="action" value="add_paiement">';
print '<input type="hidden" name="socid" value="'.$societe->id.'">';
print '<input type="hidden" name="type" id="invoice_type" value="'.$facture->type.'">';
print '<input type="hidden" name="thirdpartylabel" id="thirdpartylabel" value="'.dol_escape_htmltag($societe->name).'">';

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

// Third party
print '<tr><td><span class="fieldrequired">'.$langs->trans('Company').'</span></td><td colspan="2">'.$societe->getNomUrl(4)."</td></tr>\n";

// Date payment
print '<tr><td><span class="fieldrequired">'.$langs->trans('Date').'</span></td><td>';
$datepayment = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
$datepayment= ($datepayment == '' ? (empty($conf->global->MAIN_AUTOFILL_DATE)?-1:'') : $datepayment);
$form->select_date($datepayment,'','','',0,"add_paiement",1,1);
print '</td>';
print '<td>'.$langs->trans('Comments').'</td></tr>';

$rowspan=5;
if ($conf->use_javascript_ajax && !empty($conf->global->MAIN_JS_ON_PAYMENT)) $rowspan++;

// Payment mode
print '<tr><td><span class="fieldrequired">'.$langs->trans('PaymentMode').'</span></td><td>';
$form->select_types_paiements((GETPOST('paiementcode')?GETPOST('paiementcode'):$facture->mode_reglement_code),'paiementcode','',2);
print "</td>\n";
print '<td rowspan="'.$rowspan.'" valign="top">';
print '<textarea name="comment" wrap="soft" cols="60" rows="'.ROWS_4.'">'.(empty($_POST['comment'])?'':$_POST['comment']).'</textarea></td>';
print '</tr>';

// Bank account
print '<tr>';
if (! empty($conf->banque->enabled))
{
    if ($facture->type != 2) print '<td><span class="fieldrequired">'.$langs->trans('AccountToCredit').'</span></td>';
    if ($facture->type == 2) print '<td><span class="fieldrequired">'.$langs->trans('AccountToDebit').'</span></td>';
    print '<td>';
    $form->select_comptes($accountid,'accountid',0,'',2);
    print '</td>';
}
else
{
    print '<td colspan="2">&nbsp;</td>';
}
print "</tr>\n";

// Payment amount
if ($conf->use_javascript_ajax && !empty($conf->global->MAIN_JS_ON_PAYMENT))
{
    print '<tr><td><span class="fieldrequired">'.$langs->trans('AmountPayment').'</span></td>';
    print '<td>';
    if ($action == 'add_paiement')
    {
        print '<input id="amountpayment" name="amountpaymenthidden" size="8" type="text" value="'.(empty($_POST['amountpayment'])?'':$_POST['amountpayment']).'" disabled="disabled">';
        print '<input name="amountpayment" type="hidden" value="'.(empty($_POST['amountpayment'])?'':$_POST['amountpayment']).'">';
    }
    else
    {
        print '<input id="amountpayment" name="amountpayment" size="8" type="text" value="'.(empty($_POST['amountpayment'])?'':$_POST['amountpayment']).'">';
    }
    print '</td>';
    print '</tr>';
}

// Cheque number
print '<tr><td>'.$langs->trans('Numero');
print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
print '</td>';
print '<td><input name="num_paiement" type="text" value="'.$paymentnum.'"></td></tr>';

// Check transmitter
print '<tr><td class="'.(GETPOST('paiementcode')=='CHQ'?'fieldrequired ':'').'fieldrequireddyn">'.$langs->trans('CheckTransmitter');
print ' <em>('.$langs->trans("ChequeMaker").')</em>';
print '</td>';
print '<td><input id="fieldchqemetteur" name="chqemetteur" size="30" type="text" value="'.GETPOST('chqemetteur').'"></td></tr>';

// Bank name
print '<tr><td>'.$langs->trans('Bank');
print ' <em>('.$langs->trans("ChequeBank").')</em>';
print '</td>';
print '<td><input name="chqbank" size="30" type="text" value="'.GETPOST('chqbank').'"></td></tr>';

print '</table>';

if ((float) DOL_VERSION < 10.0) $field_facture_ref = 'facnumber';
else $field_facture_ref = 'ref';
/*
 * List of unpaid invoices
 */
$sql = "
	SELECT f.rowid as idfac ,f.".$field_facture_ref." AS facnumber, f.fk_soc, s.nom, f.date_lim_reglement as DateLim, f.total, f.tva,
		total_ttc, (f.total_ttc - IFNULL((
				SELECT SUM(pf.amount)
				FROM ".MAIN_DB_PREFIX."paiement_facture as pf
				WHERE pf.fk_facture = f.rowid),0)) as reste, f.rowid RecProc
				
	FROM ".MAIN_DB_PREFIX."facture as f LEFT OUTER JOIN ".MAIN_DB_PREFIX."rec_dossier_facture as df ON (df.fk_facture=f.rowid)
	LEFT JOIN ".MAIN_DB_PREFIX."societe as s ON (f.fk_soc = s.rowid)
	LEFT JOIN ".MAIN_DB_PREFIX."societe as sm ON (sm.rowid = s.parent)
	WHERE f.entity IN (".getEntity('facture',1).") 
		AND f.paye=0
		AND f.fk_statut = 1
		AND f.total>0
		AND type = 0
		AND df.rowid IS NULL 
		AND (s.parent = " . $socid . " OR s.rowid = " . $socid . ") 
	";
	
if(GETPOST('date_deb') || GETPOST('date_fin')) {
	$date_deb = (GETPOST('date_deb')>0) ? date('Y-m-d',Tools::get_time(GETPOST('date_deb'))) : date('Y-m-d',Tools::get_time('01/01/2000'));
	$date_fin = (GETPOST('date_fin')>0) ? date('Y-m-d',Tools::get_time(GETPOST('date_fin'))) : date('Y-m-d',Tools::get_time(date('d/m/Y')));

	$sql.= " AND f.date_lim_reglement BETWEEN '".$date_deb."' AND '".$date_fin."'";
}

$sql.= " ORDER BY f.".$field_facture_ref." ASC ";

$resql = $db->query($sql);
if ($resql)
{
    $num = $db->num_rows($resql);
    if ($num > 0)
    {
    	$sign=1;
    	if ($facture->type == 2) $sign=-1;

		$arraytitle=$langs->trans('Invoice');
		if ($facture->type == 2) $arraytitle=$langs->trans("CreditNotes");
		$alreadypayedlabel=$langs->trans('Received');
		if ($facture->type == 2) $alreadypayedlabel=$langs->trans("PaidBack");
		$remaindertopay=$langs->trans('RemainderToTake');
		if ($facture->type == 2) $remaindertopay=$langs->trans("RemainderToPayBack");
		
		
		$parameters=array();
		$reshook=$hookmanager->executeHooks('formAddObjectLine',$parameters,$facture,$action);    // Note that $action and $object may have been modified by hook
		
        $i = 0;
        //print '<tr><td colspan="3">';
        print '<br>';
        print '<table id="list_bills" class="noborder" width="100%">';
        print '<tr class="liste_titre">';
        print '<td>' . $arraytitle . '</td>';
        print '<td>Lot concerné</td>';
        print '<td align="center">'.$langs->trans('Date').'</td>';
        print '<td align="right">'.$langs->trans('AmountTTC').'</td>';
        print '<td align="right">'.$alreadypayedlabel.'</td>';
        print '<td align="right">'.$remaindertopay.'</td>';
        print '<td align="right">'.$langs->trans('PaymentAmount').'</td>';
        print '<td align="right">&nbsp;</td>';
        print "</tr>\n";

        $var=True;
        $total=0;
        $totalrecu=0;
        $totalrecucreditnote=0;
        $totalrecudeposits=0;

        while ($i < $num)
        {
            $objp = $db->fetch_object($resql);
            $var=!$var;
			
            $invoice=new Facture($db);
            $invoice->fetch($objp->idfac);
            $paiement = $invoice->getSommePaiement();
            $creditnotes=$invoice->getSumCreditNotesUsed();
            $deposits=$invoice->getSumDepositsUsed();
            $alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
            $remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');

            print '<tr '.$bc[$var].'>';

            print '<td>';
			print '<input class="auto_set_amount" type="checkbox" data-facid="' . $invoice->id . '" value="0" />';
            print $invoice->getNomUrl(1,'');
            print "</td>\n";
			
			$lot = new Societe($db);
			$lot->fetch($invoice->socid);
			
			print '<td>' . $lot->getNomUrl(1, '') . '</td>';
            // Date
            print '<td align="center">'.dol_print_date($db->jdate(date('Y-m-d', $invoice->date)),'day')."</td>\n";

            // Price
            print '<td align="right">'.price($sign * $objp->total_ttc).'</td>';

            // Received or paid back
            print '<td align="right">'.price($sign * $paiement);
            if ($creditnotes) print '+'.price($creditnotes);
            if ($deposits) print '+'.price($deposits);
            print '</td>';

            // Remain to take or to pay back
            print '<td align="right">'.price($sign * $remaintopay).'</td>';
            //$test= price(price2num($objp->total_ttc - $paiement - $creditnotes - $deposits));

            // Amount
            print '<td align="right">';

            // Add remind amount
            $namef = 'amount_'.$objp->idfac;
            $nameRemain = 'remain_'.$objp->idfac;
			
            if ($conf->use_javascript_ajax && !empty($conf->global->MAIN_JS_ON_PAYMENT))
            {
                print img_picto($langs->trans('AddRemind'),'rightarrow.png','id="'.$objp->facid.'"');
            }
			
            print '<input type="hidden" name="'.$nameRemain.'" value="'.$remaintopay.'">';
            print '<input class="payment_amount" type="text" size="8" name="'.$namef.'" value="'.$_POST[$namef].'" data-facid="' . $invoice->id . '" />';
            
            print "</td>";

            // Warning
            print '<td align="center" width="16">';
            //print "xx".$amounts[$invoice->id]."-".$amountsresttopay[$invoice->id]."<br>";
            if ($amounts[$invoice->id] && (abs($amounts[$invoice->id]) > abs($amountsresttopay[$invoice->id])))
            {
                print ' '.img_warning($langs->trans("PaymentHigherThanReminderToPay"));
            }
            print '</td>';

			$parameters=array();
			$reshook=$hookmanager->executeHooks('printObjectLine',$parameters,$objp,$action); // Note that $action and $object may have been modified by hook

            print "</tr>\n";

            $total+=$objp->total;
            $total_ttc+=$objp->total_ttc;
            $totalrecu+=$paiement;
            $totalrecucreditnote+=$creditnotes;
            $totalrecudeposits+=$deposits;
            $i++;
        }
        if ($i > 1)
        {
            // Print total
            print '<tr class="liste_total">';
            print '<td colspan="3" align="left">'.$langs->trans('TotalTTC').'</td>';
            print '<td align="right"><b>'.price($sign * $total_ttc).'</b></td>';
            print '<td align="right"><b>'.price($sign * $totalrecu);
            if ($totalrecucreditnote) print '+'.price($totalrecucreditnote);
            if ($totalrecudeposits) print '+'.price($totalrecudeposits);
            print '</b></td>';
            print '<td align="right"><b>'.price($sign * price2num($total_ttc - $totalrecu - $totalrecucreditnote - $totalrecudeposits,'MT')).'</b></td>';
            print '<td align="right" id="result" style="font-weight: bold;"></td>';
            print '<td align="center">&nbsp;</td>';
            print "</tr>\n";
        }
        print "</table>";
        //print "</td></tr>\n";
    }
    $db->free($resql);
}
else
{
    dol_print_error($db);
}


// Bouton Enregistrer
if ($action != 'add_paiement') {
	$checkboxlabel=$langs->trans("ClosePaidInvoicesAutomatically");
	if ($facture->type == 2) $checkboxlabel=$langs->trans("ClosePaidCreditNotesAutomatically");
	$buttontitle=$langs->trans('ToMakePayment');
	if ($facture->type == 2) $buttontitle=$langs->trans('ToMakePaymentBack');
	
	print '<center><br>';
	print '<input type="checkbox" checked="checked" name="closepaidinvoices"> '.$checkboxlabel;
	print '<br><input type="submit" class="button" value="'.dol_escape_htmltag($buttontitle).'"><br><br>';
	print '</center>';
}

// Message d'erreur
if ($fiche_erreur_message)
{
    print $fiche_erreur_message;
}

// Form to confirm payment
if ($action == 'add_paiement') {
    $preselectedchoice=$addwarning?'no':'yes';

    print '<br>';
    $text=$langs->trans('ConfirmCustomerPayment',$totalpaiement,$langs->trans("Currency".$conf->currency));
    if (GETPOST('closepaidinvoices'))
    {
        $text.='<br>'.$langs->trans("AllCompletelyPayedInvoiceWillBeClosed");
        print '<input type="hidden" name="closepaidinvoices" value="'.GETPOST('closepaidinvoices').'">';
    }
	
    $form->form_confirm($_SERVER['PHP_SELF'].'?socid=' . $societe->id, $langs->trans('ReceivedCustomersPayments'),$text,'confirm_paiement',$formquestion,$preselectedchoice);
}

print "</form>\n";

$db->close();

llxFooter();
?>

<script>
	$('#list_bills tr td .auto_set_amount').click(function() {
		var facid = $(this).data('facid');
		console.log(status);
		if ($(this).is(':checked')) {
			var remain = $('input[name="remain_' + facid + '"]').val();
			$('.payment_amount[data-facid=' + facid + ']').val(remain);
		} else {
			$('.payment_amount[data-facid=' + facid + ']').val('');
		}
	});
</script>
