<?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 . '/core/lib/invoice.lib.php');
require_once(DOL_DOCUMENT_ROOT . "/compta/facture/class/facture.class.php");
$res = 0;
if (!$res && file_exists(DOL_DOCUMENT_ROOT . "/compta/prelevement/class/bonprelevement.class.php"))
    $res = @require_once(DOL_DOCUMENT_ROOT . "/compta/prelevement/class/bonprelevement.class.php");
if (!$res && file_exists(DOL_DOCUMENT_ROOT . "/compta/prelevement/class/bon-prelevement.class.php"))
    $res = @require_once(DOL_DOCUMENT_ROOT . "/compta/prelevement/class/bon-prelevement.class.php");
if (!$res)
    die("Include of bon prelevement class fails");
$res = 0;
// 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('ide', 'int');
$action = GETPOST('action', 'alpha');


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

$echeancier = new echeancier($db);
$echeancier->fetch($id);
$html = new Form($db);

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

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


    $sql = "";
    $count = GETPOST('count');

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

        if (GETPOST('check' . $i) != '') {
            $paye = 1;
            if (GETPOST('montant' . $i) != '') {
                $montant = "montant='" . GETPOST('montant' . $i) . "',";
            } elseif (GETPOST('montanth' . $i) != '') {
                $montant = "montant='" . GETPOST('montanth' . $i) . "',";
            }
        } elseif (GETPOST('montanth' . $i) != '') {
            $paye = 0;
        } else {
            $paye = 0;
            $montant = "montant='" . GETPOST('montant' . $i) . "',";
        }

        $date = strftime("%Y-%m-%d", mktime(0, 0, 0, GETPOST('dated' . $i . 'month'), GETPOST('dated' . $i . 'day'), GETPOST('dated' . $i . 'year')));
        $sql = " update " . MAIN_DB_PREFIX . "echeance set date_reglement='" . $date . "', " . $montant . " paye='" . $paye . "' where rowid='" . GETPOST('id' . $i) . "';";
        $db->query($sql);
    }
   
    

    header('location:fiche_facture.php?id=' . $echeancier->id_element);
}


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

