<?php // BEGIN PHP

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

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

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";
include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
include_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';


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

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

// Check if all necessary parameters are passed.
if (empty($order_ref)) {
	redirectToContainer('404');
    exit;
}

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

// 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) {
	    
        $customer_id = GETPOST('id_customer');
	}
}

// Check if there is a paid order for this customer with the sent information.
$sql_find_order = "SELECT c.rowid, c.ref, c.fk_statut, c.fk_soc, c.date_creation, c.module_source ";
$sql_find_order .= "FROM ".MAIN_DB_PREFIX."commande as c ";
$sql_find_order .= "WHERE c.fk_soc = " . $customer_id . " and c.ref = '" . $order_ref . "' 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_order .= "limit 1";
$find_order = $db->query($sql_find_order);
$obj_order = $db->fetch_object($find_order);

if (empty($obj_order)) {
    redirectToContainer('404');
} else {
    // Get order object
    $order_ref = $obj_order->ref;
    $order_object = new Commande($db);
    $result = $order_object->fetch('', $order_ref);
    if ($result < 0) {
    	redirectToContainer('404');
    }
    
    // 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;
        }*/
        
        // 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 = " . $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;
        
        
        // Generate invoice PDF (share it)
        $sql_invoice_pdf = "select lef.rowid as invoice_pdf_id ";
        $sql_invoice_pdf .= "from ".MAIN_DB_PREFIX."ecm_files lef ";
        $sql_invoice_pdf .= "where lef.src_object_type = 'facture' and lef.src_object_id = " . $invoice_object->id ;

        $find_invoice_pdf = $db->query($sql_invoice_pdf);
        $obj_invoice_pdf = $db->fetch_object($find_invoice_pdf);
        $invoice_pdf_id = $obj_invoice_pdf->invoice_pdf_id;

        $ecmfile = new EcmFiles($db);
    	$result = $ecmfile->fetch($invoice_pdf_id);
    	if ($result > 0 && empty($ecmfile->share)) {
    		$ecmfile->share = getRandomPassword(true);
    		$result = $ecmfile->update($user);
    		if ($result < 0) {
    			setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
    		}
    	}
    	$invoice_pdf_link = DOL_URL_ROOT . "/document.php?hashp=" . $ecmfile->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;
		        
		        // 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_object = null;
    }
}


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

  <div class="columns-container">
    <div id="columns" class="container">
        <!--  Breadcrumb  -->
        <div class="breadcrumb clearfix">
        	<a class="home" href="index.php" title="<?php print $weblangs->trans("backHome"); ?>"><i class="icon-home"></i></a>
        	<span class="navigation-pipe">&gt;</span> <a href="order-history.php" title="<?php print $weblangs->trans("orderHistory"); ?>" data-gg=""><?php print $weblangs->trans("orderHistory"); ?></a>
        	<span class="navigation-pipe">&gt;</span> <?php print $weblangs->trans("orderDetails"); ?>
        </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">
          <div class="clearfix">
                <h1 class="page-heading"><?php print $weblangs->trans("orderDetails"); ?></h1>
                <div id="block-history" class="block-center">
                    <div id="block-order-detail" class="unvisible" style="display: block;">
                    	<div class="info-order box">
                    	    <p class="dark">
                				<?php print $weblangs->trans("orderReference"); ?> <strong><?php print $order_object->ref; ?></strong> - <?php print $weblangs->trans("placedOn"); ?> <strong><?php print dol_print_date($order_object->date, 'day'); ?></strong>
                				<span style="background-color:#DDEEFF; border-color:#DDEEFF;padding: 4px 10px;float:right;" class="label dark"><?php print $weblangs->trans("paymentAccepted"); ?></span>
                			</p>
                			<?php if (!empty($invoice_ref)): ?>
                    			<p class="dark">
                    				<?php print $weblangs->trans("invoiceRef"); ?> <strong><?php print $invoice_ref; ?></strong>
                    			</p>
                			<?php endif ?>
                    		<p><strong class="dark"><?php print $weblangs->trans("paymentMethod"); ?> : </strong> <span class="color-myaccount"><?php print $payment_method; ?></span></p>
                    		<p class="download_invoice">
                    			<i class="icon-file-text"></i>
                    			<?php
                    			    if ($invoice_object === null) {
                    			        print $weblangs->trans("ifYouNeedAnInvoice", "https://wwwold.dolistore.com", "wwwold.dolistore.com");
                    			    } else{ ?>
                    			        <a target="_blank" href="<?php print $invoice_pdf_link; ?>"><?php print $weblangs->trans("downloadInvoicePDF"); ?></a>
                    			    <?php } 
                    			?>
                    			<?php if (!empty ($linked_credits) && count($linked_credits) > 0): ?>
                    			    <hr>
                    			    <?php
                    			        // Prepare list of credit notes to be used after
                    			        $credit_note_refs = array();
                                        foreach ($linked_credits as $key => $linked_credit) {
                                            $credit_note_refs[] = $linked_credit['ref'];
                                        }
                                        $credit_note_refs_placeholder = implode(',', array_map(function($ref) use ($db) {
                                            return "'" . $db->escape($ref) . "'";
                                        }, $credit_note_refs));
                    			    ?>
                        		    <?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>
                                		</p>
									<?php endforeach ?>
                        		<?php endif ?>
                    		</p>
                    	</div>
                    
                        <!--
                    	<div class="adresses_bloc">
                    		<div class="row">
                    			<div class="col-xs-12 col-sm-6">
                    				<ul class="address item full_width box">
                    					<li>
                    						<h3 class="page-subheading"><?php print $weblangs->trans("invoiceAddress"); ?></h3>
                    					</li>
                    					<li><span class="address_firstname"><?php print $customer->name; ?></span></li>
                    					<li><span class="address_address1"><?php print $customer->address; ?></span></li>
                    					<li><span class="address_Country:name"><?php print $customer->country; ?></span></li>
                    					<li><span class="address_phone"></span></li>
                    				</ul>
                    			</div>
                    		</div>
                    	</div>
                        -->
                        
                    	<form action="" method="post">
                    		<div id="order-detail-content" class="table_block table-responsive">
                    			<table class="table table-bordered table-bordered-block-order-detail">
                    				<thead>
                    					<tr>
                    						<th class="first_item"><?php print $weblangs->trans("product"); ?></th>
                    						<th class="item"><?php print $weblangs->trans("download"); ?></th>
                    						<th class="item"><?php print $weblangs->trans("Quantity"); ?></th>
                    						<th class="item"><?php print $weblangs->trans("unitPrice"); ?></th>
                    						<th class="last_item"><?php print $weblangs->trans("totalPrice"); ?></th>
                    					</tr>
                    				</thead>
                    				<tfoot>
                    					<tr class="item">
                    						<td colspan="1">
                    							<strong> <?php print $weblangs->trans("TotalHT"); ?> </strong>
                    						</td>
                    						<td colspan="4">
                    							<span class="price"><?php print price($order_object->total_ht); ?> €</span></span>
                    						</td>
                    					</tr>
                    					<tr class="totalprice item">
                    						<td colspan="1">
                    							<strong><?php print $weblangs->trans("TotalTTC"); ?></strong>
                    						</td>
                    						<td colspan="4">
                    							<span class="price"><?php print price($order_object->total_ttc); ?> €</span></span>
                    						</td>
                    					</tr>
                    				</tfoot>
                    				<tbody>
                    					<!-- Customized products -->
                    					<!-- Classic products -->
                    					<?php $lines = $order_object->lines; ?>
                    					<?php foreach ($lines as $line): ?>
                    					    <?php
                                                $product = new Product($db);
                                                $ret = $product->fetch($line->fk_product);
                                            ?>
                        					<tr class="item">
                        						<td class="cart_description">
    												<p class="product-name"><a target="_blank" href="product.php?id=<?php print $product->id; ?>"><?php print $line->desc; ?> <i class="icon-external-link"></i></a></p>
    												<small class="cart_ref"><?php print $weblangs->trans("Ref"); ?> : <?php print $product->ref; ?></small>
    											</td>
    											<td class="download_icon">
                        						    <?php 
                        						        // Get attached file
        												$files = getPublicFilesOfObject($product);
        												
        												$url_attached_file = '';
        												foreach ($files as $file) {
                                                            if ($file['position'] == 100) {     // TODO If we change position, this detection is broken. We should take the last file.
                                                                $url_attached_file = $file['url'];
                                                            }
                                                        }

                                                        // Check Link Validity
                                                        $now = dol_now();
                                                        $one_year_ago = dol_time_plus_duree($now, -1, 'y');
                                                        $isValidLink = 1;
                                                        if ($order_object->date < $one_year_ago) {
                                                            $isValidLink = 0;
                                                            $unvalidlinkmessage= $weblangs->trans("invalidLink");
                                                        }

                                                        // Check refund qty
                                            		    if (!empty($credit_note_refs) && is_array($credit_note_refs) && count($credit_note_refs) > 0) {
                                        		            $sum_qty_returned = "SELECT SUM(fd.qty) AS return_qty ";
                                                            $sum_qty_returned .= "FROM " . MAIN_DB_PREFIX . "facture AS f, " . MAIN_DB_PREFIX . "facturedet AS fd ";
                                                            $sum_qty_returned .= "WHERE f.rowid = fd.fk_facture ";
                                                            $sum_qty_returned .= "AND fd.fk_product = " . ((int) $line->fk_product) . " ";
                                                            $sum_qty_returned .= "AND f.ref IN (" . $credit_note_refs_placeholder . ")";
                                                            //print $sum_qty_returned;exit;
                                                            
                                                            $resql = $db->query($sum_qty_returned);
                                                            if ($resql) {
                                                                $row = $db->fetch_object($resql);
                                                                $total_return_qty = $row->return_qty ?? 0;
                                                            }
                                                            
                                                            if (($line->qty - $total_return_qty) < 1) {
                                                                $isValidLink = 0;
                                                                $unvalidlinkmessage= "-";
                                                            }
                                                        }
                                                        
    												?>
    												<?php if ($isValidLink == 1) { ?>
    												    <p><a target="_blank" href="_service_download.php?t=paied&r=<?php print $order_object->ref; ?>&p=<?php print $line->fk_product; ?>&u=<?php print $user_id; ?>">
    												        <i class="icon-cloud-download small"></i> <?php echo $weblangs->trans("Download"); ?>
    												    </a></p>
    												    <!--<p><a target="_blank" href="<?php //print $url_attached_file; ?>"><i class="icon-cloud-download"></i></a></p>-->
    												<?php } else { ?>
    												    <p><?php print $unvalidlinkmessage; ?> </p>
    												<?php } ?>
    											</td>
                        						<td class="return_quantity right">
                        							<span class="order_qte_span"><?php print $line->qty; ?></span>
                                            		    
                                            		<?php if (!empty($total_return_qty)) { ?>
                                            		    <span class="order_qte_span" style="color:red;">(<?php print $total_return_qty . " " . $weblangs->trans("Refunded"); ?>)</span>
                                            		<?php } ?>
                        						</td>
                        						<td class="right">
                        						    <?php print price($line->price); ?> €</span>
                        						</td>
                        						<td class="right">
                        							<?php print price($line->total_ttc); ?> €</span>
                        						</td>
                        					</tr>
                    					<?php endforeach ?>
                    					
                    				</tbody>
                    			</table>
                    		</div>
                    	</form>
                    </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>
        </div>
      </div>
    </div>
  </div>
  <!-- .columns-container -->
  <div class="footer-container">
    <?php includeContainer('footer'); ?>
  </div>
</div>