<?php

/* <one line to give the program's name and a brief idea of what it does.>
 * Copyright (C) 2012-2013 jacquel jerome <icfr.eirl@free.fr>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */


/**
 * 	\file		mypage.php
 * 	\ingroup	mymodule
 * 	\brief		This file is an example php page
 * 				Put some comments here
 */
//if (! defined('NOREQUIREUSER'))	define('NOREQUIREUSER','1');
//if (! defined('NOREQUIREDB'))		define('NOREQUIREDB','1');
//if (! defined('NOREQUIRESOC'))	define('NOREQUIRESOC','1');
//if (! defined('NOREQUIRETRAN'))	define('NOREQUIRETRAN','1');
//if (! defined('NOCSRFCHECK'))		define('NOCSRFCHECK','1');
//if (! defined('NOTOKENRENEWAL'))	define('NOTOKENRENEWAL','1');
// If there is no menu to show
//if (! defined('NOREQUIREMENU'))	define('NOREQUIREMENU','1');
// If we don't need to load the html.form.class.php
//if (! defined('NOREQUIREHTML'))	define('NOREQUIREHTML','1');
//if (! defined('NOREQUIREAJAX'))	define('NOREQUIREAJAX','1');
// If this page is public (can be called outside logged session)
//if (! defined("NOLOGIN"))			define("NOLOGIN",'1');
// Choose the following lines to use the correct relative path
// (../, ../../, etc)
$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");
}
// The following should only be used in development environments
if (!$res && file_exists("../../../dolibarr/htdocs/main.inc.php")) {
    $res = @include("../../../dolibarr/htdocs/main.inc.php");
}
if (!$res && file_exists("../../../../dolibarr/htdocs/main.inc.php")) {
    $res = @include("../../../../dolibarr/htdocs/main.inc.php");
}
if (!$res && file_exists("../../../../../dolibarr/htdocs/main.inc.php")) {
    $res = @include("../../../../../dolibarr/htdocs/main.inc.php");
}
if (!$res) {
    die("Main include failed");
}
$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");
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';

// Change this following line to use the correct relative path from htdocs
// (do not remove DOL_DOCUMENT_ROOT)
//require_once DOL_DOCUMENT_ROOT . "custom/mymodule/class/myclass.class.php";
// Load translation files required by the page
$langs->load("echeancier@echeancier");

// Get parameters
$id = GETPOST('id', 'int');
$action = GETPOST('action', 'alpha');
$myparam = GETPOST('myparam', 'alpha');

// Access control
if ($user->societe_id > 0 || !$user->rights->echeancier->encaissement) {
    // External user
    //accessforbidden();
}

$echeance = new echeance($db);

/*
 * ACTIONS
 *
 * Put here all code to do according to value of "action" parameter
 */

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

    $lastday = strftime("%Y%m%d", mktime(0, 0, 0, GETPOST('datefmonth'), GETPOST('datefday'), GETPOST('datefyear')));
    $firstday = strftime("%Y%m%d", mktime(0, 0, 0, GETPOST('datedmonth'), GETPOST('datedday'), GETPOST('datedyear')));
    $firstday = strtotime($firstday);
    $lastday = strtotime($lastday);
} else {

    $mois = date('m');
    $annee = date('y');
    $lastday = strftime("%Y%m%d", mktime(0, 0, 0, $mois + 1, 0, $annee));
    $firstday = strftime("%Y%m%d", mktime(0, 0, 0, $mois, 1, $annee));
    $firstday = strtotime($firstday);
    $lastday = strtotime($lastday);
}



