<?php
/* Copyright (C) 2008-2011  Laurent Destailleur
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 * or see https://www.gnu.org/
 */

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

/*print '<pre>';
print_r($website);
print '</pre>';
exit;*/
//require "../../master.inc.php";
include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
include_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php';
include_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';
include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
includeContainer('_library_page_lib.php', 1);
setSessionLang();

$website_id = getDolGlobalInt("MARKETPLACE_WEBSITE_ID");

$weblangs->load("marketplace@marketplace");

$website_object = new Website($db);
$this_website = $website_object->fetch($website_id);
if (!defined('USEDOLIBARRSERVER')) {
	$order_page_url = "order.php";
} else {
	$order_page_url = "index.php?website=".$website->ref."&pageref=order";
}

$product_id = GETPOSTINT('product_id');
$product_thumb = GETPOST('product_thumb');
$product_qty = GETPOSTINT('product_quantity');


// Addition of a product into basket
if ($product_id && $product_qty) {

	$object = new Product($db);
	$get_product = $object->fetch($product_id);
	
	// TODO Check that the product is inside the category of marketplace + Check product is open to sales
	// ...
	
	// check discount and calculate discounted price
    $discount = marketplace_check_discount($object->id);
    $discounted_price = marketplace_calculate_discounted_price($object->price_ttc, $discount);
    
    if ($discounted_price != $object->price_ttc) {
        $price_to_display = $discounted_price;
    } else {
        $price_to_display = $object->price_ttc;
    }

    $new_product['product_id'] = $object->id;
    $new_product['product_thumb'] = $product_thumb;
    $new_product['product_name'] = $object->label;
    $new_product['product_ref'] = $object->ref;
    $new_product['product_price'] = $price_to_display;
    $new_product['product_qty'] = $product_qty;

    if (isset($_SESSION['products'])) {  //if session var already exist
        if (isset($_SESSION['products'][$new_product['product_id']])) { //check item exist in products array
            unset($_SESSION['products'][$new_product['product_id']]); //unset old item
        }
    }

    $_SESSION['products'][$new_product['product_id']] = $new_product;	//update products with new item array

    $total_items = count($_SESSION['products']); //count total items

    $popup_product_html = '
        <span class="cross" title="Close window"></span>
        <h2>
            <i class="icon-ok"></i>'.$weblangs->trans("ProductAddedSuccessfully").'
        </h2>
        <div class="product-image-container layer_cart_img">
            <img class="layer_cart_img img-responsive" src="'.$product_thumb.'" alt="'.$object->label.'" title="'.$object->label.'">
        </div>
        <div id="layer_cart_product_info">
            <span id="layer_cart_product_title" class="product-name">'.$object->label.'</span>
            <span id="layer_cart_product_attributes"></span>
            <div>
            <strong class="dark">'.$weblangs->trans("Quantity").' : </strong>
            <span id="layer_cart_product_quantity">'.$product_qty.'</span>
            </div>
            <div>
            <strong class="dark">'.$weblangs->trans("Total").' : </strong>
            <span id="layer_cart_product_price">('.($product_qty * $price_to_display).' €)</span>
            </div>
        </div>';

    header("Content-type: application/json");
    die(json_encode(array('items'=>$total_items,'popup_product_html'=>$popup_product_html))); //output json
}

