<?php

class SupplierEstimations{

    private function getTrackingInfo($idOrder) {
        global $database;
        $data = [];

        $sql = "
                SELECT
                  roso.id AS idTracking,
                  roso.idSupplier,
                  roso.trackingNumber,
                  roso.trackingUrl
                FROM
                  ".TABLES['rel_order_supplier_options']." roso
                WHERE roso.idOrder = $idOrder";
        $query = $database->query($sql);

        while($row = $database->fetchArray($query)) {
            $data[$row['idSupplier']][] = $row;
        }

        return $data;
    }

    /**
     * add null values for products estimations in an order
     * @param INT $idOrder   id of the order
     */
    private function addStartEstimatisonForProducts($idOrder){
        global $database;

        $sql = "INSERT INTO ".TABLES['rel_order_supplier_estimations']."
                (idOrder, idSupplier)
                SELECT rop.idOrder, scp.idSupplier
                FROM ".TABLES['rel_package_products']." rpp
                INNER JOIN ".TABLES['rel_order_packages']." rop
                    ON rop.idPackage=rpp.idPackage AND rop.packageInstance=rpp.packageInstance
                INNER JOIN ".TABLES['suppliers_countries_products']." scp
                    ON scp.idProduct=rpp.idProduct
                WHERE rop.idOrder=$idOrder
                GROUP BY rop.idOrder, scp.idSupplier";
        $query = $database->query($sql);

        return $database->affectedRows();
    }

    /**
     * get estimations for products
     * @param  INT $idOrder   id for the order
     * @return Array          Array of products estimations
     */
    public function getSupplierEstimations($idOrder){
        global $database, $user;
        $idOrder = $database->escapeValue($idOrder);
        $data = [];
        $whereSql = "";

        $trackingInfo = $this->getTrackingInfo($idOrder);

        if($user->getUserType() === USER_TYPES['SUPPLIER']){
            $whereSql = " AND s.idUser=".$user->getUserId();
        }

        $sql = "SELECT
                       rose.estimatedDate,
                       rose.confirmedDate,
                       s.id AS idSupplier,
                       s.name AS supplierName
                FROM ".TABLES['rel_order_supplier_estimations']." rose
                INNER JOIN ".TABLES['suppliers']." s
                    ON s.id=rose.idSupplier
                WHERE idOrder=$idOrder $whereSql
                ORDER BY s.id";

        $query = $database->query($sql);
        if($database->numRows($query) === 0){
            if($user->getUserType() === USER_TYPES['SUPPLIER']) {
                return $data;
            }
            $addedStartValues = $this->addStartEstimatisonForProducts($idOrder);
            if($addedStartValues > 0){
                return $this->getSupplierEstimations($idOrder);
            }else{
                return $data;
            }
        }

        while($row = $database->fetchArray($query)){
            $row['trackings'] = isset($trackingInfo[$row['idSupplier']]) ? $trackingInfo[$row['idSupplier']] : [];
            $data[] = $row;
        }

        return $data;
    }

    private function isProductOwner($idSupplier){
        global $user, $database;

        if($user->getUserType() === USER_TYPES['BROKER']){
            return true;
        }else if($user->getUserType() === USER_TYPES['SUPPLIER']){
            $sql = "SELECT s.id
                    FROM ".TABLES['suppliers']." s
                    WHERE s.id=$idSupplier AND s.idUser=".$user->getUserId();
            $query = $database->query($sql);

            return $database->numRows($query) > 0;
        }

        return false;
    }

    /**
     * update dates for products in an order
     * @param  INT $idOrder       id for the order
     * @param INT $idSupplier     od for the supplier
     * @param  String $estimatedDate estimated date
     * @param  String $confirmedDate confirmed date
     * @return Array                update message
     */
    public function updateSupplierEstimation($idOrder, $idSupplier,$estimatedDate, $confirmedDate){
        global $database;
        $idOrder = $database->escapeValue($idOrder);
        $idSupplier = $database->escapeValue($idSupplier);
        $estimatedDate = $database->escapeValue($estimatedDate);
        $confirmedDate = $database->escapeValue($confirmedDate);
        $data = [];

        if(!$this->isProductOwner($idSupplier)){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'NOT_OWNER_OF_PROD'
            ];

            return $data;
        }

        if(!$idOrder || !$idSupplier){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'EST_MISSING_DATA'
            ];

            return $data;
        }

        if(empty($estimatedDate) && empty($confirmedDate)){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'EMPTY_DATES'
            ];

            return $data;
        }

        $checkEstimatedDate = $database->invalidDate('INVALID_DATE_ESTIMATED', $estimatedDate);
        $checkConfirmedDate = $database->invalidDate('INVALID_DATE_ESTIMATED', $confirmedDate);
        if(($checkEstimatedDate && !empty($estimatedDate)) || ($checkConfirmedDate && !empty($confirmedDate))){
            $data['messages'][] = $checkEstimatedDate ? $checkEstimatedDate : [];
            $data['messages'][] = $checkConfirmedDate ? $checkConfirmedDate : [];

            return $data;
        }

        if(empty($estimatedDate)){
            $estimatedDate = $confirmedDate;
        }

        $estimatedDate = !empty($estimatedDate) ? "'$estimatedDate'" : "null";
        $confirmedDate = !empty($confirmedDate) ? "'$confirmedDate'" : "null";

        $sql = "UPDATE ".TABLES['rel_order_supplier_estimations']."
                SET estimatedDate=$estimatedDate,
                confirmedDate=$confirmedDate
                WHERE idOrder=$idOrder AND idSupplier=$idSupplier";
        $query = $database->query($sql);

        if($database->affectedRows() > 0){
            $data['messages'][] = [
                'code' => 'success',
                'message' => 'SUPPLIER_ESTIMATION_UPDATED'
            ];
            $data['idSupplier'] = $idSupplier;
        }else{
            $data['messages'][] = [
                'code' => 'warning',
                'message' => 'NO_CHANGES'
            ];
        }

        return $data;
    }

    /**
     * update dates for products in an order
     * @param  INT $idOrder       id for the order
     * @param  INT $idSupplier     id for the package
     * @param  String $type       estiamtion or confirmation date
     * @return Array                update message
     */
    public function removeSupplierEstimation($idOrder, $idSupplier, $type){
        global $database;
        $idOrder = $database->escapeValue($idOrder);
        $idSupplier = $database->escapeValue($idSupplier);
        $type = $database->escapeValue($type);
        $data = [];

        if(!$this->isProductOwner($idSupplier)){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'NOT_OWNER_OF_PROD'
            ];

            return $data;
        }

        if(!$idOrder || !$idSupplier){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'EST_MISSING_DATA'
            ];

            return $data;
        }

        if($type !== 'estimation' &&  $type !== 'confirmation'){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'INVALID_ESTIMATION_TYPE'
            ];

            return $data;
        }

        $fieldToUpdate = $type === 'estimation' ? "estimatedDate=NULL" : "confirmedDate=NULL";

        $sql = "UPDATE ".TABLES['rel_order_supplier_estimations']."
                SET $fieldToUpdate
                WHERE idOrder=$idOrder AND idSupplier=$idSupplier";
        $query = $database->query($sql);

        if($database->affectedRows() > 0){
            $data['messages'][] = [
                'code' => 'success',
                'message' => 'SUPPLIER_ESTIMATION_UPDATED'
            ];
        }else{
            $data['messages'][] = [
                'code' => 'warning',
                'message' => 'NO_CHANGES'
            ];
        }

        return $data;
    }
}