if (GETPOST('action') == 'valide') {
    $count = GETPOST('count');
    $paiementc = array();
    $j = 0;


    for ($i = 0; $i < $count; $i++) {

        $post = 'check' . $i;

        if ($_POST[$post] != '') {
            $paiementc[$j]['id'] = GETPOST($post);
            $paiementc[$j]['paiementcode'] = GETPOST('paiementcode' . $i);
            $echeance_row = $echeance->GetEcheanceForPaiement($paiementc[$j]['id']);

            $error = 0;





            $datepaye = $echeance_row['date_reglement'];

            $db->begin();

            // Creation of payment line
            $paiement = new Paiement($db);
            $paiement->datepaye = strtotime($datepaye);
            $paiement->amounts = array($echeance_row['rowid'] => $echeance_row['montant']);   // Array with all payments dispatching
            //print $paiementc[$j]['paiementcode'];
            $paiement->paiementid = dol_getIdFromCode($db, $paiementc[$j]['paiementcode'], 'c_paiement');
            
            $number_ech = str_pad($echeance_row['num'] + 1, 3, '0', STR_PAD_LEFT);
            if ($paiementc[$j]['paiementcode'] == 'CHQ') {
                if (GETPOST('num'.$i) != ''){
                $paiement->num_paiement = $echeance_row['facnumber'] . '-' . $number_ech . '(cheque n° ' . GETPOST('num' . $i) . ')';
                }  else {
                    $error++;
                    $errmsg = $langs->trans('NoChequeNum');
                }
            } else {

                $paiement->num_paiement = $echeance_row['facnumber'] . '-' . $number_ech;
                $paiement->note = GETPOST('num' . $i);
            }



            if (!$error) {
                $close = 0;
                $deja_paye = $echeance_row['deja_paye'] + $echeance_row['montant'];
                if ($deja_paye >= $echeance_row['total_ttc'])
                    $close = 1;
                $paiement_id = $paiement->create($user, $close);
                if ($paiement_id < 0) {
                    $errmsg = $paiement->error;
                    $error++;
                }
            }

            if (!$error) {
                $label = '(CustomerInvoicePayment)';
                $result = $paiement->addPaymentToBank($user, 'payment', $label, $_POST['accountid' . $i], '', '');
                if ($result < 0) {
                    $errmsg = $paiement->error;
                    $error++;
                }
            }

            if (!$error) {
                $db->commit();
                $sql = "update " . MAIN_DB_PREFIX . "echeance set paye=1,montant_paye=".$echeance_row['montant'].",ecart=0,fk_bank=" . $paiement_id . " where rowid=" . $echeance_row['id'];
                $db->query($sql);
                $num = intval($echeance_row['num']) + 1;

                $sql = "update " . MAIN_DB_PREFIX . "echeancier set num=" . $num . " where id=" . $echeance_row['id_ech'];

                $db->query($sql);
            } else {
                $db->rollback();
            }


            $j++;
        }
    }
    if (GETPOST('datefmonth') != '') {
        $lastday = strftime("%Y%m%d", mktime(0, 0, 0, GETPOST('datefmonth'), GETPOST('datefday'), GETPOST('datefyear')));
        $firstday = strftime("%Y%m%d", mktime(0, 0, 0, GETPOST('datedmonth'), GETPOST('datedday'), GETPOST('datedyear')));
        $firstday = strtotime($firstday);
        $lastday = strtotime($lastday);
    } else {

        $mois = date('m');
        $annee = date('y');
        $lastday = strftime("%Y%m%d", mktime(0, 0, 0, $mois + 1, 0, $annee));
        $firstday = strftime("%Y%m%d", mktime(0, 0, 0, $mois, 1, $annee));
        $firstday = strtotime($firstday);
        $lastday = strtotime($lastday);
    }
}






/*
 * VIEW
 *
 * Put here all code to build page
 */

$css = array('/echeancier/css/styles.css');
llxHeader('', 'Echeancier', '', '', '', '', $js, $css);

$html = new Form($db);
$echeance = new echeance($db);



print '<form action="valide.php" method="post">';
print '<input type="hidden" name="action" value="search">';
print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
print '<div id="search"><label>' . $langs->trans('ViewEcheancebtwn') . '</label>';
$html->select_date($firstday, 'dated', '', '', '', "setdate");
print '<label>' . $langs->trans(' et ') . '</label>';
$html->select_date($lastday, 'datef', '', '', '', "setdate");


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

print '<div id="valeur_defaut"><label>' . $langs->trans('DefautOption') . '</label><label>' . $langs->trans('PaymentMode') . ':</label>';
$html->select_types_paiements('', 'paiementcodedefault', '', 2, '', 1);
if (!empty($conf->banque->enabled)) {
    print '<label>' . $langs->trans('AccountToCredit') . ':</label>';
    $html->select_comptes('', 'accountiddefault', 0, '', 2);
}
//TODOT recup valeur valide pour ne pas tout remmetre a la main
print '</div>';
print '<form action="valide.php" method="post">';
print '<input type="hidden" name="action" value="valide">';
print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
print '<input type="hidden" name="datedmonth" value="' . GETPOST('datedmonth') . '">';
print '<input type="hidden" name="datedday" value="' . GETPOST('datedday') . '">';
print '<input type="hidden" name="datedyear" value="' . GETPOST('datedyear') . '">';
print '<input type="hidden" name="datefmonth" value="' . GETPOST('datefmonth') . '">';
print '<input type="hidden" name="datefday" value="' . GETPOST('datefday') . '">';
print '<input type="hidden" name="datefyear" value="' . GETPOST('datefyear') . '">';

