<?php // BEGIN PHP

//session_set_cookie_params(['lifetime' => 0, 'path' => '/', 'domain' => '', 'secure' => true, 'httponly' => true, 'samesite' => 'Lax');
session_start(); // start session

require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
require_once DOL_DOCUMENT_ROOT . '/core/lib/categories.lib.php';
include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
require_once DOL_DOCUMENT_ROOT."/commande/class/commande.class.php";
require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';

include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';

//error_reporting(E_ALL);
//ini_set('display_errors', 1);

print '<script nonce="'.getNonce().'" type="text/javascript" src="'.DOL_MAIN_URL_ROOT.'/core/js/lib_head.js.php"></script>'."\n";

$form = new Form($db);

$date_start_timestamp = '';
$date_end_timestamp = '';
if (!empty(GETPOST('datestart')) || !empty(GETPOST('dateend'))) {
    
    $date_start = GETPOST('datestart');
    $date_end = GETPOST('dateend');
    
    $date_start_timestamp = dol_mktime(0, 0, 0, GETPOSTINT('datestartmonth'), GETPOSTINT('datestartday'), GETPOSTINT('datestartyear'));
    $date_end_timestamp = dol_mktime(0, 0, 0, GETPOSTINT('dateendmonth'), GETPOSTINT('dateendday'), GETPOSTINT('dateendyear'));
    
    $error = 0;
    $error_messages = array();
    
    if ((empty($date_start) && !empty($date_end)) || (!empty($date_start) && empty($date_end))) {
        $error++;
        $error_messages[] = "oneDateEmpty";
    }
    
    if ($date_end_timestamp < $date_start_timestamp) {
        $error++;
        $error_messages[] = "endDateMustBeGreater";
    }
    
    $filter = '';
    if ($error == 0 && !empty($date_start) && !empty($date_end)) {
        $filter = " AND c.date_commande BETWEEN '".$db->idate($date_start_timestamp)."' AND '".$db->idate($date_end_timestamp)."'";
    }
}



$weblangs->load('companies');

// If not login redirect to login.
if(empty($_SESSION['user']['id_user'])){
    redirectToContainer('login-register');
}


// Get Account ID.
$user_id = $_SESSION['user']['id_user'];
$customer_account = new SocieteAccount($db);
$result = $customer_account->fetch($user_id);
$customer_id = $customer_account->fk_soc;

// Get soc info.
$socInfo = new Societe($db);
$socInfo->fetch($customer_id);

// Get account info
$accounts = array();
$sql = "select rowid, login from ".MAIN_DB_PREFIX."societe_account where fk_soc = ".$customer_id." AND fk_website = ".$website->id." LIMIT 100";
$resql = $db->query($sql);
while ($objsql = $db->fetch_object($resql)) {
    $accounts[] = array('id' => $objsql->rowid, 'login' => $objsql->login);
}

/*
$cContacts = $socInfo->contact_array_objects();
foreach ($cContacts as $cContact) {
    if ($cContact->ref_ext == $user_id) {
        $customer_firstname = $cContact->firstname;
        $customer_lastname = $cContact->lastname;
        $customer_email = $cContact->email;
        $customer_address = $cContact->address;
    }
}
*/


// To render the view of another user
if (!empty(GETPOST('id_customer'))) {
    // Only for members with a specific role
    require_once DOL_DOCUMENT_ROOT."/adherents/class/adherent.class.php";
    $membre = new Adherent($db);
    $result = $membre->fetch('', 0, $customer_id);
    
    $adminsCat = new Categorie($db);
	$adminsCat->fetch(1);
	
	$result = $adminsCat->containsObject('member', $membre->id);
	if ($result > 0) {
	    
        $customer_id = GETPOST('id_customer');
        // Get soc info.
        $socInfo = new Societe($db);
        $socInfo->fetch($customer_id);
        
        // Get soc acount email
        $sql = "select rowid from ".MAIN_DB_PREFIX."societe_account where fk_soc = ".$customer_id." AND fk_website = ".$website->id;
        $result = $db->query($sql);
        $objsql = $db->fetch_object($result);
        
        // Get account info
        /*
        $cContacts = $socInfo->contact_array_objects();
        foreach ($cContacts as $cContact) {
            if ($cContact->ref_ext == $objsql->rowid) {
                $customer_firstname = $cContact->firstname;
                $customer_lastname = $cContact->lastname;
                $customer_email = $cContact->email;
                $customer_address = $cContact->address;
            }
        }
        */
	}
}

