<?php

class PackageDocuments{
    private function getProductDocuments($idPackage = 0){
        global $database, $user;
        $whreSql = "";
        $maxInstWhereSql = "";
        $data = [];

        if($user->getUserType() !== USER_TYPES['BROKER']){
            $whreSql = " AND visibleToCustomer=1";
        }

        if($idPackage !== 0){
            $whreSql .= " AND rpp.idPackage=$idPackage";
            $maxInstWhereSql = "AND idPackage=$idPackage";
        }

        $sql = "SELECT
                    d.id AS idDocument,
                    d.documentName,
                    d.documentPath,
                    d.extension,
                    dt.type AS documentType,
                    rpp.idPackage,
                    rpd.idProduct
                FROM ".TABLES['rel_product_documents']." rpd
                INNER JOIN ".TABLES['documents']." d
                    ON d.id=rpd.idDocument
                INNER JOIN ".TABLES['document_types']." dt
                    ON dt.id=d.idDocumentType
                INNER JOIN ".TABLES['rel_package_products']." rpp
                    ON rpp.idProduct=rpd.idProduct
                INNER JOIN (
                    SELECT MAX(packageInstance) as maxInstance
                    FROM ".TABLES['rel_package_products']."
                    WHERE 1=1 $maxInstWhereSql
                    GROUP BY idPackage
                ) max_inst
                    ON max_inst.maxInstance=rpp.packageInstance
                WHERE 1=1 $whreSql
                ";
        $query = $database->query($sql);
        while($row = $database->fetchArray($query)){
            $data[$row['idPackage']][] = $row;
        }

        return $data;
    }

    /**
     * get package documents
     * @param  INT $idPackage        id for the pacakge
     * @return Array                 list of documents
     */
    public function getPackageDocuments($idPackage = 0){
        global $database;
        $data[$idPackage] = [];
        $whereSql = $idPackage !== 0 ? "WHERE rpd.idPackage=$idPackage" : "";

        $sql = "SELECT
                   d.id AS idDocument,
                   d.documentName,
                   d.extension,
                   rpd.idPackage
               FROM ".TABLES['documents']." d
               INNER JOIN ".TABLES['document_types']." dt
                   ON dt.id=d.idDocumentType
               INNER JOIN ".TABLES['rel_package_documents']." rpd
                   ON rpd.idDocument=d.id
               $whereSql ";

        $query = $database->query($sql);
        while($row = $database->fetchArray($query)){
            $data[$row['idPackage']][] = $row;
        }
        $productDocuments = $this->getProductDocuments($idPackage);
        foreach ($data as $idPackage => &$documents) {
            if(isset($productDocuments[$idPackage])){
                $documents = array_merge($documents, $productDocuments[$idPackage]);
            }
        }

        return $data;
    }
}