print '<table  id="rowclick" class="noborder" width="100%" >';
print '<thead><tr class="liste_titre"><th>' . $langs->trans('Facture') . '</th><th>' . $langs->trans('Nom') . '</th><th>' . $langs->trans('Date de reglement') . '</th><th>' . $langs->trans('montant') . '</th><th>' . $langs->trans('PaymentMode') . '</th><th>' . $langs->trans('AccountToCredit') . '</th><th>' . $langs->trans('ChequeNumber') . '</th><th></th></tr></thead>';
$echeances = $echeance->GetEcheanceFromDate(date('Y-m-d', $firstday), date('Y-m-d', $lastday));
$i = 0;
foreach ($echeances as $echeance_row) {
    if ($echeance_row['type'] == 2) {
        $var = !$var;
        print '<tr ' . $bc[$var] . ' id="row' . $i . '">';
        if (DOL_VERSION < 6.0) {
            print '<td ><a href="' . DOL_MAIN_URL_ROOT . '/compta/facture.php?facid=' . $echeance_row['id_facture'] . '">' . $echeance_row['facnumber'] . '</a></td>';
        } else {
            print '<td ><a href="' . DOL_MAIN_URL_ROOT . '/compta/facture/card.php?facid=' . $echeance_row['id_facture'] . '">' . $echeance_row['facnumber'] . '</a></td>';
        }
        print '<td align="center">' . $echeance_row['nom'] . '</td>';
        print '<td align="center">' . dol_print_date($echeance_row['date_reglement']) . '</td>';
        print '<td align="center">' . $echeance_row['montant'] . '</td><td width="300px" align="center">';
        $html->select_types_paiements('', 'paiementcode' . $i, '', 2, '', 1);
        print '</td><td align="center">';
        if (!empty($conf->banque->enabled)) {
            $html->select_comptes('', 'accountid' . $i, 0, '', 2);
        }
        print '</td><td width="20px"><input id="num"' . $i . ' disabled type="text" name="num' . $i . '" value=""></td>';
        print '</td><td width="20px"><input type="checkbox" disabled name="check' . $i . '" value="' . $echeance_row['id'] . '"></td>';
        print '</tr>';
        $i++;
    }
}

print '<input type="hidden" name="count" value="' . $i . '">';
print '</table>';
print '<div class="tabsAction" ><input type="submit" id="addelementbuton" class="butAction" value="' . $langs->trans("valide") . '"></div></form>';




print '</div>';

// End of page
?>

<script type="text/javascript">


    jQuery(document).ready(function() {
      
            
        jQuery('#rowclick tr')
      
        .filter(':has(:checkbox:checked)')
        .addClass('selected')
        .end()
     
        
        
         
        .click(function(event) {
            
           
           
            jQuery('#rowclick').find('.fire').each(function(){
                jQuery(this).removeClass("fire");
            });
            
            if (event.target.type !== 'select-one' && event.target.type !== 'undefined' && event.target.type !== 'text' ) {
                
                jQuery(this)
                .toggleClass('selected')               
                .addClass('fire');
                jQuery('[id^="selectpaiementcode"]',this).prop("selectedIndex",jQuery('#selectpaiementcodedefault').prop("selectedIndex"));
                jQuery('[id^="selectaccountid"]',this).prop("selectedIndex",jQuery('#selectaccountiddefault').prop("selectedIndex"));
                if (jQuery('[id^="selectpaiementcode"]',this).val() == 'CHQ') { $cheque = true; }else{ $cheque=false}
                    
                jQuery('[id^="num"]',this).attr('disabled', function() {                                
                    
                        return !$cheque;  
                    
                });
                
                   
                jQuery(':checkbox', this)
                .attr('checked', function() {
                    return !this.checked;
                    
                })
                .attr('disabled', function() {
                    return !this.disabled;
                    
                });
            };
             
            
        })
        
    });
    

    
    



</script>

<?php

dol_htmloutput_errors($errmsg);
llxFooter();
$db->close();