<?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");
}

if (!$res) {
    die("Main include failed");
}
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';
// 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");

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

$error = 0;

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

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

    // External user
    accessforbidden();
}


require_once(DOL_DOCUMENT_ROOT . "/comm/propal/class/propal.class.php");
require_once(DOL_DOCUMENT_ROOT . "/core/lib/propal.lib.php");

$langs->load('propal');
$langs->load('compta');
$langs->load('bills');

$id = GETPOST("id");

if (GETPOST('action')) {

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


        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "echeancier (type, montant, nombre, id_element, id_client, date_debut)"
            ." VALUES (1,'" . GETPOST('montant') . "'," . GETPOST('mois') . ",'" . GETPOST('id') . "','" . GETPOST('id_client') . "','" . GETPOST('datedyear') . '-' . GETPOST('datedmonth') . '-' . GETPOST('datedday') . "')";
        $result = $db->query($sql);


        $lastid = $db->last_insert_id(MAIN_DB_PREFIX . "echeancier", "id");

        for ($i = 1; $i < GETPOST('mois') + 1; $i++) {
            if (GETPOST('creation_facture')) {
                $acompte = "FALSE";
            } else {
                $acompte = 'TRUE';
            }
            $sql = "INSERT INTO " . MAIN_DB_PREFIX . "echeance (fk_echeancier, fk_facture, date_reglement, montant, montant_paye, acompte, paye, type, ecart, fk_bank)"
                ." VALUE (" . $lastid . ", 0,'" . date('Y-m-d', strtotime(GETPOST('date' . $i))) . "','" . GETPOST('textbox' . $i) . "', 0," . $acompte . ",FALSE,1,0,0)";
            $result = $db->query($sql);
        }




        header('location:fiche_propale.php?id=' . $id);
    }
}












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


$html = new Form($db);

/* * ************************************************************************** */
/*                                                                             */
/* Mode fiche                                                                  */
/*                                                                             */
/* * ************************************************************************** */


$id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha');
$socid = GETPOST('socid', 'int');
$action = GETPOST('action', 'alpha');
$confirm = GETPOST('confirm', 'alpha');
$lineid = GETPOST('lineid', 'int');

//PDF
$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0));
$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));

// Nombre de ligne pour choix de produit/service predefinis
$NBLINES = 4;

// Security check
$object = new Propal($db);

// Load object
if ($id > 0 || !empty($ref)) {
    $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();
}






/*
 * Actions
 */

$parameters = array('socid' => $socid);






/*
 * View
 */

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


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



// Ref
print '<tr><td>' . $langs->trans('Ref') . '</td><td colspan="5">';
print $form->showrefnav($object, 'ref', '', 0, '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 ($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->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">';
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)) {

    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>';
}

// 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';
}

/*
 * Lines
 */

if (!empty($conf->use_javascript_ajax) && $object->statut == 0) {
    include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
}


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



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



$form = new Form($db);

if (GETPOST('action')) {




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

        $propale = GETPOST('id');
        $montant = GETPOST('montant');
        print '<form action="simul_propal.php" method="post">';
        print '<input type="hidden" name="action" value="add">';
        print '<input type="hidden" name="token" value="' . $_SESSION['newtoken'] . '">';
        print '<input type="hidden" name="id" value="' . $propale . '">';
        print '<input type="hidden" name="montant" value="' . $montant . '">';
        print '<input type="hidden" name="id_client" value="' . GETPOST('id_client') . '">';
        print '<div id="select"><p><label>' . $langs->trans('start_date') . ' : </label>';
        $form->select_date($object->date, 'dated', '', '', '', "setdate");
        print '</p><p><label>' . $langs->trans('echeanceNumber') . ' : </label><input name="mois" type="textbox" id="mois" >';
        print'<select id="periodicite" onchange="calc()"><option value="1">' . $langs->trans('mensuel') . '</option><option value="3">' . $langs->trans('trimestriel') . '</option><option value="6">' . $langs->trans('semestriel') . '</option><option value="12">' . $langs->trans('Annuel') . '</option></select></p></div>';
        print ' <div id="TextBoxesGroup"><div id="TextBoxDiv1"></div></div>';
        print '<input type="submit" disabled id="addelementbuton" class="button" value="' . $langs->trans("Create") . '">';
    }
}
print '</div>';
print "\n";
?>
<script type="text/javascript">
    jQuery(document).ready(function() {
        var nonmanuel = 0;
        var date;
        var $idset;
        var counter = 1;
        var tot = '<?php print $montant; ?>';

        // jQuery('#select :input').live('change',function(event) {
        jQuery('#select :input').bind('input', function() {
            date = new Date(jQuery('#datedyear').val(), jQuery('#datedmonth').val() - 1, jQuery('#datedday').val());
            $idset = setInterval(function() {
                date = new Date(jQuery('#datedyear').val(), jQuery('#datedmonth').val() - 1, jQuery('#datedday').val());

            }, 1000);
            var $periodicite = jQuery('#periodicite').val();
            jQuery('#TextBoxDiv1').html('')
            $loopcount = $('#mois').val(); // get the selected value
            if ($loopcount >= 1)
            {
                jQuery('#addelementbuton').removeAttr('disabled');
            } else {
                jQuery('#addelementbuton').attr("disabled", "disabled");
            }

            var totalfix = (tot / $loopcount).toFixed(<?php echo $conf->global->MAIN_MAX_DECIMALS_TOT ?>);
            for (var i = 1; i <= $loopcount; i++)
            {


               dateText = date.getFullYear() + '-' + ('0'+(date.getMonth()+1)).substr(-2) + '-' + ('0'+date.getDate()).substr(-2);

            jQuery('#TextBoxDiv1').append('<div class="label_echeance"><input type="hidden" name="date' + i + '" value="' + dateText + '"><label>' + date.toLocaleDateString() + '</label><input type="text" id="textbox' + i + '" name="textbox' + i + '" class="textbox2" value="' + totalfix + '" /></div>');

            date.setMonth(parseInt(date.getMonth()) + parseFloat($periodicite));



            }

            calclast();





        }

        );


        jQuery('#TextBoxDiv1 :input').live('change', function(event) {
            nonmanuel = 0;
            var totalmanuel = 0;
            var reste = 0;
            //clearInterval($idset)
            jQuery(event.target).attr('manuel', true);
            jQuery('#TextBoxDiv1 :input:text').each(function(index, domEle) {

                if ($(domEle).attr('manuel')) {

                    totalmanuel = totalmanuel + parseFloat($(domEle).val());
                } else {

                    nonmanuel++;

                }

            });

            var val = ((tot - totalmanuel) / nonmanuel).toFixed(<?php echo $conf->global->MAIN_MAX_DECIMALS_TOT; ?>);
            jQuery('#TextBoxDiv1 :input:text').each(function(index, domEle) {
                if (!($(domEle).attr('manuel'))) {
                    jQuery($(domEle)).val(val);

                }

            });

            calclast();

        });

        function totalttc() {

            var totalttc = 0;
            jQuery('#TextBoxDiv1 :input:text').each(function(index, domEle) {

                totalttc = totalttc + parseFloat($(domEle).val());

            });

            return totalttc

        }

        function calclast() {
            var diff = tot - totalttc();
            var last = "#textbox" + $loopcount.toString();
            var lastele = $('#TextBoxDiv1').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);


        }




    });
</script>

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