if (GETPOST('load_cart') && GETPOST('load_cart') == 1) {
    if (isset($_SESSION['products']) && count($_SESSION['products']) > 0) { //if we have session variable
    
    
        $cart_box = '
        <p class="cart-buttons">
            <a id="button_order_cart" class="btn btn-default button button-small" href="' . $order_page_url . '" title="Check out" rel="nofollow">
                <span> '.$weblangs->trans("cartCheckout").' <i class="icon-chevron-right right"></i>
                </span>
            </a>
        </p>
        ';
        
        $total = 0;
        foreach($_SESSION['products'] as $cart_product){ //loop though items and prepare html content

            $cart_box .= "<dl class=\"products\">
                <dt class=\"item\" data-id=\"cart_block_product_" . $cart_product['product_id'] . "\" style=\"display: block;\">
                    <a class=\"cart-images\" href=\"product.php?id=" . $cart_product['product_id'] . "\" title=\"" . $cart_product['product_name'] . "\"><img src=\"" . $cart_product['product_thumb'] . "\" alt=\"" . $cart_product['product_name'] . "\"></a>
                    <div class=\"cart-info\">
                        <div class=\"product-name\"><span class=\"quantity-formated\"><span class=\"quantity\">" . $cart_product['product_qty'] . "</span>&nbsp;x&nbsp;</span><a href=\"product.php?id=" . $cart_product['product_id'] . "\" title=\"" . $cart_product['product_name'] . "\" class=\"cart_block_product_name truncate3\">" . $cart_product['product_name'] . "</a></div>
                        <span class=\"price\">" . price($cart_product['product_price']) . " €</span>
                    </div>
                    <span class=\"remove_link\"><a rel=\"nofollow\" class=\"ajax_cart_block_remove_link\" href=\"\" data-code=\"" . $cart_product['product_id'] . "\"> </a></span>
                </dt>
            </dl>";

            $subtotal = ($cart_product['product_price'] * $cart_product['product_qty']);
            $total = ($total + $subtotal);
        }
        $cart_box .= '
        <div class="cart-prices">
            <div class="cart-prices-line first-line last-line">
                <span class="price cart_block_total ajax_block_cart_total">' . $total . ' €</span>
                <span>'.$weblangs->trans("Total").'</span>
            </div>
            <p> '.$weblangs->trans("priceDependCountry").' </p>
        </div>
        ';
        die($cart_box); //exit and output content
    }else{
        die("<p class='cart_block_no_products'> No products </p>"); //we have empty cart
    }
}

if (GETPOST('load_popup_products_html') && GETPOST('load_popup_products_html') == 1) {
    if(isset($_SESSION['products']) && count($_SESSION['products'])>0){ //if we have session variable
        $total = 0;
        foreach($_SESSION['products'] as $cart_product){ //loop though items and prepare html content
            $subtotal = ($cart_product['product_price'] * $cart_product['product_qty']);
            $total = ($total + $subtotal);
        }
        if(count($_SESSION['products']) == 1){
            $title = '<span class="ajax_cart_product_txt"> '.$weblangs->trans("OneItemInCart").' </span>';
        }else{
            $title = '<span class="ajax_cart_product_txt_s"> '.$weblangs->trans("NbreProductsInCart", count($_SESSION["products"])).' </span>';
        }
        $popup_products_html = '
        <h2>'.$title.'</h2>
        <div class="layer_cart_row">
            <strong class="dark"> '.$weblangs->trans("TotalProductsInCart").' </strong>
            <span class="ajax_block_products_total">'.$total.' €</span>
        </div>
        <div class="button-container">
            <span class="continue btn btn-default button exclusive-medium" title="'.$weblangs->trans("ContinueShopping").'">
            <span>
                <i class="icon-chevron-left left"></i>'.$weblangs->trans("ContinueShopping").' </span>
            </span>
            <a class="btn btn-default button button-medium" href="' . $order_page_url . '" title="'.$weblangs->trans("ProceedToCheckout").'" rel="nofollow">
            <span> '.$weblangs->trans("ProceedToCheckout").' <i class="icon-chevron-right right"></i>
            </span>
            </a>
        </div>';

        die($popup_products_html); //exit and output content
    }
}


// Remove item from shopping cart
if (GETPOST('remove_code') && isset($_SESSION['products'])) {
    $product_code   = GETPOST('remove_code'); //get the product code to remove

    if(isset($_SESSION['products'][$product_code]))
    {
        unset($_SESSION['products'][$product_code]);
    }

    $total_items = count($_SESSION['products']);

    header("Content-type: application/json");
    die(json_encode(array('items'=>$total_items)));
}

