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

$tag = GETPOST('tag', 'alpha');
$cat_id = GETPOSTINT('cat');
$search = GETPOST('search_query', 'alpha');

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

$weblangs->load("bills");

// 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 customer ID.
$customer = new Societe($db);
$result = $customer->fetch($customer_id);

$isAdmin = false;

// To render 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) {
	    $isAdmin = true;

        $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 = ".((int) $customer_id)." AND fk_website = ".((int) $website->id)." limit 1";
        $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 all paid orders for this customer when module_source is Marketplace.
$sql_find_orders = "SELECT c.rowid, c.ref, c.fk_statut, c.fk_soc, c.date_creation, c.date_commande, c.date_valid, c.module_source ";
$sql_find_orders .= "FROM ".MAIN_DB_PREFIX."commande as c ";
$sql_find_orders .= "WHERE c.fk_soc = " . ((int) $customer_id) . " and ( c.fk_statut= 1 or c.fk_statut= -1 ) and (c.facture = 1 || c.ref_ext IS NOT NULL) and c.module_source = 'Marketplace' ";
$sql_find_orders .= "ORDER BY c.date_commande desc ";
$resql = $db->query($sql_find_orders);
if ($resql) {
    $orders_id = array();
	while ($obj = $db->fetch_object($resql)) {
	    $orders_id[] = $obj->rowid;
	}
}/* else {
	print $weblangs->trans("noOrderFounded");
	exit();
}*/

