<?php
class OrderHelper{
    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'
    ];
    
    /**
     * get the orderNumber based on the order id
     * @param  Int $idOrder the id of the order
     * @return Int           the order number of that order
     */
    public function getOrderNumberById($idOrder) {
        global $database;

        $sql = "
            SELECT
                o.orderNumber
            FROM
                ".TABLES['orders']." o
            WHERE o.id = $idOrder
            LIMIT 1
        ";
        $orderNumberArray = $database->fetchResultArray($sql);
        if($orderNumberArray && $orderNumberArray[0]) {
            return array_key_exists('orderNumber', $orderNumberArray[0]) ? $orderNumberArray[0]['orderNumber'] : '';
        }

        return '';
    }

    /**
     * gets the name of the customer and commercial lead by order id
     * @param  Int $idOrder the id of the order
     * @return Array          the names of the customer and commercial lead from the given order
     */
    public function getCustomerAndCLNamesFromOrder($idOrder) {
        global $database;

        $sql = "
            SELECT
                c.name AS customerName,
                cl.name AS commercialLeadName
            FROM
                ".TABLES['orders']." o
            INNER JOIN ".TABLES['rel_commercial_lead_customers']." rclc
                ON rclc.id = o.idCustomerInstance
            INNER JOIN ".TABLES['customers']." c
                ON c.id = rclc.idCustomer
            INNER JOIN ".TABLES['commercial_leads']." cl
                ON cl.id = rclc.idCommercialLead
            WHERE o.id = $idOrder
            LIMIT 1
        ";
        $values = $database->fetchResultArray($sql);

        return $values && $values[0] ? $values[0] : [];
    }

    /**
     * returns the processId selected for a package in an order
     * @param  Int $idOrder   id of the order
     * @param  Int $idPackage id of the package
     * @return Int            the id of the process selected
     */
    public function getIdProcessSelectedForPackageOrder($idOrder, $idPackage) {
        global $database;

        if(!$idPackage) {
            return 0;
        }

        $sql = "
            SELECT
                rps.idProcess
            FROM
                ".TABLES['rel_process_steps']." rps
            INNER JOIN ".TABLES['rel_order_process_step']." rops
                ON rops.idProcessStep = rps.id
                AND rops.idPackage = $idPackage
                AND rops.idOrder = $idOrder
            GROUP BY rps.idProcess
            LIMIT 1
        ";

        return $database->fetchResultArray($sql)[0]['idProcess'];
    }

    /**
	 * returns the mail addresses for cl and customer involved in the order process
     * @param  String $customerName   		customer's name
     * @param  String $commercialLeadName 	commercial lead's name
     * @return Array            			mails of the customer and commercial lead
     */
	public function getCLAndCustomerMails($customerName, $commercialLeadName, $isForComment = 0) {
		global $database, $user;
        $mailArray = [];

		$sql = "
				SELECT
                  c.idUser,
				  u.mail,
                  'customer' AS type
				FROM
				  ".TABLES['customers']." c
                  INNER JOIN ".TABLES['users']." u
                    ON u.id = c.idUser
				WHERE c.name = '$customerName'
				UNION
				SELECT
                  cl.idUser,
				  u.mail,
                  'other' AS type
				FROM
				  ".TABLES['commercial_leads']." cl
                  INNER JOIN ".TABLES['users']." u
                    ON u.id = cl.idUser
				WHERE cl.name = '$commercialLeadName'
		";
		$result = $database->query($sql);
        while($row = $database->fetchArray($result)) {
            if($row['mail'] !== '') {
                if($isForComment) {
                    if($row['idUser'] != $user->getUserId()) {
                        $mailArray[$row['type']][] = $row['mail'];
                    }
                } else {
                    $mailArray[$row['type']][] = $row['mail'];
                }
            }
        }

		return $mailArray;
	}

    /**
     * check if user has rights to see a specific order
     * @param  INT $idOrder id of the order
     * @return Boolean      retruns true if the user can see the order
     */
    public function checkOrderOwner($idOrder){
        global $database, $user;

        if($user->getUserType() === USER_TYPES['BROKER']){
            return true;
        }else if($user->getUserType() === USER_TYPES['CUSTOMER']){
            $extraJoin = " INNER JOIN ".TABLES['rel_commercial_lead_customers']." rclc
                            ON rclc.id=o.idCustomerInstance
                            INNER JOIN ".TABLES['customers']." u
                            ON u.id=rclc.idCustomer";
        }else if($user->getUserType() === USER_TYPES['COMMERCIAL_LEAD']){
            $extraJoin = "INNER JOIN ".TABLES['rel_commercial_lead_customers']." rclc
                            ON rclc.id=o.idCustomerInstance
                            INNER JOIN ".TABLES['commercial_leads']." u
                            ON u.id=rclc.idCommercialLead";
        }else if($user->getUserType() === USER_TYPES['SUPPLIER']){
            $extraJoin = "INNER JOIN ".TABLES['rel_order_products_estimation']." rope
                            ON rope.idOrder=o.id
                          INNER JOIN ".TABLES['suppliers_countries_products']." scp
                            ON scp.idProduct=rope.idProduct
                            OR scp.idProductCategory = ".self::ID_INSTALLATION_CATEGORY."
                          INNER JOIN ".TABLES['suppliers']." u
                            ON u.id=scp.idSupplier";
        }else{
            return false;
        }

        $sql = "SELECT o.id
                FROM ".TABLES['orders']." o
                $extraJoin
                WHERE u.idUser=".$user->getUserId()." AND o.id=$idOrder
                LIMIT 1";
        $query = $database->query($sql);

        return $database->numRows($query) === 1;
    }

    /**
        * upload document for an order
        * @param  Int $idOrder        id of the order
        * @param  Int $idPackage      id of the package
        * @param  Int $idFileType     the id of the type of the file uploaded
        * @param  String $fileName    the name of the file
        * @param  FILE $file          file to be uploaded
        * @return Array               message with status
     */
    public function uploadOrderDocument($idOrder, $idPackage, $idDocumentType, $documentName, $file){
        global $database;
        $idOrder = $database->escapeValue($idOrder);
        $idPackage = $database->escapeValue($idPackage);
        $idDocumentType = $database->escapeValue($idDocumentType);
        $documentName = $database->escapeValue($documentName);

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

            return $data;
        }

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

            return $data;
        }

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

            return $data;
        }

        $sql = "SELECT d.id
               FROM ".TABLES['documents']." d
               WHERE d.documentName='$documentName'";
        $query = $database->query($sql);
        if($database->numRows($query) > 0){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'NAME_EXISTS'
            ];

            return $data;
        }

        $fileManager = new FileManager();
        $data = $fileManager->uploadFile($file, $idDocumentType, $documentName);

        if(isset($data['messages'])){
            return $data;
        }

        if(array_search($idDocumentType, [self::DOCUMENT_TYPES['ID_CONFIGURATION_DOC_TYPE'], self::DOCUMENT_TYPES['ID_INSTALLATION_PROTOTCOL_DOC_TYPE']])) {
            $docValidation = 'not-required';
        } else {
            $docValidation = 'not-validated';
        }

        $idDocument = $data['idDocument'];

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

        $data['messages'][] = [
            'code' => 'success',
            'message' => 'DOCUMENT_UPLOADED'
        ];

        return $data;
    }
}