if (GETPOST('action') && GETPOST('action') == "update_order" && GETPOST('order')) {
    include_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
    $error = 0;
    foreach (GETPOST('order') as $id_image => $position_image) {
        $ecmfile = new EcmFiles($db);
        $result_get_ecmfile = $ecmfile->fetch($id_image);
        $ecmfile->position = $db->escape($position_image);
        $result_update_ecmfile = $ecmfile->update($user);
        if ($result_update_ecmfile < 0) {
		    $error++;
    	}
    }    
    if ($error > 0) {
        header("Content-type: application/json");
        die(json_encode(array('success' => false, 'message' => $weblangs->trans('errorOccurred'))));
	} else {
        header("Content-type: application/json");
		die(json_encode(array('success' => true, 'message' => $weblangs->trans('orderChanged'))));
	}

}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && GETPOST('action') == 'add_product_image' && GETPOST('position') && GETPOST('product_id') && isset($_FILES['file']['name'])) {
    $error = 0;
    $error_messages = '';
    $product = new Product($db);
	$ret = $product->fetch(GETPOST('product_id', 'int'));
	if ($ret < 0) {
		$error++;
	}
    
    if ($error == 0) {
        $checkImage = checkImage($_FILES['file']);
        if ($checkImage != false) {
            $error++;
    	    $error_messages = $checkImage;
        }
    }
    
    if ($error == 0){
        $upload_dir = $conf->product->multidir_output[1] . '/' . get_exdir(0, 0, 0, 1, $product, 'product');
        $img = $upload_dir . '/' . $product->ref . '-image_' . GETPOST('position', 'int') . '.jpg';
        if (move_uploaded_file($_FILES['file']['tmp_name'], $img) != true){
            $error++;
            $error_messages = $weblangs->trans('fileCopyError');
        } else {
            // Add thumb
            $product->addThumbs($img);

            // Add index to db
            $filename = basename($product->ref . '-image_' . GETPOST('position', 'int')  . '.jpg');
    		addFileIntoDatabaseIndex($upload_dir, $filename, 'MARKETPLACE', 'uploaded', 1, $product);
    
    		// Update index to put position
    		$rel_dir = preg_replace('/^' . preg_quote(DOL_DATA_ROOT, '/') . '/', '', $upload_dir);
    		$rel_dir = preg_replace('/^[\\/]/', '', $rel_dir);
    		$ref = dol_hash($rel_dir . '/' . $filename, 3);
    
    		$ecmfile = new EcmFiles($db);
    		$result_get_ecmfile = $ecmfile->fetch('', $ref);
    
    		$ecmfile->position = GETPOST('position', 'int');
    		
    		$result_update_ecmfile = $ecmfile->update($user);
    
    		if ($result_update_ecmfile < 0) {
    			$error++;
    		    $error_messages = $weblangs->trans('fileCopyError');
    	    }
    	}
    }
    
    if ($error > 0) {
        header("Content-type: application/json");
        die(json_encode(array('success' => false, 'message' => $error_messages)));
	} else {
        header("Content-type: application/json");
		die(json_encode(array('success' => true, 'message' => $weblangs->trans('imageAdded'))));
	}
}

if (GETPOST('action') == "delete_image" && GETPOST('id_image')) {
    include_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
    $id_image = GETPOSTINT('id_image');
    $error = 0;
    $ecmfile = new EcmFiles($db);
    $result_get_ecmfile = $ecmfile->fetch($id_image);
    $result_delete_ecmfile = $ecmfile->delete($user);
    if ($result_delete_ecmfile < 0) {
	    $error++;
	}
	
    if ($error > 0) {
        header("Content-type: application/json");
        die(json_encode(array('success' => false, 'message' => $weblangs->trans('errorOccurred'))));
	} else {
        header("Content-type: application/json");
		die(json_encode(array('success' => true, 'message' => $weblangs->trans('imageDeleted'))));
	}

}