$css = array('/echeancier/css/styles.css');
llxHeader('', 'Echeancier', '', '', '', '', $js, $css);
if ($_REQUEST["ide"] > 0 || $_REQUEST["ref"]) {
    $fac = new Facture($db);
    if ($fac->fetch($echeancier->id_element, $echeancier->ref_element)) {
        if ($mesg)
            print $mesg . '<br>';

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

        $totalpaye = $fac->getSommePaiement();
        $totalcreditnotes = $fac->getSumCreditNotesUsed();
        $totaldeposits = $fac->getSumDepositsUsed();

        $resteapayer = price2num($fac->total_ttc - $totalpaye - $totalcreditnotes - $totaldeposits, 'MT');

        if ($fac->paye)
            $resteapayer = 0;
        $resteapayeraffiche = $resteapayer;

        $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');

        $author = new User($db);
        if ($fac->user_author) {
            $author->fetch($fac->user_author);
        }

        $head = facture_prepare_head($fac);

        dol_fiche_head($head, 'tabEcheancier', $langs->trans('InvoiceCustomer'), 0, 'bill');

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

        // Ref
        print '<tr><td width="20%">' . $langs->trans("Ref") . '</td><td colspan="5">';
        $morehtmlref = '';
        $discount = new DiscountAbsolute($db);
        $result = $discount->fetch(0, $fac->id);
        if ($result > 0) {
            $morehtmlref = ' (' . $langs->trans("CreditNoteConvertedIntoDiscount", $discount->getNomUrl(1, 'discount')) . ')';
        }
        if ($result < 0) {
            dol_print_error('', $discount->error);
        }
        print $html->showrefnav($fac, 'ref', '', 1, 'facnumber', 'ref', $morehtmlref);
        print "</td></tr>";

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

        // Type
        print '<tr><td>' . $langs->trans('Type') . '</td><td colspan="5">';
        print $fac->getLibType();
        if ($fac->type == 1) {
            $facreplaced = new Facture($db);
            $facreplaced->fetch($fac->fk_facture_source);
            print ' (' . $langs->transnoentities("ReplaceInvoice", $facreplaced->getNomUrl(1)) . ')';
        }
        if ($fac->type == 2) {
            $facusing = new Facture($db);
            $facusing->fetch($fac->fk_facture_source);
            print ' (' . $langs->transnoentities("CorrectInvoice", $facusing->getNomUrl(1)) . ')';
        }

        $facidavoir = $fac->getListIdAvoirFromInvoice();
        if (sizeof($facidavoir) > 0) {
            print ' (' . $langs->transnoentities("InvoiceHasAvoir");
            $i = 0;
            foreach ($facidavoir as $id) {
                if ($i == 0)
                    print ' ';
                else
                    print ',';
                $facavoir = new Facture($db);
                $facavoir->fetch($id);
                print $facavoir->getNomUrl(1);
            }
            print ')';
        }
        if ($facidnext > 0) {
            $facthatreplace = new Facture($db);
            $facthatreplace->fetch($facidnext);
            print ' (' . $langs->transnoentities("ReplacedByInvoice", $facthatreplace->getNomUrl(1)) . ')';
        }
        print '</td></tr>';



        // Date invoice
        print '<tr><td>';
        print '<table class="nobordernopadding" width="100%"><tr><td>';
        print $langs->trans('Date');
        print '</td>';
        if ($fac->type != 2 && $_GET['action'] != 'editinvoicedate' && $fac->brouillon && $user->rights->facture->creer)
            print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editinvoicedate&amp;facid=' . $fac->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
        print '</tr></table>';
        print '</td><td colspan="3">';

        if ($fac->type != 2) {
            if ($_GET['action'] == 'editinvoicedate') {
                $html->form_date($_SERVER['PHP_SELF'] . '?facid=' . $fac->id, $fac->date, 'invoicedate');
            } else {
                print dol_print_date($fac->date, 'daytext');
            }
        } else {
            print dol_print_date($fac->date, 'daytext');
        }
        print '</td>';
        print '</tr>';

        // Date payment term
        print '<tr><td>';
        print '<table class="nobordernopadding" width="100%"><tr><td>';
        print $langs->trans('DateMaxPayment');
        print '</td>';
        if ($fac->type != 2 && $_GET['action'] != 'editpaymentterm' && $fac->brouillon && $user->rights->facture->creer)
            print '<td align="right"><a href="' . $_SERVER["PHP_SELF"] . '?action=editpaymentterm&amp;facid=' . $fac->id . '">' . img_edit($langs->trans('SetDate'), 1) . '</a></td>';
        print '</tr></table>';
        print '</td><td colspan="3">';
        if ($fac->type != 2) {
            if ($_GET['action'] == 'editpaymentterm') {
                $html->form_date($_SERVER['PHP_SELF'] . '?facid=' . $fac->id, $fac->date_lim_reglement, 'paymentterm');
            } else {
                print dol_print_date($fac->date_lim_reglement, 'daytext');
                if ($fac->date_lim_reglement < ($now - $conf->facture->client->warning_delay) && !$fac->paye && $fac->statut == 1 && !$fac->am)
                    print img_warning($langs->trans('Late'));
            }
        }
        else {
            print '&nbsp;';
        }
        print '</td></tr>';

        // Conditions de reglement
        print '<tr><td>';
        print '<table class="nobordernopadding" width="100%"><tr><td>';
        print $langs->trans('PaymentConditionsShort');
        print '</td>';
        print '</tr></table>';
        print '</td><td colspan="3">';
        if ($fac->type != 2) {

            $html->form_conditions_reglement($_SERVER['PHP_SELF'] . '?facid=' . $fac->id, $fac->cond_reglement_id, 'none');
        } else {
            print '&nbsp;';
        }
        print '</td></tr>';

        // Mode de reglement
        print '<tr><td>';
        print '<table class="nobordernopadding" width="100%"><tr><td>';
        print $langs->trans('PaymentMode');
        print '</td>';
        print '</tr></table>';
        print '</td><td colspan="3">';
        $html->form_modes_reglement($_SERVER['PHP_SELF'] . '?facid=' . $fac->id, $fac->mode_reglement_id, 'none');

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

        // Montants
        print '<tr><td>' . $langs->trans('AmountHT') . '</td>';
        print '<td align="right" colspan="2" nowrap>' . price($fac->total_ht) . '</td>';
        print '<td>' . $langs->trans('Currency' . (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td></tr>';
        print '<tr><td>' . $langs->trans('AmountVAT') . '</td><td align="right" colspan="2" nowrap>' . price($fac->total_tva) . '</td>';
        print '<td>' . $langs->trans('Currency' . (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td></tr>';

        // Amount Local Taxes
        if ($mysoc->pays_code == 'ES') {
            if ($mysoc->localtax1_assuj == "1") { //Localtax1 RE
                print '<tr><td>' . $langs->transcountry("AmountLT1", $mysoc->pays_code) . '</td>';
                print '<td align="right" colspan="2" nowrap>' . price($fac->total_localtax1) . '</td>';
                print '<td>' . $langs->trans("Currency" . (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td></tr>';
            }
            if ($mysoc->localtax2_assuj == "1") { //Localtax2 IRPF
                print '<tr><td>' . $langs->transcountry("AmountLT2", $mysoc->pays_code) . '</td>';
                print '<td align="right" colspan="2" nowrap>' . price($fac->total_localtax2) . '</td>';
                print '<td>' . $langs->trans("Currency" . (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td></tr>';
            }
        }

        print '<tr><td>' . $langs->trans('AmountTTC') . '</td><td align="right" colspan="2" nowrap>' . price($fac->total_ttc) . '</td>';
        print '<td>' . $langs->trans('Currency' . (!empty($object->multicurrency_code) ? $object->multicurrency_code : $conf->currency)) . '</td></tr>';

        // Statut
        print '<tr><td>' . $langs->trans('Status') . '</td>';
        print '<td align="left" colspan="3">' . ($fac->getLibStatut(4, $totalpaye)) . '</td></tr>';



        print '</table>';
    } else {
        /* Invoice not found */
        print $langs->trans("ErrorBillNotFound", $_GET["facid"]);
    }
}

if ($echeancier->GetEcheancesFromFacture($fac->id)) {
    print '<table id="ticket" class="noborder" width="100%" >';
    print '<thead><tr class="liste_titre"><th>' . $langs->trans('montant') . '</th><th>' . $langs->trans('echeance') . '</th><th>' . $langs->trans('LastEcheance') . '</th><th></th></tr></thead>';

    $echeancier->fetch($echeancier->id);
    print '<tr>';
    print '<form action="modif_echeancier_facture.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="' . GETPOST('redirect') . '">';

    print '<td align="center">' . price($echeancier->deja_paye) . ' de ' . price($echeancier->montant) . '</td>';
    print '<td align="center">' . $echeancier->count_paye . ' sur ' . $echeancier->nombre_echeance . '</td>';
    print '<td align="center">' . dol_print_date($echeancier->echeances[$echeancier->nombre_echeance - 1]['date_reglement']) . '</td>';
    print '</tr>';



    print '</table>';
}
$montant = $echeancier->montant;




print '<form action="valide.php" method="post">';
print '<input type="hidden" name="action" value="modife">';
print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';


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


$i = 0;
foreach ($echeancier->echeances as $echeance_row) {
    $var = !$var;
    $disabled = '';
    $check = '';
    if ($echeance_row['paye']) {
        $disabled = "disabled";
        $check = 'checked="checked"';
        print '<input type="hidden" name="montanth' . $i . '" value="' . $echeance_row['montant'] . '">';
    }
    print '<tr ' . $bc[$var] . ' id="row' . $i . '">';
    print '<td align="center">';
    $html->select_date($echeance_row['date_reglement'], 'dated' . $i, '', '', '', "setdate",1,0,0,$echeance_row['paye']);
    print '</td>';
    print '<td align="center"><input ' . $disabled . ' type="text" manuel="true" id="montant' . $i . '" name="montant' . $i . '" value="' .($echeance_row['paye']?$echeance_row['montant_paye']:$echeance_row['montant']) . '"></td>';


    print '<td align="center"></td>';
    $disabled = '';
    if ($echeance_row['paye']) {
        if ($echeance_row['num_chq'] != '') {
            print '<td >' . $echeance_row['num_chq'] . '<input type="checkbox" class="hide"  checked="checked" name="check' . $i . '" value="' . $echeance_row['id'] . '"> </td>';
            
        } else {
            $disabled = 'checked="checked"';
            print '<td width="20px"><input type="checkbox" ' . $disabled . ' name="check' . $i . '" value="' . $echeance_row['id'] . '"></td>';
            
        }
    } else {
        $last = $i;
        print '<td width="20px"><input type="checkbox"  name="check' . $i . '" value="' . $echeance_row['id'] . '"></td>';
    }

    print '<input type="hidden" name="id' . $i . '" value="' . $echeance_row['id'] . '">';
    print '<input type="hidden" name="redirect" value="' . GETPOST('redirect') . '">';
    print '<input type="hidden" name="update" value="' . GETPOST('redirect') . '">';
    print '</tr>';
    $i++;
}

print '<input type="hidden" name="count" value="' . $i . '">';
print '</table>';
print '<span class="alert">'.$langs->trans('NoModifInvoice').'</span>';
print '<div class="tabsAction semi" ><input type="submit" id="addelementbuton" class="butAction" value="' . $langs->trans("modifie") . '"><input type="button" id="recalcul" class="butAction" value="' . $langs->trans("Recalcul") . '"></div></form>';




print '</div>';
?>

<script type="text/javascript">
    jQuery(document).ready(function(){
        var nonmanuel = 0 ;
        var date;
        var $idset;
        $loopcount = <?php print $i - 1; ?>; 
        var counter = 1;
        tot = '<?php print $montant; ?>' ;
        dejaPaye = <?php print $echeancier->deja_paye?$echeancier->deja_paye:0 ?>;
        var lasti = <?php print $last ?> ;
        
        $('#recalcul').click(recalcul);
        
   
        

        jQuery('#echeancier :input').on('change',function(event) {
            nonmanuel = 0 ;
            var totalmanuel = 0 ;
            var reste =0 ;
            //clearInterval($idset)
            jQuery(event.target).attr('manuel', true);
            jQuery('#echeancier :input:text').each(function(index,domEle){
                
            
       
                if ($(domEle).attr('manuel') && !$(domEle).attr('disabled') && $(domEle).attr('name').substring(0, 5) != 'dated'){
                
                    totalmanuel = totalmanuel + parseFloat($(domEle).val());
                }else{
                    if (!$(domEle).attr('disabled') && $(domEle).attr('name').substring(0, 5) != 'dated'){
                        nonmanuel++;
                    }
                }
                
            
            });
           
            var val = ((tot-totalmanuel)/nonmanuel).toFixed(<?php echo $conf->global->MAIN_MAX_DECIMALS_TOT; ?>);
            jQuery('#echeancier :input:text').each(function(index,domEle){
                if (!($(domEle).attr('manuel')) && !$(domEle).attr('disabled') && $(domEle).attr('name').substring(0, 5) != 'dated'){
                    jQuery($(domEle)).val(val);
                
                }
            
            });
       
            calclast();
    
        });

        function totalttc(){
    
            var totalttc=0;
            jQuery('#echeancier :input:text').each(function(index,domEle){
                
                if ( $(domEle).attr('name').substring(0, 5) != 'dated'){
                    totalttc = totalttc + parseFloat($(domEle).val());
               
                }       
            });
    
            return totalttc;
    
        }
        
        function add_echeance () { 
         
                    
            
                      
            
            var totalfix = (tot/$loopcount).toFixed(<?php echo $conf->global->MAIN_MAX_DECIMALS_TOT ?>);
           
               
                
            jQuery('#echeancier').append('<div class="label_echeance"><input type="hidden" name="date'+i+'" value="'+date +'"><label>'+date.toLocaleDateString()+'</label><input type="text" id="textbox'+i+'" name="textbox'+i+'" class="textbox2" value="'+totalfix+'" /></div>');
                
            date.setMonth(date.getMonth() + $periodicite );
               
        
    
            
               
            calclast();
        }

        function calclast(){
            var diff = tot - totalttc();
            var last= "#montant" + lasti.toString();
            var lastele = $('#echeancier').find(last);
            var lasttextbox = parseFloat(jQuery(lastele).val());
            var lastval = (lasttextbox + diff).toFixed(<?php echo $conf->global->MAIN_MAX_DECIMALS_TOT ?>);
            jQuery(last).val(lastval);
            
            //setTimeout(function(){clearInterval($idset)},100);
    
    
        }
        
       
        function recalcul(){
            nondisabled = 0;
            disabled = 0;
            datenow = new Date(new Date().getTime()-1 * 24 * 60 * 60 * 1000);
            jQuery('#echeancier :input:text[name^=montant]').each(function(index,domEle){
            element = $(domEle).attr('name').substring(7, 10);   
                if (!$(domEle).is(':disabled')){
                     date = new Date(jQuery('#dated'+element+'year').val(),  parseInt(jQuery('#dated'+element+'month').val())-1 , parseInt(jQuery('#dated'+element+'day').val()) +1);
                     if (date < datenow){
                          $(domEle).val(0);
                          $(':input[name=check'+element+']').attr('checked', true);
                     }else{
                    nondisabled++;
                    $(domEle).attr('manuel',false);
                     }
                }
               
                           
            });
            var val = ((tot-dejaPaye)/nondisabled).toFixed(<?php echo $conf->global->MAIN_MAX_DECIMALS_TOT; ?>);
            $('#echeancier :input:text[name^=montant]').each(function(index,domEle){
               if ($(domEle).attr('manuel') === 'false' && !$(domEle).is(':disabled')){
                    $(domEle).val(val);
                            }
            
            });
            
            var totalttc=0;
            jQuery('#echeancier :input:text[name^=montant]').each(function(index,domEle){
                if ( !$(domEle).is(':disabled')){
                    totalttc = totalttc + parseFloat($(domEle).val());
                }       
            });
       
            var diff = tot - dejaPaye - totalttc;
            var last= "#montant" + lasti.toString();
            var lastele = $('#echeancier').find(last);
            var lasttextbox = parseFloat(jQuery(lastele).val());
            var lastval = (lasttextbox + diff).toFixed(<?php echo $conf->global->MAIN_MAX_DECIMALS_TOT ?>);
            jQuery(last).val(lastval);
        }



    });
     
            
        
</script>

<?php
// End of page
llxFooter();
$db->close();