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

$type = GETPOST('t', 'alpha');
$order_ref = GETPOST('r', 'alpha');
$id_produit = GETPOST('p', 'alpha');
$user_id = GETPOST('u', 'alpha');

// Link for paied modules 
if ($type == "paied") {
    if (!empty($order_ref) && !empty($id_produit) && !empty($user_id)) {
    
        // Get Account ID.
        $customer_account = new SocieteAccount($db);
        $result = $customer_account->fetch($user_id);
        $customer_id = $customer_account->fk_soc;
    
        // Check given informations
        $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 = " . ((int) $customer_id) . " and c.ref = '" . $db->escape($order_ref) . "' and c.fk_statut= 1 and (c.facture = 1 OR 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)) {
            http_response_code(404);
            echo $weblangs->trans("unfoundedOrder");
            exit;
        }
    
        $order_ref = $obj_order->ref;
        $order_object = new Commande($db);
        $result = $order_object->fetch('', $order_ref);
        if ($result < 0) {
            http_response_code(404);
            echo $weblangs->trans("unfoundedOrder");
            exit;
        }
    
        $one_year_ago = dol_time_plus_duree(dol_now(), -1, 'y');
        if ($order_object->date < $one_year_ago) {
            http_response_code(410);
            echo $weblangs->trans("invalidLink");
            exit;
        }
    
        $lines = $order_object->lines;
        $check_product = false;
        foreach ($lines as $line) {
            if ($line->fk_product == $id_produit) {
                $check_product = true;
                break;
            }
        }
    
        if (!$check_product) {
            http_response_code(403);
            echo $weblangs->trans("productNotFoundInOrder");
            exit;
        }

        // Looking for credit notes for the main invoice. It can be more then one
        // Check if qty in order mince qty in credit note (if existe) is grather than 0
        $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;
            }

    		$linked_credits = [];
            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->ref;
                }
            }
            
            if (!empty($linked_credits)) {
                $credit_note_refs_placeholder = implode(',', array_map(function($ref) use ($db) {
                    return "'" . $db->escape($ref) . "'";
                }, $linked_credits));
            }
            
            $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 . ")";
            
            $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) {
                http_response_code(410);
                echo $weblangs->trans("Refunded");
                exit;
            }
        }
    
        $product = new Product($db);
        $ret = $product->fetch($line->fk_product);

        $sql_file = "SELECT rowid, ref, share, filename, filepath, cover, position";
    	$sql_file .= " FROM ".MAIN_DB_PREFIX."ecm_files";
    	$sql_file .= " WHERE entity IN (".getEntity($product->element).")";
    	$sql_file .= " AND src_object_type = '".$db->escape($product->element)."' AND src_object_id = ".((int) $product->id)." AND position = 100 ";
    	$sql_file .= $db->order("date_c", "DESC");
    	$sql_file .= $db->plimit(1);
    	$fileQuery = $db->query($sql_file);
        $fileDetails = $db->fetch_object($fileQuery);
        $file_path = DOL_DATA_ROOT . "/" . $fileDetails->filepath . "/" .$fileDetails->filename;
    
        if (!empty($file_path)) {
            $type = dol_mimetype($fileDetails->filename);
            header('Content-Type: '.$type);
            header('Content-Description: File Transfer');
            header('Content-Disposition: attachment; filename="' . $fileDetails->filename . '"');
            readfile($file_path);
            exit;
        }
        else {
            http_response_code(404);
            echo $weblangs->trans("FileNotFound");
            exit;
        }
    }
}

// Link for free modules 
if ($type == "free") {
    if (!empty ($id_produit)) {
        $product = new Product($db);
        $ret = $product->fetch($id_produit);
        
        if ($product->price_ttc == 0) {
            $sql_file = "SELECT rowid, ref, share, filename, filepath, cover, position";
        	$sql_file .= " FROM ".MAIN_DB_PREFIX."ecm_files";
        	$sql_file .= " WHERE entity IN (".getEntity($product->element).")";
        	// TODO Why position=100 ?
        	$sql_file .= " AND src_object_type = '".$db->escape($product->element)."' AND src_object_id = ".((int) $product->id)." AND position = 100 ";
        	$sql_file .= $db->order("date_c", "DESC");
        	$sql_file .= $db->plimit(1);
        	$fileQuery = $db->query($sql_file);
            $fileDetails = $db->fetch_object($fileQuery);
            $file_path = DOL_DATA_ROOT . "/" . $fileDetails->filepath . "/" .$fileDetails->filename;
            
            if (!empty($file_path)) {
                $type = dol_mimetype($fileDetails->filename);
                header('Content-Type: '.$type);
                header('Content-Description: File Transfer');
                header('Content-Disposition: attachment; filename="' . $fileDetails->filename . '"');
                header('Cache-Control: no-cache');
                readfile($file_path);
                exit;
            }
            else {
                http_response_code(404);
                echo $weblangs->trans("FileNotFound");
                exit;
            }
        } else {
            echo $weblangs->trans("paiedProduct");
        }
    }
}

?>