// Generate CVS of sells history
if (GETPOST('sells_history') && GETPOST('sells_history') == 1) {

    // Get Account ID.
    include_once DOL_DOCUMENT_ROOT.'/societe/class/societeaccount.class.php';
    $user_id = $_SESSION['user']['id_user'];
    $customer_account = new SocieteAccount($db);
    $result = $customer_account->fetch($user_id);
    $customer_id = $customer_account->fk_soc;
    
    // Render a CSV of another customer
    if (!empty(GETPOST('id_customer')) && GETPOST('id_customer') != $customer_id) {
        // 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 liste of products
    $products_ids = array();
    $sql = 'SELECT fk_product, MIN(datec) AS first_date FROM '.MAIN_DB_PREFIX."product_fournisseur_price WHERE fk_soc = ".((int) $customer_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);
    

    /*$data_for_csv = "SELECT s.nom as customer, c.date_commande as registred_on, sp.email, sc.label as country, c.date_commande, p.rowid as product_id ,p.label ,p.ref, d.total_ht as total_earned, d.total_ht as total_origin, c.fk_statut ";
    $data_for_csv .= "FROM ".MAIN_DB_PREFIX."commande as c, ".MAIN_DB_PREFIX."commandedet as d , ".MAIN_DB_PREFIX."product as p , ".MAIN_DB_PREFIX."societe as s , ".MAIN_DB_PREFIX."socpeople as sp , ".MAIN_DB_PREFIX."c_country as sc ";
    $data_for_csv .= "WHERE p.rowid = d.fk_product AND s.rowid = c.fk_soc AND sp.fk_soc = s.rowid AND sp.fk_pays = sc.rowid AND 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 || c.ref_ext IS NOT NULL) and c.module_source = 'Marketplace' ";
    $data_for_csv .= "ORDER BY c.date_commande DESC";*/
    
    $data_for_csv = "SELECT c.rowid as c_id, d.rowid as d_id, s.nom as customer, s.datec as registred_on, sp.email, sc.label as country, c.date_commande, ";
    $data_for_csv .= "p.rowid as product_id, p.label, p.ref, d.total_ht as total_earned, d.total_ht as total_origin, c.fk_statut ";
    $data_for_csv .= "FROM ".MAIN_DB_PREFIX."commande as c ";
    $data_for_csv .= "JOIN ".MAIN_DB_PREFIX."commandedet as d ON c.rowid = d.fk_commande ";
    $data_for_csv .= "JOIN ".MAIN_DB_PREFIX."product as p ON p.rowid = d.fk_product ";
    $data_for_csv .= "JOIN ".MAIN_DB_PREFIX."societe as s ON s.rowid = c.fk_soc ";
    $data_for_csv .= "JOIN ".MAIN_DB_PREFIX."societe_account as sa ON s.rowid = sa.fk_soc ";
    $data_for_csv .= "JOIN ".MAIN_DB_PREFIX."socpeople as sp ON sp.fk_soc = s.rowid  AND sp.ref_ext = sa.rowid ";
    $data_for_csv .= "JOIN ".MAIN_DB_PREFIX."c_country as sc ON sp.fk_pays = sc.rowid ";
    $data_for_csv .= "WHERE d.fk_product IN (" . $products_ids_str . ") ";
    $data_for_csv .= "AND d.total_ht != 0 ";
    $data_for_csv .= "AND c.fk_statut IN (1,3) ";
    $data_for_csv .= "AND (c.facture = 1 OR c.ref_ext IS NOT NULL) ";
    $data_for_csv .= "AND c.module_source = 'Marketplace' ";
    $data_for_csv .= "ORDER BY c.date_commande DESC";
    //print $data_for_csv;
    
    //print $data_for_csv;

    if ($result_data_for_csv = $db->query($data_for_csv)) {
        $row_no = 1;
        $data = [
            ['#', 'Customer', 'Customer date creation', 'Customer email', 'Customer country', 'Date sell', 'Product id', 'Product label', 'Product ref', 'Amount earned', 'Amount origin', 'Note']
        ];
        $current_date = new DateTime();
        while ($row = $result_data_for_csv->fetch_object()) {

            $date_commande = new DateTime($row->date_commande);
        
            $interval = $current_date->diff($date_commande);
            $days_diff = $interval->days;
            
            if ($days_diff > 30) {
                $status = 'validated';
            } else {
                $status = '';
            }
            
            $data[] = [
                $row_no++,
                $row->customer,
                $row->registred_on,
                $row->email,
                $row->country,
                $row->date_commande,
                $row->product_id,
                $row->label,
                $row->ref,
                /*price($row->total_earned),
                price($row->total_origin),*/
                number_format($row->total_earned, 2, '.', ''),
                number_format($row->total_origin, 2, '.', ''),
                $status
            ];
        }
    }

    $filepath = 'export_' . date('Ymd') . '.csv';

    $fp = fopen($filepath, 'w');

    foreach ($data as $row) {
        fputcsv($fp, $row, ';');
    }

    fclose($fp);
    
    
    header("Content-type: application/json");
    print json_encode(['filepath' => $filepath]);
    exit();
}


if (GETPOST('filepath') && GETPOST('action') === 'remove_csv') {
    $filepath = GETPOST('filepath');
    if (file_exists($filepath)) {
        unlink($filepath);
        header("Content-type: application/json");
        echo json_encode(['status' => 'success', 'message' => 'File deleted']);
    } else {
        header("Content-type: application/json");
        echo json_encode(['status' => 'error', 'message' => 'file not found']);
    }
}


?>