// Get customer ID.
$customer = new Societe($db);
$result = $customer->fetch($customer_id);

// Get liste of products
$products_ids = array();
/*$sql = 'SELECT fk_product, datec FROM '.MAIN_DB_PREFIX."product_fournisseur_price, '.MAIN_DB_PREFIX.'categorie_product AS cp WHERE fk_soc = ".((int) $customer_id). " AND cp.fk_categorie = '.getDolGlobalInt("MARKETPLACE_ROOT_CATEGORY_ID").' GROUP BY fk_product ORDER BY datec DESC";*/
$sql = 'SELECT pf.fk_product, MIN(pf.datec) AS first_date
        FROM '.MAIN_DB_PREFIX.'product_fournisseur_price as pf, '.MAIN_DB_PREFIX.'categorie_product AS cp 
        WHERE pf.fk_soc = '.$customer_id.' AND pf.fk_product = cp.fk_product 
        AND cp.fk_categorie = '.getDolGlobalInt("MARKETPLACE_ROOT_CATEGORY_ID").' 
        GROUP BY fk_product 
        ORDER BY first_date DESC';

if ($result_products = $db->query($sql)) {
	while ($product_id = $result_products->fetch_object()) {
        $products_ids[] = $product_id->fk_product;
	}
}
$products_ids_str = implode(',', $products_ids);

