<?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 = GETPOST('cat', 'alpha');
$search = GETPOST('search_query', 'alpha');
$current_lang = $_SESSION['lang']['code'];
$weblangs->load("products");


// 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 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);
    $idcategoryoftheboardteam = getDolGlobalInt('MARKETPLACE_MEMBER_CATEGORY_ADMIN_ID');
	$adminsCat->fetch($idcategoryoftheboardteam);
	
	$result = $adminsCat->containsObject('member', $membre->id);
	if ($result > 0) {
	    $isAdmin = true;
	    
        $customer_id = GETPOSTINT('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 liste of products
$products_ids = array();

$sql = 'SELECT pf.fk_product, MIN(pf.datec) AS first_date ';
$sql .= 'FROM '.MAIN_DB_PREFIX.'product_fournisseur_price AS pf, '.MAIN_DB_PREFIX.'categorie_product AS cp ';
$sql .= 'WHERE pf.fk_soc = '.((int) $customer_id).' ';
$sql .= 'AND cp.fk_product = pf.fk_product ';
$sql .= 'AND cp.fk_categorie = '.getDolGlobalInt("MARKETPLACE_ROOT_CATEGORY_ID").' ';
$sql .= 'GROUP BY pf.fk_product ';
$sql .= 'ORDER BY first_date ASC';

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

// END PHP 
?>
<div id="page">
  <div class="header-container">
    <?php 
        includeContainer('header'); 
        $__PAGE__TITLE__ = $weblangs->trans("manageProductsPageTitle");
    ?>
  </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("manageProducts"); ?></a>
        	<span class="navigation-pipe">&gt;</span> <?php print $weblangs->trans("ListOfProductsServices"); ?>
        </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)): ?>
                <h1 class="page-heading"><?php print $weblangs->trans("ListOfProductsServices"); ?></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("ListOfProductsServices"); ?></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="item"><?php print $weblangs->trans("coverImage"); ?></th>
                    						<th class="item"><?php print $weblangs->trans("product"); ?></th>
                    						<th class="item"><?php print $weblangs->trans("Nb"); ?></th>
                    						<th class="item" width="80"><?php print $weblangs->trans("amountEarned"); ?></th>
                    						<th class="last_item"></th>
                    					</tr>
                    				</thead>
                    				<tbody>
                    					<!-- Customized products -->
                    					<!-- Classic products -->
                    					<?php foreach ($products_ids as $products_id): ?>
                    					    <?php
                    					        $weblangs->load("products");
                                                // Get order object
                                                $product = new Product($db);
                                                $result = $product->fetch($products_id);
                                                
                                                // Get nbr of sales
                                                $sql = "SELECT sum(d.qty) as qty, sum(d.total_ht) as total_ht";
                                        		$sql .= " FROM ".$db->prefix()."commandedet as d, ".$db->prefix()."commande as c, ".$db->prefix()."societe as s";
                                        		$sql .= " WHERE c.rowid = d.fk_commande";
                                        		$sql .= " AND d.fk_product = ".((int) $product->id);
                                        		$sql .= " AND c.fk_soc = s.rowid";
                                        		$sql .= " AND c.module_source = 'marketplace'";
                                        		$sql .= " AND (c.facture = 1 OR c.pos_source = '2161031@prestashop')";  // Filter on c.pos_source is to take old imported record

                                        		$resql = $db->query($sql);
    		                                    $stats = $db->fetch_object($resql);
    		                                    
    		                                    // Calculate refunded products
    		                                    $refunded_sql = "SELECT SUM(fd.qty) AS refund_qty, sum(fd.total_ht) as refund_total_ht ";
                                                $refunded_sql .= " FROM " . MAIN_DB_PREFIX . "facture AS f, " . MAIN_DB_PREFIX . "facturedet AS fd ";
                                                $refunded_sql .= " WHERE f.rowid = fd.fk_facture ";
                                                $refunded_sql .= " AND fd.fk_product = " . ((int) $product->id) . " ";
                                                $refunded_sql .= " AND f.type = 2 AND f.paye = 1";
                                                //print $refunded_sql;
                                                
                                                $resql = $db->query($refunded_sql);
                                                if ($resql) {
                                                    $row = $db->fetch_object($resql);
                                                    $refund_qty = $row->refund_qty ?? 0;
                                                    $refund_total_ht = $row->refund_total_ht ?? 0;
                                                }
    		                                    
    		                                    // Calculate all discounts for this product
                                                $TOTAL_DISCOUNTS = 0;
                                                $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 c.module_source = 'marketplace' ";
                                                $sum_all_discounts .= "AND d.description LIKE '" . ((int) $product->id) . "# %' ";
                                                $sum_all_discounts .= "AND (c.facture = 1 OR c.pos_source = '2161031@prestashop' OR c.ref_ext IS NOT NULL) ";  // Filter on c.pos_source is to take old imported record
                                                $resql = $db->query($sum_all_discounts);
                                                $sells_discounts = $db->fetch_object($resql);
                                                $TOTAL_DISCOUNTS = $sells_discounts->total;
    		                                    
    		                                    // Get package
    		                                    $files_and_images = getPublicFilesOfObject($product);
            			                        foreach ($files_and_images as $key => $file) {
                                                    if ($file['position'] == 100) {
                                                        $virtual_product_file = $file;
                                                    }
                                                }
                                            ?>
                        					<tr class="item">
                        					    <td>
                        					        <img class="img-responsive" src="<?php print getImagePublicURLOfObject($product, 0, '_small'); ?>" alt="<?php print $product->label; ?>" title="<?php print $product->label; ?>" width="160" itemprop="image" style="margin: auto;" />
                        					    </td>
                        					    <td>
                        						    <p>
                        						        <b><?php print $product->label; ?> <?php print $product->array_options['options_marketplace_module_version']; ?> </b> 
                        						        
                        						        <small class="opacitymedium"> (<?php print $product->array_options['options_marketplace_min_version']; ?> - <?php print $product->array_options['options_marketplace_max_version']; ?>)</small>
                        						    </p>
                        						    <p>
                        						        <small class="cart_ref">
                        						            <?php print $product->description; ?><br><br>
                        						            <?php print $weblangs->trans("CurrentProductPrice"); ?>: <b><?php print price($product->price); ?> €</b>
                        						            <?php print $weblangs->trans("exclTax"); ?>
                        						            <!-- &nbsp; - &nbsp; <?php print price($product->price_ttc); ?> € <?php print $weblangs->trans("inclTax"); ?> -->
                        						            <br>
                                                            <?php print $weblangs->trans("Ref"); ?>: <?php print $product->ref; ?><br>
                                                            <?php print $weblangs->trans("Status"); ?>: <?php 
                                                                if ($product->status > 0) {
                                                                    print '<span style="color: #28a745;">'.$langs->trans("Enabled").'</span>';
                                                                } else {
                                                                    print '<span style="color: #dc3545;">'.$langs->trans("Disabled").'</span>';
                                                                    print '<span class="opacitymedium"> - '.$product->array_options['options_marketplace_reason_disabled'].'</span>';
                                                                }
                                                            ?><br>
                                                            <?php if (!empty($virtual_product_file['url'])) { ?>
                                                                <?php print $weblangs->trans("File"); ?>: <a href="<?php print $virtual_product_file['url']; ?>" target="_new" ><?php print $virtual_product_file['filename']; ?> <i class="icon-cloud-download"></i></a><br>
                                                            <?php } ?>
                                                            <?php print $weblangs->trans("DateCreation"); ?>: <?php print dol_print_date($product->date_creation, 'day'); ?> - <?php print $weblangs->trans("DateModification"); ?>: <?php print dol_print_date($product->date_modification, 'day'); ?><br>
                       						        </small>
                        						    </p>
                        						</td>
                        						<td>
                        						        <?php print $stats->qty; ?>
                        						        <?php if (!empty($refund_qty)) { ?>
                        						            <br>
                                                		    <span style="color:red;font-size:12px;">-<?php print $refund_qty . " " . $weblangs->trans("Refunded"); ?></span>
                                                		<?php } ?>
    											</td>
                        						<td class="nowraponall right">
                        							    <span class="price"><?php print price($stats->total_ht + $TOTAL_DISCOUNTS); ?> €</span>
                        							    <?php if (!empty($refund_total_ht)) { ?>
                        						            <br>
                                                		    <span style="color:red;font-size:12px;display: contents;"><?php print price($refund_total_ht)  . " € " . $weblangs->trans("Refunded"); ?></span>
                                                		<?php } ?>
                        						</td>
                        						<td class="btn-table">
                        						    <a href="edit-module-product.php?id=<?php print $product->id; ?>" class="btn btn-default button button-small"><span title="<?php print $weblangs->trans("edit"); ?>"> 
                        						    <i class="icon-edit product-table-icons" style="width:18px"></i></span></a>
                        						    <br><br>
                        						    <a href="product-statistics.php?id=<?php print $product->id; ?>" class="btn btn-default button button-small"><span title="<?php print $weblangs->trans("listOfSells"); ?>"> 
                        						    <i class="icon-shopping-cart product-table-icons" style="width:18px"></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>