// END PHP 
?>
<div id="page">
  <div class="header-container">
    <?php 
        includeContainer('header');
        $__PAGE__TITLE__ = $weblangs->trans("orderHistoryPageTitle");
    ?>
  </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("orderHistory"); ?>
        </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($orders_id)): ?>
                <h1 class="page-heading"><?php print $weblangs->trans("orderHistory"); ?></h1>
                <p class="alert alert-warning"><?php print $weblangs->trans("noOrderFounded"); ?> </p>
            <?php else: ?>
              <div class="clearfix">
                    <h1 class="page-heading"><?php print $weblangs->trans("orderHistory"); ?></h1>
                    <div id="block-history" class="block-center">
                        <div id="block-order-detail" class="unvisible" style="display: block;">
                    		<div id="order-detail-content" class="table_block table-responsive">
                    			<table class="table table-bordered table-bordered-block-order-detail order-history">
                    				<thead>
                    					<tr>
                    						<th class="first_item"><?php print $weblangs->trans("orderRef"); ?></th>
                    						<th class="item"><?php print $weblangs->trans("products"); ?></th>
                    						<th class="item"><?php print $weblangs->trans("Date"); ?></th>
                    						<th class="item"><?php print $weblangs->trans("totalPrice"); ?></th>
                    						<th class="item" width="80"><?php print $weblangs->trans("paymentMethod"); ?></th>
                    						<th class="item"><?php print $weblangs->trans("Invoice"); ?></th>
                    						<th class="last_item"><?php print $weblangs->trans("details"); ?></th>
                    					</tr>
                    				</thead>
                    				<tbody>
                    					<!-- Customized products -->
                    					<!-- Classic products -->
                    					<?php foreach ($orders_id as $order_id): ?>
                    					    <?php
                                                // Get order object
                                                $order_object = new Commande($db);
                                                $result = $order_object->fetch($order_id);
                                                
                                                // Get invoice object
                                                $order_object->fetchObjectLinked();
                                                if (!empty($order_object->linkedObjects['facture'])) {
    												$linked_invoices = $order_object->linkedObjects['facture'];
                                                    /*$last_invoice_object = $linked_invoices[reset(array_keys($linked_invoices))];
    
                                                    if ($last_invoice_object instanceof Facture) {
                                                        $invoice_object = $last_invoice_object;
                                                        print $invoice_object->ref;
                                                    }*/
                                                    
                                                    // Extract only regular invoices 
                                                    $regular_invoices = array_filter($linked_invoices, function ($invoice) {
                                                        return ($invoice instanceof Facture) && ($invoice->type == 0);
                                                    });
                                                
                                                    // Get first regular invoice if exist
                                                    if (!empty($regular_invoices)) {
                                                        $first_regular_invoice = reset($regular_invoices);
                                                        $invoice_object = $first_regular_invoice;
                                                    }
    
    												// Get payment details
    												$sql_payment_details = "SELECT c.libelle AS payment_method ";
    												$sql_payment_details .= "FROM ";
    												$sql_payment_details .= "".MAIN_DB_PREFIX."paiement_facture AS pf ";
    												$sql_payment_details .= "JOIN ".MAIN_DB_PREFIX."paiement AS p ON pf.fk_paiement = p.rowid ";
    												$sql_payment_details .= "LEFT JOIN ".MAIN_DB_PREFIX."c_paiement AS c ON p.fk_paiement = c.id ";
    												$sql_payment_details .= "WHERE ";
    												$sql_payment_details .= "pf.fk_facture = " . ((int) $invoice_object->id);
    												
    												$invoice_ref = $invoice_object->ref;
    												
    												$find_payment_details = $db->query($sql_payment_details);
    												$obj_payment = $db->fetch_object($find_payment_details);
    												$payment_method = $obj_payment->payment_method;
    
    												// Get invoice PDF
    												$sql_invoice_pdf = "select lef.rowid, lef.share ";
    												$sql_invoice_pdf .= "from ".MAIN_DB_PREFIX."ecm_files lef ";
    												$sql_invoice_pdf .= "where lef.src_object_type = 'facture' and lef.src_object_id = " . ((int) $invoice_object->id);
    
    												$find_invoice_pdf = $db->query($sql_invoice_pdf);
    												$obj_invoice_pdf = $db->fetch_object($find_invoice_pdf);
    												$invoice_pdf_link = DOL_URL_ROOT . "/document.php?hashp=" . urlencode($obj_invoice_pdf->share);
    												
    												// Looking for credit notes for the main invoice. It can be more then one
    												$linked_credits = array();
    												foreach ($linked_invoices as $linked_invoice) {
    												    if ($linked_invoice instanceof Facture && $linked_invoice->fk_facture_source == $invoice_object->id && $linked_invoice->type == Facture::TYPE_CREDIT_NOTE && $linked_invoice->paye == 1) {
    												        $linked_credits[$linked_invoice->id]['ref'] = $linked_invoice->ref;
    												        $linked_credits[$linked_invoice->id]['total_ttc'] = $linked_invoice->total_ttc;
    												        
    												        // Get credit note PDF
            												$sql_credit_pdf = "select lef.rowid, lef.share ";
            												$sql_credit_pdf .= "from ".MAIN_DB_PREFIX."ecm_files lef ";
            												$sql_credit_pdf .= "where lef.src_object_type = 'facture' and lef.src_object_id = " . $linked_invoice->id ;
            
            												$find_credit_pdf = $db->query($sql_credit_pdf);
            												$obj_credit_pdf = $db->fetch_object($find_credit_pdf);
            												$linked_credits[$linked_invoice->id]['pdf_link'] = DOL_URL_ROOT . "/document.php?hashp=" . $obj_credit_pdf->share;
    												    }
    												}
    
                                                } else {
    												$payment_method = "";
    												$invoice_pdf_link = "#";
    												$invoice_ref = "/";
                                                }
                                            ?>
                        					<tr class="item">
                        					    <td class="nowraponall center">
                        						    <span class="cart_ref"><?php print dolPrintHTML($order_object->ref); ?></span>
                        						</td>
                        						<td class="order-history">
                        						    <?php $order_lines = $order_object->lines; ?>
                        						    <ul class="order-history-products-list">
                        						    <?php foreach ($order_lines as $order_line): ?>
                        			                    <li><?php print $order_line->desc; ?></li>
    												<?php endforeach ?>
    												</ul>
    											</td>
                        						<td>
    												<p title="<?php print dol_print_date($order_object->date_commande, 'dayhour'); ?>"><?php print dol_print_date($order_object->date_commande, 'day'); ?></p>
    											</td>
                        						<td>
                        							<p><span class="price"><?php print price($order_object->total_ttc); ?> €</span></p>
                        						</td>
                        						<td>
                        						    <p><?php print $payment_method; ?></p>
                        						</td>
                        						<td class="nowraponall">
                        						    <?php if ($invoice_pdf_link != "#"): ?>
                            						    <p class="invoice-pdf-link">
                                                			<i class="icon-file-text"></i>
                                                			<a target="_blank" href="<?php print $invoice_pdf_link; ?>"> <?php print $invoice_ref; ?></a>
                                                		</p>
                                                		<?php if (count($linked_credits) > 0): ?>
                                                		    <?php foreach ($linked_credits as $linked_credit): ?>
                                			                    <p class="invoice-pdf-link">
                                                        			<i class="icon-file-text"></i>
                                                        			<a target="_blank" href="<?php print $linked_credit['pdf_link']; ?>"> <?php print $linked_credit['ref']; ?></a>
                                                        			<span style="font-size: 12px;">(<?php print price($linked_credit['total_ttc']); ?> €)</span>
                                                        		</p>
            												<?php endforeach ?>
                                                		<?php endif ?>
                                                	<?php endif ?>
                        						</td>
                        						<td class="btn-table">
                        						    <a href="order-details.php?ref=<?php print $order_object->ref; ?>" class="btn btn-default button button-small"><span><?php print $weblangs->trans("details"); ?> <i class="icon-chevron-right right"></i></span></a>
                        						</td>
                        					</tr>
                    					<?php endforeach ?>
                    				</tbody>
                    			</table>
                    		</div>
                        </div>
                    </div>
                    <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>
          
            <?php endif ?>
        </div>
      </div>
    </div>
  </div>
  <!-- .columns-container -->
  <div class="footer-container">
    <?php includeContainer('footer'); ?>
  </div>
</div>