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

if (empty($_SESSION['user']['id_user'])) {
    $login_page_url = "index.php?website=".$website->ref."&pageref=login-register&back=payement";
    header("Location:".$login_page_url);
    exit;
}
                        
$tag = GETPOST('tag', 'alpha');
$cat_id = GETPOST('cat', 'alpha');
$search = GETPOST('search_query', 'alpha');
?>

<div id="page">
	<div class="header-container">
		<?php
		    includeContainer('header');
		    $__PAGE__TITLE__ = $weblangs->trans("paymentPageTitle");
		?>
	</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> <?php print $weblangs->trans("yourShoppingCart"); ?>
			</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">

                        <?php
                            if(!empty($_SESSION['products'])){
                                
                                include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
                                require_once DOL_DOCUMENT_ROOT."/commande/class/commande.class.php";

                                // Load user and its permissions
                                $result = $user->fetch('', 'admin');	// Load user for login 'admin'. Comment line to run as anonymous user.
                                if (!$result > 0) {
                                	dol_print_error(null, $user->error);
                                	exit;
                                }
                                $user->getrights();
                                
                                $user_id = $_SESSION['user']['id_user'];
                                $customer = new SocieteAccount($db);
                                $result = $customer->fetch($user_id);
                                $customer_id = $customer->fk_soc;
                                if (empty($customer_id)) {
                                	dol_print_error(null, $customer->error);
                                	exit;
                                }
                                
                                $com = new Commande($db);
                            
                                $com->socid          = $customer_id;
                                $com->date           = dol_now();
                                $com->note_private   = 'Order from the marketplace';
                                $com->module_source  = 'marketplace';
                                $com->pos_source	 = dol_getmypid() . "@" . $website->id;
                                $com->remise_percent = 0;
                                
                                $db->begin();
                                
                                // Check if there is an existing open order for this thirdparty.
                                $sql_find_order = "SELECT c.rowid, 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 = " . ((int) $customer_id) . " and c.fk_statut= 1 and c.facture = 0 and c.ref_ext is null "; // ignore billed orders and imported orders
                                $sql_find_order .= "AND c.date_commande >= DATE_SUB(NOW(), INTERVAL 30 DAY) and c.module_source = 'marketplace' ";  // ignore too old open orders
                                $sql_find_order .= "ORDER BY c.date_creation DESC ";
                                $sql_find_order .= "LIMIT 1";
                                
                                $find_order = $db->query($sql_find_order);
                                $obj_order = $db->fetch_object($find_order);
                                
                                // If there is an order, update the current unpaid order lines by SESSION articles.
                                if (!empty($obj_order)) {
                                    $com->fetch($obj_order->rowid);
                                    
                                    //$com->fetch_lines();      // the fetch_lines is already included into the fetch
                                    
                                    $lines = $com->lines;
                                    
                                    $com->setDraft($user);      // ensure order is set back to draft status
                                    
                                    // remove current order lines 
                                    foreach ($lines as $line){
                                        $ree = $com->deleteLine($user, $line->id);
                                        //print $com->error . '<br>';
                                    }

                                    $result = $com->id;
                                } else {
                                    $result = $com->create($user);
                                }
                                
                                if ($result >= 0) {
                                    // Loop on each product into session and add it into the order
                                    foreach ($_SESSION['products'] as $session_product) {
                                        // Get  product
                                        $product = new Product($db);
                                        $result = $product->fetch($session_product['product_id']);
                                        if (!$result > 0) {
                                        	dol_print_error($db, $product->error);
                                        	exit;
                                        }
                                        
                                		// Get buyer
                                	    $thirdparty_buyer = new Societe($db);
                                        $result = $thirdparty_buyer->fetch($customer_id);
                                        if (!$result > 0) {
                                        	dol_print_error($db, $thirdparty_buyer->error);
                                        	exit;
                                        }

                                        // Get seller
                                        $sql_get_seller_id = "select lpfp.rowid, lpfp.fk_soc 
                                            from ".MAIN_DB_PREFIX."product_fournisseur_price lpfp 
                                            where lpfp.fk_product = " .((int) $session_product['product_id']) . " LIMIT 1"; // we hope to have only one supplier for each product
                                        $resql = $db->query($sql_get_seller_id);
                                		$objsql = $db->fetch_object($resql);
                                		
                                		if (!empty($objsql->fk_soc)) {
                                		    $thirdparty_seller = new Societe($db);
                                            $thirdparty_seller->fetch($objsql->fk_soc);

                                            //$tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $product->id, $objsql->rowid);   // it seems tha vat rate of supplier price not always correctly defined, so we redo the generic code
                                            $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $product->id);
                                		} else {
                                		    // To complete with default third party if no price/no seller was found for product ?

                                            $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $product->id);
                                		}
                                        
                                        // Check discount
                            			$discount = marketplace_check_discount($product->id);
                            			$discount_percent = ($discount['mode'] === 'percent') ? $discount['value'] : 0;
                                        
                                        $result = $com->addline($product->label, $product->price, $session_product['product_qty'], $tva_tx, 0, 0, $product->id, $discount_percent, 0, 0, $product->price_base_type, $product->price_ttc, '', '', $product->type);
                            			if ($result <= 0) {
                            				dol_print_error($db, $product->error);
                            				exit;
                            			}
                            			
                            			// TODO
                    					if ($discount['mode'] === 'amount' && $discount['value'] > 0) {
                                            // Add amount discount
                    					}

                                    } 
                                    
                                    $com->set_date($user, dol_now(), 1);
                                    
                                    $result = $com->valid($user);
                                    
                            		if ($result > 0) {
                            			$db->commit();
                                        $order_is_created = '1';
                                        $order_id = $com->id;
                            		} else {
                            			$db->rollback();
                            			dol_print_error($db, $com->error);
                            		}
                            	} else {
                            		$db->rollback();
                            		dol_print_error($db, $com->error);
                            	}
                            }
                            
        
                            if (isset($order_is_created)){
                                $commande = new Commande($db);
                                $ret = $commande->fetch($order_id);
                                
                                //$commande->fetch_lines();     // already included into the fetch()
                                
                                $lines = $commande->lines;
                            }
                        ?>

						<h1 class="page-heading"><?php print $weblangs->trans("cartSummary"); ?>
    						<span class="heading-counter"><?php print $weblangs->trans("yourCartContains"); ?>:
        						<?php if (isset($lines)): ?>
                                    <span class="ajax_cart_no_product"><?php print count($lines); ?></span> <?php if(count($lines) > 1){ print $weblangs->trans("products");}else{ print $weblangs->trans("product");} ?>
                                <?php else: ?>
                                    <span id="ajax_cart_no_product">0</span> <?php print $weblangs->trans("product"); ?>
                                <?php endif ?>
    						</span>
						</h1>
						<?php if (!$_SESSION['products'] || !isset($order_is_created)): ?>
                            <?php if (!$_SESSION['products']): ?>
                                <p class="alert alert-warning"><?php print $weblangs->trans("cartIsEmpty"); ?></p>
                            <?php endif ?>
                            <?php if (!isset($order_is_created)): ?>
                                <p class="alert alert-warning"><?php print $weblangs->trans("errorOccurred"); ?> </p>
                            <?php endif ?>
                        <?php else: ?>
							<div id="order-detail-content" class="table_block table-responsive">
								<table id="cart_summary" class="table table-bordered stock-management-off">
									<thead>
										<tr>
											<th class="cart_product first_item"><?php print $weblangs->trans("product"); ?></th>
											<th class="cart_description item"><?php print $weblangs->trans("Description"); ?></th>
											<th class="cart_unit item text-center"><?php print $weblangs->trans("UnitPriceHT"); ?></th>
											<th class="cart_quantity item text-center"><?php print $weblangs->trans("Quantity"); ?></th>
											<th class="cart_total item cart_total_payment"><?php print $weblangs->trans("TotalTTC"); ?></th>
										</tr>
									</thead>
									
									<tbody>
                                        <?php $total = 0; ?>
                                        
                                        <?php foreach ($lines as $line): ?>
                                            <?php
                                                $product = new Product($db);
                                                $ret = $product->fetch($line->fk_product);
                                            ?>
                                            <tr id="product_<?php print $product->id; ?>" class="cart_item">
    											<td class="cart_product">
    												<a href="product.php?id=<?php print $product->id; ?>"><img src="<?php print getImagePublicURLOfObject($product,1);; ?>" id="product_img_<?php print $product->id; ?>" alt="<?php print $product->name; ?>" width="98" height="98"></a>
    											</td>
    											<td class="cart_description">
    												<p class="product-name"><a href="product.php?id=<?php print $product->id; ?>"><?php print $line->desc; ?></a></p>
    												<small class="cart_ref"><?php print $weblangs->trans("sku"); ?> : <?php print $product->ref; ?></small>
    											</td>
    											<td class="cart_unit" data-title="Unit price">
    												<span class="price" id="product_price"><span class="price" id="product_price_<?php print $product->id; ?>"><?php print price($line->price); ?></span> €</span>
    											</td>
    
    											<td class="cart_quantity text-center">
                                                    <span class="text-center"><?php print $line->qty; ?></span>
    											</td>
    											<td class="cart_total cart_total_payment" data-title="Total">
    												<span class="price"><span class="total_line" id="total_product_price_<?php print $product->id; ?>"><?php print price($line->total_ttc); ?></span> €</span>
    											</td>
    										</tr>
                                        <?php endforeach ?>
                                    </tbody>
                                    
                                    <tfoot>
										<tr class="cart_total_price">
											<td rowspan="5" colspan="2" id="cart_voucher" class="cart_voucher">
											</td>
											<td colspan="2" class="text-right"><?php print $weblangs->trans("totalProductsTaxIncl"); ?></td>
											<td colspan="2" class="price" ><span id="total_product"><?php print price($commande->total_ttc); ?></span> €</td>
										</tr>
										<tr class="cart_total_delivery">
											<td colspan="2" class="text-right"><?php print $weblangs->trans("Shipping"); ?></td>
											<td colspan="2" class="price" id="total_shipping"><?php print $weblangs->trans("freeShipping"); ?></td>
										</tr>

										<tr class="cart_total_price">
											<td colspan="2" class="total_price_container text-right">
												<span><?php print $weblangs->trans("total"); ?></span>
											</td>
											<td colspan="2" class="price" id="total_price_container">
												<span><span id="total_price"><?php print price($commande->total_ttc); ?></span> €</span>
											</td>
										</tr>
									    </tfoot>
								</table>
							</div>
    						
    						<?php if (!getDolGlobalInt("MARKETPLACE_BLOCK_SALES") || in_array($_SESSION['user']['id_user'], array_map('trim', explode(',', getDolGlobalString("MARKETPLACE_ADMIN_USER_IDS"))))): ?>
    							<div id="HOOK_PAYMENT">
    							    <?php $current_lang = $_SESSION['lang']['code']; ?>
    							    <?php 
        							    require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
        							    $urlforframe = getOnlinePaymentUrl(0, 'order', $commande->ref, 0, '', $website->virtualhost);
    							    ?>
        				            <iframe frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%" src="<?php print $urlforframe ?>&ws=<?php print $website->ref; ?>&lang=<?php print $current_lang; ?>&paymentmethod=stripe"></iframe>
    							</div>
    							
    							<br>
    							
    							<a href="/" class="button-exclusive btn btn-default" title="<?php print $weblangs->trans("continueShopping"); ?>">
									<i class="icon-chevron-left"></i> <?php print $weblangs->trans("continueShopping"); ?>
								</a>
    						<?php else: ?>
    						    <div class="block-sells-notification">
                                    <?php print $weblangs->trans("marketplacePurchasesDisabled"); ?>
                                </div>
    						<?php endif ?>
    						
						<?php endif ?>
					</div>
				</div>
			</div>
		</div>
	</div>
	<!-- .columns-container -->
	<div class="footer-container">
		<?php includeContainer('footer'); ?>
	</div>
</div>

