<?php

class OrderDocuments{
    const DOCUMENT_TYPES = [
        'ID_QUESTIONAIRE_DOC_TYPE' => 2, // 2 => 'orderQuestionaire'
        'ID_CONFIGURATION_DOC_TYPE' => 3, // 3 => 'configuration'
        'ID_ACCEPTANCE_DOC_TYPE' => 5, // 5 => 'customerAcceptance'
        'ID_INSTALLATION_PROTOTCOL_DOC_TYPE' => 10 // 10 => 'installationProtocol'
    ];

    private function getProductDocuments($idOrder){
        global $database, $user;
        $whreSql = "";
        $data = [];

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

        $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 ".TABLES['rel_order_packages']." rop
                    ON rop.idPackage=rpp.idPackage AND rop.packageInstance=rpp.packageInstance
                WHERE rop.idOrder=$idOrder $whreSql
                ";
        $query = $database->query($sql);
        while($row = $database->fetchArray($query)){
            $data[$row['idPackage']][] = $row;
        }

        return $data;
    }

    /**
     * get all docuemnts linked to an order
     * @param  INT $idOrder id for the order
     * @return Array        list of documetns for an order grouped by package id
     */
    public function getOrderDocuments($idOrder){
        global $database;
        $data = [];

        $sql = "SELECT
                    d.id AS idDocument,
                    d.documentName,
                    d.documentPath,
                    d.extension,
                    dt.type AS documentType,
                    IFNULL(rod.idPackage, 0) as idPackage
                FROM ".TABLES['rel_order_documents']." rod
                INNER JOIN ".TABLES['documents']." d
                    ON d.id=rod.idDocument
                INNER JOIN ".TABLES['document_types']." dt
                    ON dt.id=d.idDocumentType
                WHERE rod.idOrder=$idOrder
                UNION all
                SELECT
                        d.id AS idDocument,
                        d.documentName,
                        d.documentPath,
                        d.extension,
                        dt.type AS documentType,
                        rpd.idPackage
                    FROM ".TABLES['rel_package_documents']." rpd
                    INNER JOIN ".TABLES['rel_order_packages']." rop
                        ON rop.idPackage=rpd.idPackage
                    INNER JOIN ".TABLES['documents']." d
                        ON d.id=rpd.idDocument
                    INNER JOIN ".TABLES['document_types']." dt
                        ON dt.id=d.idDocumentType
                    WHERE rop.idOrder=$idOrder";
        $query = $database->query($sql);
        while($row = $database->fetchArray($query)){
            $data[$row['idPackage']][] = $row;
        }

        $productDocuments = $this->getProductDocuments($idOrder);
        if(!empty($productDocuments)){
            foreach ($productDocuments as $idPackage => &$documents) {
                if(isset($data[$idPackage])){
                    $data[$idPackage] = array_merge($data[$idPackage], $documents);
                }else{
                    $data[$idPackage] = $documents;
                }
            }
        }

        return $data;
    }

    /**
     * upload a new file for configuration
     * @param  INT $idOrder    id for the order
     * @param  INT $idPackage  id for the package
     * @param  INT $idSupplier id for supplier
     * @param  STRING $fileType the type of the file (configuration or installation)
     * @param  FILE $file      file to be uploaded
     * @return Array           upload message
     */
    public function uploadConfigurationDocument($idOrder, $idPackage, $idSupplier, $fileType, $file){
        global $database, $user;
        $idOrder = $database->escapeValue($idOrder);
        $idPackage = $database->escapeValue($idPackage);
        $idSupplier = $database->escapeValue($idSupplier);
        $fileType = $database->escapeValue($fileType);

        if(!$idPackage){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'NO_PACKAGE'
            ];

            return $data;
        }

        $idDocumentType = self::DOCUMENT_TYPES['ID_CONFIGURATION_DOC_TYPE'];
        $nameSuffix = 'config';
        $maxCount = 1;

        $sql = "SELECT s.idUser
                FROM ".TABLES['suppliers']." s
                WHERE s.id=$idSupplier";
        $query = $database->query($sql);
        $supplier = $database->fetchArray($query);

        $sql = "SELECT name
                FROM ".TABLES['packages']."
                WHERE id=$idPackage";
        $query = $database->query($sql);
        $package = $database->fetchArray($query);
        $documentName = isset($package['name']) ? str_replace(' ', '_', $package['name']) : '';
        $documentName .= '_'.$idSupplier.'_'.$nameSuffix;

        $sql = "
            SELECT
              d.documentName
            FROM
              ".TABLES['documents']." d
              INNER JOIN ".TABLES['rel_order_documents']." rod
                ON d.id = rod.idDocument
            WHERE rod.idOrder = $idOrder
              AND rod.idPackage = $idPackage
              AND d.idDocumentType = $idDocumentType
            ORDER BY d.id DESC
            LIMIT 1";
        $lastDocName = $database->fetchResultArray($sql);
        if($lastDocName && $lastDocName[0]['documentName']) {
            $count = explode('_', $lastDocName[0]['documentName']);
            $maxCount = intval(end($count)) + 1;
        }
        $documentName .= '_'.$maxCount;
        $idUser = $user->getUserId();

        $fileManager = new FileManager();
        $data = $fileManager->uploadFile($file, $idDocumentType, $documentName, $idUser, $supplier['idUser']);
        if(isset($data['messages'])){
            return $data;
        }

        $idDocument = $data['idDocument'];

        $sql = "INSERT INTO ".TABLES['rel_order_documents']."
                (idOrder, idPackage, idDocument, validation)
                VALUES($idOrder, $idPackage, $idDocument, 'not-required')";
        $query = $database->query($sql);

        if($database->affectedRows() > 0){
            $data['messages'][] = [
                'code' => 'success',
                'message' => 'FILE_UPLOADED'
            ];
        }else{
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'NOT_UPLOADED'
            ];
        }

        return $data;
    }

    /**
     * remove order document
     * @param  INT $idOrder    id for order
     * @param  INT $idPackage  id for package
     * @param  INT $idDocument id for document
     * @return Array           remove message
     */
    public function removeOrderDocument($idOrder, $idPackage, $idDocument) {
        global $database;
        $idOrder = $database->escapeValue($idOrder);
        $idPackage = $database->escapeValue($idPackage);
        $idDocument = $database->escapeValue($idDocument);
        $rowsDeleted = 0;
        $data = [];

        if(!$idDocument) {
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'DOCUMENT_NOT_SET'
            ];

            return $data;
        }

        $fileManager = new FileManager();
        $data = $fileManager->removeDocument($idDocument);

        foreach ($data['messages'] as $messageObj) {
            if ($messageObj['code'] === 'success') {
                $sqlUnlink = "
                            DELETE
                              FROM ".TABLES['rel_order_documents']."
                            WHERE idOrder = $idOrder
                              AND idPackage = $idPackage
                              AND idDocument = $idDocument
                ";
                $query = $database->query($sqlUnlink);
            }
        }

        return $data;
    }
}