if (!empty($products_ids_str)) {
    $all_sells_period = "SELECT SUM(d.qty) AS sells ";
    $all_sells_period .= "FROM ".MAIN_DB_PREFIX."commande as c, ".MAIN_DB_PREFIX."commandedet as d ";
    $all_sells_period .= "WHERE c.rowid = d.fk_commande and d.fk_product IN (" . $products_ids_str . ") and d.total_ht != 0 and c.fk_statut IN (1,3) and (c.facture = 1 OR c.ref_ext IS NOT NULL) and c.module_source = 'Marketplace' ";
    if (!empty($filter)) {
       $all_sells_period .=  $filter;
    }
    $resql = $db->query($all_sells_period);
    $all_sells_period = $db->fetch_object($resql);
    
    $sum_all_sells_period = "SELECT SUM(d.total_ht) as total ";
    $sum_all_sells_period .= "FROM ".MAIN_DB_PREFIX."commande as c, ".MAIN_DB_PREFIX."commandedet as d ";
    $sum_all_sells_period .= "WHERE c.rowid = d.fk_commande and d.fk_product IN (" . $products_ids_str . ") and c.fk_statut IN (1,3) and (c.facture = 1 || c.ref_ext IS NOT NULL) and c.module_source = 'Marketplace' ";
    if (!empty($filter)) {
       $sum_all_sells_period .=  $filter;
    }
    $resql = $db->query($sum_all_sells_period);
    $sum_all_sells_period = $db->fetch_object($resql);
    
    $sum_all_validated_sells_period = "SELECT SUM(d.total_ht) as total ";
    $sum_all_validated_sells_period .= "FROM ".MAIN_DB_PREFIX."commande as c, ".MAIN_DB_PREFIX."commandedet as d ";
    $sum_all_validated_sells_period .= "WHERE c.rowid = d.fk_commande and d.fk_product IN (" . $products_ids_str . ") and (c.facture = 1 || c.ref_ext IS NOT NULL) and c.module_source = 'Marketplace' ";
    $sum_all_validated_sells_period .= "AND c.date_commande < DATE_SUB(NOW(), INTERVAL 1 MONTH)";
    if (!empty($filter)) {
       $sum_all_validated_sells_period .=  $filter;
    }
    $resql = $db->query($sum_all_validated_sells_period);
    $sum_all_validated_sells_period = $db->fetch_object($resql);
    
    $sum_all_sells = "SELECT SUM(d.total_ht) as total ";
    $sum_all_sells .= "FROM ".MAIN_DB_PREFIX."commande as c, ".MAIN_DB_PREFIX."commandedet as d ";
    $sum_all_sells .= "WHERE c.rowid = d.fk_commande and d.fk_product IN (" . $products_ids_str . ") and c.fk_statut IN (1,3) and (c.facture = 1 || c.ref_ext IS NOT NULL) and c.module_source = 'Marketplace' ";
    $resql = $db->query($sum_all_sells);
    $sum_all_sells = $db->fetch_object($resql);
    
    $sum_all_validated_sells = "SELECT SUM(d.total_ht) as total ";
    $sum_all_validated_sells .= "FROM ".MAIN_DB_PREFIX."commande as c, ".MAIN_DB_PREFIX."commandedet as d ";
    $sum_all_validated_sells .= "WHERE c.rowid = d.fk_commande and d.fk_product IN (" . $products_ids_str . ") and (c.facture = 1 || c.ref_ext IS NOT NULL) and c.module_source = 'Marketplace' ";
    $sum_all_validated_sells .= "AND c.date_commande < DATE_SUB(NOW(), INTERVAL 1 MONTH)";
    
    $resql = $db->query($sum_all_validated_sells);
    $sells_done_validated = $db->fetch_object($resql);
    
    // Calculate all discounts for this customer products
    $TOTAL_DISCOUNTS = 0;
    $like_conditions = [];
    foreach ($products_ids as $product_id) {
        $like_conditions[] = "d.description LIKE '" . $product_id . "# %'";
    }
    // Join all conditions with OR
    $like_clause = implode(' OR ', $like_conditions);
    
    $sum_all_discounts = "SELECT SUM(d.total_ht) as total ";
    $sum_all_discounts .= "FROM ".MAIN_DB_PREFIX."commande as c, ".MAIN_DB_PREFIX."commandedet as d ";
    $sum_all_discounts .= "WHERE c.rowid = d.fk_commande ";
    $sum_all_discounts .= "AND (" . $like_clause . ") ";
    $sum_all_discounts .= "AND (c.facture = 1 OR c.ref_ext IS NOT NULL) ";
    $sum_all_discounts .= "AND c.module_source = 'Marketplace' ";
    $resql = $db->query($sum_all_discounts);
    $sells_discounts = $db->fetch_object($resql);
    $TOTAL_DISCOUNTS = $sells_discounts->total;
    
    /*=========== Payment History ====================*/
    $payment_history = "SELECT f.rowid, f.ref, f.fk_statut, f.fk_soc, f.datec, f.datef, f.date_closing, f.total_ht , f.total_ttc ";
    $payment_history .= "FROM ".MAIN_DB_PREFIX."facture_fourn as f ";
    $payment_history .= "WHERE f.fk_soc = " . ((int) $customer_id) . " and f.fk_statut = 2 and f.paye = 1 ORDER BY f.datef DESC";

    $alreadyreceived=0;
    $dolistoreinvoices=array();
    $linesinvoice = array();
    if ($result_payment_history = $db->query($payment_history)) {

        while ($payment = $result_payment_history->fetch_object()) {
            $invoice = new FactureFournisseur($db);
            $result = $invoice->fetch($payment->rowid);
            
            // Define lines of invoice
            $linesresp = array();
            foreach ($invoice->lines as $line) {
                    $linesresp[] = array(
                            'id' => $line->rowid,
                            'type' => $line->product_type,
                            'desc' => dol_htmlcleanlastbr($line->desc),
                            'total_net' => $line->total_ht,
                            'total_vat' => $line->total_tva,
                            'total' => $line->total_ttc,
                            'vat_rate' => $line->tva_tx,
                            'qty' => $line->qty,
                            'product_ref' => $line->product_ref,
                            'product_label' => $line->product_label,
                            'product_desc' => $line->product_desc,
                    );
            }
            
            // Now define invoice
            $linesinvoice[] = array(
                    'id' => $invoice->id,
                    'ref' => $invoice->ref,
                    'ref_supplier' => $invoice->ref_supplier,
                    'ref_ext' => $invoice->ref_ext,
                    'fk_user_author' => $invoice->user_creation_id,
                    'fk_user_valid' => $invoice->user_validation_id,
                    'fk_thirdparty' => $invoice->socid,
                    'type' => $invoice->type,
                    'status' => $invoice->status,
                    'total_net' => $invoice->total_ht,
                    'total_vat' => $invoice->total_tva,
                    'total' => $invoice->total_ttc,
                    'date_creation' => dol_print_date($invoice->datec, 'dayhourrfc'),
                    'date_modification' => dol_print_date($invoice->tms, 'dayhourrfc'),
                    'date_invoice' => dol_print_date($invoice->date, 'dayhourrfc'),
                    'date_term' => dol_print_date($invoice->date_echeance, 'dayhourrfc'),
                    'label' => $invoice->label,
                    'paid' => $invoice->paid,
                    'note_private' => $invoice->note_private,
                    'note_public' => $invoice->note_public,
                    'close_code' => $invoice->close_code,
                    'close_note' => $invoice->close_note,

                    'lines' => $linesresp
            );
        }
        
        foreach($linesinvoice as $invoice) {
            $dateinvoice=substr($invoice['date_invoice'], 0, 10);
            
            // Rule to detect invoice found is for dolistore payment back
			$isfordolistore=0;
			if ((preg_match('/dolistore/i',$invoice['note_private']) || preg_match('/dolistore/i',$invoice['label']))
				&& ! preg_match('/agios/i',$invoice['ref_supplier'])
				&& ! preg_match('/frais/i',$invoice['ref_supplier'])
				&& ! preg_match('/comDolistore/i',$invoice['ref_supplier'])
				) $isfordolistore=1;
				
			if (! $isfordolistore) {
				foreach($invoice['lines'] as $line)
				{
					if (preg_match('/dolistore/i',$line['desc'])
						&& ! preg_match('/Remboursement certificat|Remboursement domaine/i',$line['desc'])
						&& ! preg_match('/agios/i',$invoice['ref_supplier'])
						&& ! preg_match('/frais/i',$invoice['ref_supplier'])
						&& ! preg_match('/comDolistore/i',$invoice['ref_supplier'])
						)
					{
						$isfordolistore++;
					}
				}
			}
			
			if ($isfordolistore)
			{
				// Array of already received and paid invoices
				$dolistoreinvoices[]=array(
					'dolistore_customer_id'=>$customer_id,
					'id'=>$invoice['id'],
					'ref'=>$invoice['ref'],
					'ref_supplier'=>$invoice['ref_supplier'],
					'status'=>$invoice['status'],
					'date'=>$invoice['date_invoice'],
					'datenohour'=>$dateinvoice,
					'amount_ht'=>$invoice['total_net'],
					'amount_vat'=>$invoice['total_vat'],
					'amount_ttc'=>$invoice['total'],
					'fk_thirdparty'=>$invoice['fk_thirdparty']
				);
			}
        }
    }
    
    // Calculte total recived amount
    foreach ($dolistoreinvoices as $item) {
        $tmpdate=preg_replace('/(\s|T)00:00:00Z/','',$item['date']);
        if (strcmp($tmpdate,'2013-01-01') < 0) $alreadyreceived+=$item['amount_ttc'];
		else $alreadyreceived+=$item['amount_ht'];
    }
    /*=========== Payment History ====================*/

    
    
    /*$sum_payment_done_before_2013 = "SELECT SUM(f.total_ttc) as payment_done ";
    $sum_payment_done_before_2013 .= "FROM ".MAIN_DB_PREFIX."facture_fourn as f ";
    $sum_payment_done_before_2013 .= "WHERE f.fk_soc = " . ((int) $customer_id) . " and f.fk_statut = 2 and f.paye = 1 AND (f.libelle LIKE '%vente%' OR f.libelle LIKE '%dolistore%') and f.datef < '2013-01-01' ";
    $resql = $db->query($sum_payment_done_before_2013);
    $sum_payment_done_before_2013 = $db->fetch_object($resql);
    
    $sum_payment_done_after_2013 = "SELECT SUM(f.total_ht) as payment_done ";
    $sum_payment_done_after_2013 .= "FROM ".MAIN_DB_PREFIX."facture_fourn as f ";
    $sum_payment_done_after_2013 .= "WHERE f.fk_soc = " . ((int) $customer_id) . " and f.fk_statut = 2 and f.paye = 1 AND (f.libelle LIKE '%vente%' OR f.libelle LIKE '%dolistore%') and f.datef > '2013-01-01' ";
    $resql = $db->query($sum_payment_done_after_2013);
    $sum_payment_done_after_2013 = $db->fetch_object($resql);
    
    
    $sum_payment_done = "SELECT SUM(f.total_ht) as payment_done ";
    $sum_payment_done .= "FROM ".MAIN_DB_PREFIX."facture_fourn as f ";
    $sum_payment_done .= "WHERE f.fk_soc = " . ((int) $customer_id) . " and f.fk_statut = 2 and f.paye = 1 AND (f.libelle LIKE '%vente%' OR f.libelle LIKE '%dolistore%') ";
    $resql = $db->query($sum_payment_done);
    $sum_payment_done = $db->fetch_object($resql);*/
    
    $sum_payment_done = $alreadyreceived;
}


