<?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");
}
// 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');
$total = GETPOST('montant', 'alpha');

// Access control
if ($user->societe_id > 0) {
    // External user
    //accessforbidden();
}

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;
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/class/discount.class.php');

if (!$user->rights->facture->lire || !$user->rights->echeancier->voir)
    accessforbidden();

$langs->load("bills");
$langs->load("banks");
$langs->load("withdrawals");

// Security check
if ($user->societe_id > 0) {
    $action = '';
    $socid = $user->societe_id;
}
$echeancier = new echeancier($db);

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

if (GETPOST('action') == 'supval') {
    $sql = "delete from " . MAIN_DB_PREFIX . "echeance where fk_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');
}

$now = dol_now();
$css = array('/echeancier/css/styles.css');
llxHeader('', 'Echeancier', '', '', '', '', $js, $css);
print_fiche_titre($langs->trans('echeancier'));

$html = new Form($db);

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

    $echeancier->fetch($_POST['ide']);
    if ($echeancier->count_paye > 0) {
        setEventMessage($langs->trans('NotSupEcheancier'), 'errors');
    } else {

        print $langs->trans('ConfirmSupEcheancier') . ' ' . 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();
    }
}

if ($_REQUEST["id"] > 0 || $_REQUEST["ref"]) {
    $fac = new Facture($db);
    if ($fac->fetch($_REQUEST["id"], $_REQUEST["ref"])) {
        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>';
        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>';
        print '</tr></table>';
        print '</td><td colspan="3">';
        if ($fac->type != 2) {

            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) {
if (method_exists($html,'form_conditions_reglement')){
	$html->form_conditions_reglement(
        $_SERVER['PHP_SELF'] . '?facid=' 
        . $fac->id
        , $fac->cond_reglement_id, 'none');
}else {
	
}
            
        } 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 align="center">' . $langs->trans('montant') . '</th><th align="center" >' . $langs->trans('écheance') . '</th><th align="center">' . $langs->trans('LastEcheance') . '</th><th></th></tr></thead>';

    $echeancier->fetch($echeancier->id);
    $dejapaye = $echeancier->deja_paye == null ? 0 : $echeancier->deja_paye;
    $montanttotal = floatval($echeancier->montant);

    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="' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING'] . '">';
    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(strtotime($echeancier->echeances[count($echeancier->echeances) - 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="' . $fac->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 align="center">' . $langs->trans('Montant') . '</th><th align="center">' . $langs->trans('PaidAmount') . '</th><th align="center">' . $langs->trans('Difference') . '</th><th align="center">' . $langs->trans('Solde facture') . '</th><th align="center">' . $langs->trans('Solde théorique') . '</th><th align="center">' . $langs->trans('Paye') . '</th></tr></thead>';

    $i = 0;
    $ecart = $montanttotal * -1;
    $echeancedue =0;

    $ecarttheorique = $montanttotal ;
    $ecart = intval($ecart);
    foreach ($echeancier->echeances as $echeance_row) {
        $var = !$var;

        print '<tr ' . $bc[$var] . ' id="row' . $i . '">';
        print '<td align="center">' . dol_print_date(strtotime($echeance_row['date_reglement'])) . '</td>';
        print '<td align="center">' . price($echeance_row['montant']) . '</td>';
        print '<td align="center">' . price($echeance_row['montant_paye']) . '</td>';
        print '<td align="center">' . price($echeance_row['ecart'] * -1) . '</td>';
        $ecart +=   $echeance_row['montant_paye'];
       /* if ($echeance_row['montant'] == 0) {
            $ecarttheorique = $ecarttheorique - $echeance_row['montant_paye'];
        }
        
       /* if ($echeance_row['ecart'] != 0)
            $ecarttheorique = $ecarttheorique - $echeance_row['ecart'];*/
        $ecarttheorique =  $ecarttheorique - $echeance_row['montant'] ;
     

        print '<td align="center">' . price($ecart) .'</td><td align="center">'. price($ecarttheorique).'</td>';

        if ($echeance_row['paye'] || $echeance_row['ecart'] != 0) {

            if ($echeance_row['num_chq'] != '') {
                print '<td align="center"><a href="' . DOL_URL_ROOT . '/compta/paiement/fiche.php?id=' . $echeance_row['paiement_id'] . '">' . $echeance_row['num_chq'] .($echeance_row['paye']?'':'<br>[Paiement partiel]').'</a></td>';
            } else {
                print '<td align="center">oui</td>';
            }
        } else {  print '<td align="center"></td>';
        $echeancedue += $echeance_row['montant'];
        }
        print '</tr>';
        $i++;
    }

    print '</table>';
    print '</div>';
    $tot = price2num(price($montanttotal), $conf->global->MAIN_MAX_DECIMALS_TOT);
    if ($dejapaye + $echeancedue - $tot > 0.00001) {
        setEventMessage($langs->trans('AmountDifere'), 'errors');
        $diff = $dejapaye + $echeancedue - $tot;
        setEventMessage('difference:'.price2num($diff,'MT'),'errors');
    }

    print '</div>';
} else {
    if ($fac->mode_reglement_code == 'ECH') {
        print '<div class="tabsAction" ><form action="echeancier_facture.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="' . $fac->id . '">';
        print '<input type="hidden" name="montant" value="' . $fac->total_ttc . '">';
        print '<input type="hidden" name="ref" value="' . $fac->ref . '">';
        print '<input type="hidden" name="id_client" value="' . $fac->socid . '">';
        print '<input type="submit" id="addelementbuton" class="button" value="' . $langs->trans("Créer") . '">';
        print '</form></div>';
    }
}

//echo '<pre>';var_dump($conf);echo '</pre>';

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