// END PHP 
?>
<div id="page">
  <div class="header-container">
    <?php
        includeContainer('header');
        $__PAGE__TITLE__ = $weblangs->trans("incomePaymentsPageTitle");
    ?>
  </div>

  <div class="columns-container">
    <div id="columns" class="container">
        <!--  Breadcrumb  -->
        <div class="breadcrumb clearfix">
        	<a class="home" href="index.php" title="Return to Home"><i class="icon-home"></i></a>
        	<span class="navigation-pipe">&gt;</span> <a href="myaccount.php" title="<?php print $weblangs->trans("myAccount"); ?>" data-gg=""><?php print $weblangs->trans("myAccount"); ?></a>
        	<span class="navigation-pipe">&gt;</span> <?php print $weblangs->trans("incomeAndPayments"); ?>
        </div>
        <!--  Breadcrumb  -->
      <div id="slider_row" class="row">
        <div id="top_column" class="center_column col-xs-12 col-sm-12"></div>
      </div>
        <div class="row">
            <!-- include lefet sidebar container -->
            <?php includeContainer('sidebar'); ?>
            <div id="center_column" class="center_column col-xs-12 col-sm-9">
                <?php if (empty($products_ids_str)): ?>
	                <h1 class="page-heading"><?php print $weblangs->trans("incomeAndPayments"); ?></h1>
	                <p class="alert alert-warning"><?php print $weblangs->trans("noProductToDisplay"); ?> </p>
                <?php else: ?>
                    <div class="clearfix">
                        <h1 class="page-heading"><?php print $weblangs->trans("incomeAndPayments"); ?></h1>
                        <button class="btn btn-default button" id="generate-csv" onclick="generateCSV(<?php print $customer_id; ?>)"><?php print $weblangs->trans("downloadAllSales"); ?> <i class="icon-cloud-download"></i></button>
                        
                        <div id="block-history" class="block-center">
                            <div id="block-order-detail" class="unvisible" style="display: block;">
                                
                                <div <div class="info-order box">
                                    <h3 class="page-subheading">Info</h3>
                                    <div class="row">
                                        <p class="col-xs-6"><b><?php print $weblangs->trans("Company"); ?> :</b> <?php print $socInfo->name; ?> &nbsp; <span class="opacitymedium">(ID <?php print $socInfo->id; ?>)</span></p>
                                        <!--<p class="col-xs-6"><b><?php print $weblangs->trans("ThirdPartyEmail"); ?> :</b> <?php print $socInfo->mail; ?></p>-->
                                        <p class="col-xs-6"><b><?php print $weblangs->trans("ThirdPartyAddress"); ?> :</b> <?php print $socInfo->address; ?></p>
                                        <p class="col-xs-6"><b><?php print $weblangs->trans("Country"); ?> :</b> <?php print $socInfo->country_code; ?></p>
                                        <p class="col-xs-12">&nbsp;</p>
                                        <p class="col-xs-12"><b><?php print $weblangs->trans("Logins") ?> :</b></p>
                                        <?php
                                        foreach ($accounts as $account) {
                                            print '<p class="col-xs-12">';
                                            if (count($accounts) > 1) {
                                                print '- ';   
                                            }
                                            print $account['login'];
                                            if (count($accounts) > 1) {
                                                print ($user_id == $account['id'] ? ' <span class="opacitymedium">(You)</span>' : '');
                                            }
                                            print '</p>';
                                        }
                                        ?>
                                        <!--
                                        <p class="col-xs-6"><b><?php print $weblangs->trans("Login").' - '.$weblangs->trans("Firstname"); ?> :</b> <?php print $customer_firstname; ?></p>
                                        <p class="col-xs-6"><b><?php print $weblangs->trans("Login").' - '. $weblangs->trans("Lastname"); ?> :</b> <?php print $customer_lastname; ?></p>
                                        <p class="col-xs-6"><b><?php print $weblangs->trans("Login").' - '. $weblangs->trans("Email"); ?> :</b> <?php print $customer_email; ?></p>
                                        -->
                                    </div>
                                </div>
                                
                        		<div id="order-detail-content" class="table_block table-responsive box">
                        		    <?php if (isset($error) && $error != 0): ?>
                                		<div class='alert alert-danger'>
                                    		<?php $add_s = ($error > 1) ? "s" : ""; ?>
                		                    <p><?php print $weblangs->trans("errorsOccurred", $error, $add_s); ?></p>
                                    		<ol>
                                    		    <?php foreach ($error_messages as $key => $value): ?>
                                            		<li><?php print $weblangs->trans($value); ?></li>
                                            	<?php endforeach ?>
                                    		</ol>
                                    	</div>
                                	<?php endif ?>
                                	
                                	<h3 class="page-subheading">statistics</h3>
            
                        		    <form action="" method="post" id="account-creation_form">
                                        <div class="form-row align-items-center">
                                            <div class="col-xs-12 form-group row required inline-date-filter">
                                                <span class="">
                                                    <?php print $form->selectDate(($date_start_timestamp ? $date_start_timestamp : -1), 'datestart', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $weblangs->trans("from"), 'auto', DOL_URL_ROOT.'/document.php?modulepart=medias&file=image/test/img/datepicker/object_calendarday.png'); ?>
                                                </span>
                                                <span class="">
                                                    <?php print $form->selectDate($date_end_timestamp ? $date_end_timestamp : -1, 'dateend', 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $weblangs->trans("to"), 'auto', DOL_URL_ROOT.'/document.php?modulepart=medias&file=image/test/img/datepicker/object_calendarday.png'); ?>
                                                </span>
                                                <span class="">
                                                  <button type="submit" class="btn-filter"><?php print $weblangs->trans("Refresh"); ?></button>
                                                </span>
                                            </div>
                                        </div>
                        		    </form>
                                    <hr>
                        		    <table class="table-no-border">
                        		        <?php
                        		            // Check if there is an amount of coupons 
                        		            $TOTAL_REDUC_OLD_SYSTEM = 0;
                            		        if (getDolGlobalString("MARKETPLACE_TOTAL_REDUC_OLD_SYSTEM_" . $customer_id)) {
                            		            $TOTAL_REDUC_OLD_SYSTEM = getDolGlobalString("MARKETPLACE_TOTAL_REDUC_OLD_SYSTEM_" . $customer_id);
                            		        }
                        		        ?>
                        		        <tr>
                        		            <td><?php print $weblangs->trans("numberOfProducts"); ?></td>
                        		            <td><span><?php print count($products_ids); ?></span></td>
                        		        </tr>
                        		        <tr>
                        		            <td><?php print $weblangs->trans("numberOfPaidSells"); ?></td>
                        		            <td><span class="span-blue"><?php print $all_sells_period->sells; ?></span></td>
                        		        </tr>
                        		        <tr>
                                            <td><?php print $weblangs->trans("totalOfSellsDone"); ?></td>
                                            <td>
                                                80% x ( 
                                                <?php print price($sum_all_sells_period->total); ?> 
                                                <?php if ($TOTAL_DISCOUNTS) { 
                                                    print " " . price($TOTAL_DISCOUNTS) . "*"; 
                                                } ?> 
                                                <?php if ($TOTAL_REDUC_OLD_SYSTEM) { 
                                                    print " - " . price($TOTAL_REDUC_OLD_SYSTEM) . "**"; 
                                                } ?> 
                                                ) = 
                                                <span class="span-blue">
                                                    <?php print price(($sum_all_sells_period->total - $TOTAL_REDUC_OLD_SYSTEM + $TOTAL_DISCOUNTS) * 0.80, 0, '', 1, -1, 2); ?>€
                                                </span> 
                                                <?php print $weblangs->trans("exclTax"); ?>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td><?php print $weblangs->trans("totalValidatedSells"); ?></td>
                                            <td>
                                                80% x ( 
                                                <?php print price($sum_all_validated_sells_period->total); ?> 
                                                <?php if ($TOTAL_DISCOUNTS) { 
                                                    print " " . price($TOTAL_DISCOUNTS) . "*"; 
                                                } ?> 
                                                <?php if ($TOTAL_REDUC_OLD_SYSTEM) { 
                                                    print " - " . price($TOTAL_REDUC_OLD_SYSTEM) . "**"; 
                                                } ?> 
                                                ) = 
                                                <span class="span-blue">
                                                    <?php print price(($sum_all_validated_sells_period->total - $TOTAL_REDUC_OLD_SYSTEM + $TOTAL_DISCOUNTS) * 0.80, 0, '', 1, -1, 2); ?>€
                                                </span> 
                                                <?php print $weblangs->trans("exclTax"); ?>
                                            </td>
                                        </tr>
                                        <?php if ($TOTAL_DISCOUNTS != 0): ?>
                                            <tr>
                            		            <td><small> * <?php print $weblangs->trans("totalDiscountsOffered"); ?></small></td>
                            		        </tr>
                                        <?php endif ?>
                        		        <?php if ($TOTAL_REDUC_OLD_SYSTEM != 0): ?>
                                            <tr>
                            		            <td><small> ** <?php print $weblangs->trans("totalVouchersOffered"); ?></small></td>
                            		        </tr>
                                        <?php endif ?>
                        		    </table>

                                </div>
                        		    
            
            
                                <div class="info-order box">
                                    <h3 class="page-subheading"><?php print $weblangs->trans("amountToClaim"); ?></h3>
                        		    <table class="table-no-border">
                        		        <tr>
                        		            <td><?php print $weblangs->trans("remainedAmountInOneMonth"); ?></td>
                        		            <td><span class="span-blue"><?php print price((($sum_all_sells->total - $TOTAL_REDUC_OLD_SYSTEM + $TOTAL_DISCOUNTS) * 0.80) - $sum_payment_done, 0, '', 1, -1, 2); ?>€</span> <?php print $weblangs->trans("exclTax"); ?></td>
                        		        </tr>
                        		        <tr>
                        		            <?php
                        		            // Check if there is at least one supplier invoice done during this current month
                        		            $checkLastPaymentCount = "SELECT COUNT(*) AS payment_count ";
                                            $checkLastPaymentCount .= "FROM " . MAIN_DB_PREFIX . "facture_fourn AS f ";
                                            $checkLastPaymentCount .= "WHERE f.fk_soc = " . ((int) $customer_id) . " AND f.fk_statut = 2 AND f.paye = 1 ";
                                            $checkLastPaymentCount .= "AND (f.libelle LIKE '%vente%' OR f.libelle LIKE '%dolistore%') ";
                                            $checkLastPaymentCount .= "AND MONTH(f.datef) = MONTH(CURDATE()) AND YEAR(f.datef) = YEAR(CURDATE())";
                                            $resql = $db->query($checkLastPaymentCount);
                                            $hasRecivedPaymentThisMonth = $db->fetch_object($resql);
                        		            ?>
                        		            <td><?php print $weblangs->trans("remainedAmountToday"); ?>*</td>
                        		            <?php if ($hasRecivedPaymentThisMonth->payment_count > 0): ?>
                        		                <td><span class="span-blue"><?php print price((($sells_done_validated->total - $TOTAL_REDUC_OLD_SYSTEM + $TOTAL_DISCOUNTS) * 0.80) - $sum_payment_done, 0, '', 1, -1, 2); ?>€</span> <?php print $weblangs->trans("exclTax"); ?> <small><?php print $weblangs->trans("aPaymentWasDoneThisMonth"); ?></small></td>
                        		            <?php else: ?>
                        		                <td><span class="span-blue"><?php print price((($sells_done_validated->total - $TOTAL_REDUC_OLD_SYSTEM + $TOTAL_DISCOUNTS) * 0.80) - $sum_payment_done, 0, '', 1, -1, 2); ?>€</span> <?php print $weblangs->trans("exclTax"); ?></td>
                        		            <?php endif ?>
                        		        </tr>
                        		        
                        		        <?php if (getDolGlobalInt("MARKETPLACE_MINIMUM_PAYOUT_AMOUNT")): ?>
                                            <tr>
                            		            <td><small> <?php print $weblangs->trans("minAmountToClaim"); ?> : <?php print getDolGlobalInt("MARKETPLACE_MINIMUM_PAYOUT_AMOUNT"); ?> €</small></td>
                            		        </tr>
                                        <?php endif ?>
                        		        <tr>
                        		            <td><small> * <?php print $weblangs->trans("minAmountToClaimDesc"); ?></small></td>
                        		        </tr>
                        		    </table>
                        		    
                                </div>
                                
                                <div class="info-order box">
                                    <h3 class="page-subheading"><?php print $weblangs->trans("paymentHistory"); ?></h3>
                        		    <table class="table table-bordered table-bordered-block-order-detail order-history table-payment-recap">
                        		        <thead>
                        					<tr>
                        						<th class="first_item" width="60">#</th>
                        						<th class="item" width="170"><?php print $weblangs->trans("date"); ?></th>
                        						<th class="item" width="170"><?php print $weblangs->trans("Ref"); ?></th>
                        						<th class="item"><?php print $weblangs->trans("AmountHT"); ?></th>
                        						<th class="item"><?php print $weblangs->trans("AmountTTC"); ?></th>
                        					</tr>
                        				</thead>
                        				<tbody>
                        				    <?php
                                            /*$payment_history = "SELECT f.rowid, f.ref, f.fk_statut, f.fk_soc, f.datec, f.datef, f.date_closing, f.total_ht , f.total_ttc ";
                                            $payment_history .= "FROM ".MAIN_DB_PREFIX."facture_fourn as f ";
                                            $payment_history .= "WHERE f.fk_soc = " . ((int) $customer_id) . " and f.fk_statut = 2 and f.paye = 1 AND (f.libelle LIKE '%vente%' OR f.libelle LIKE '%dolistore%') ORDER BY f.datef DESC";*/
                        				    if ($dolistoreinvoices) {
                        				        $i = 1;
                        				        $total_ht = 0;
                                                $total_ttc = 0;
                        				        foreach ($dolistoreinvoices as $payment) {
                        				            $tmpdate=preg_replace('/(\s|T)00:00:00Z/','',$payment['date']);
                        				            if (strcmp($tmpdate ,'2013-01-01') < 0) $payment['amount_ht']=$payment['amount_ttc'];
                        				            $total_ht += $payment['amount_ht'];
                                                    $total_ttc += $payment['amount_ttc'];
                        				    ?>
                                		        <tr>
                                		            <td><?php print $i; ?></td>
                                		            <td><?php print dol_print_date($tmpdate); ?></td>
                                		            <td><?php print $payment['ref_supplier']; ?><!-- <?php print $payment['ref']; ?> --></td>
                                		            <td><?php print price($payment['amount_ht']); ?> €</td>
                                		            <td><?php print price($payment['amount_ttc']); ?> €</td>
                                		        </tr>
                            		        <?php
                        					    $i++;
                                            	}
                                            	?>
                                            	<tr>
                                                    <td colspan="3"><strong><?php print $weblangs->trans("AmountTotal"); ?></strong></td>
                                                    <td><strong><?php print price($total_ht); ?> €</strong></td>
                                                    <td><strong><?php print price($total_ttc); ?> €</strong></td>
                                                </tr>
                                            <?php
                                            }
                                            ?>
                                        </tbody>
            
                        		    </table>
                                </div>
                        		    
                        		    
                        		    
                        		    
                        		    
                        		    
                        		    
                        		</div>
                            </div>
                    </div>
                <?php endif ?>
                <ul class="footer_links clearfix">
                    	<li>
                    		<a class="btn btn-default button button-small" href="myaccount.php">
                    			<span>
                    				<i class="icon-chevron-left"></i> <?php print $weblangs->trans("backToYourAccount"); ?>
                    			</span>
                    		</a>
                    	</li>
                    	<li>
                    		<a class="btn btn-default button button-small" href="index.php">
                    			<span><i class="icon-chevron-left"></i> <?php print $weblangs->trans("Home"); ?></span>
                    		</a>
                    	</li>
                    </ul>
            </div>
        </div>
      </div>
    </div>
  </div>
  <!-- .columns-container -->
  <div class="footer-container">
    <?php includeContainer('footer'); ?>
  </div>
</div>