<?php
class SuppliersModel{
    private $headersHelper;
    private $suppliersProducts;

    function __construct(){
        $this->headersHelper =  new HeadersHelper();
        $this->suppliersProducts = new SuppliersProducts();
    }

    /**
     * Get the headers requried for the suppliers
     * @param  string $type type of the headere, posible values array or sql
     * @return string|array      returns the sql header or the array of for the headers
     */
    public function getSuppliersHeaders( $type = 'array'){
        $headers = [
            's.id' => 'id',
            's.name' => 'name',
            's.phone' => 'phone',
            'u.mail' => 'mail',
            'GROUP_CONCAT(countries.countryName)' => 'sellsIn'
        ];

        return $this->headersHelper->getHeader($headers, $type);
    }

    /**
     * get the list of suppliers
     * @return Array array of suppliers
     */
    public function getSuppliers(){
        global $database;

        $headersSql = $this->getSuppliersHeaders('sql');
        $sql = "SELECT $headersSql
                FROM
                    ".TABLES['suppliers']." s
                LEFT OUTER JOIN
                (
                	 SELECT DISTINCT scp.idSupplier, c.name as countryName
                	 FROM ".TABLES['suppliers_countries_products']." scp
                	 INNER JOIN ".TABLES['countries']." c
                	 ON c.id=scp.idCountry
                ) AS countries
                    ON s.id=countries.idSupplier
                INNER JOIN ".TABLES['users']." u
                    ON u.id = s.idUser
                GROUP BY s.id
                ORDER BY s.name";

        return $database->fetchResultArray($sql);
    }

    /**
     * Get the headers requried for products for the suppliers
     * @param  string $type type of the headere, posible values array or sql
     * @return string|array      returns the sql header or the array of for the headers
     */
    public function getSuppliersProductsHeaders( $type = 'array'){
        return $this->suppliersProducts->getSuppliersProductsHeaders($type);
    }

    /**
     * get the list with all products for a country
     * @param  integer $country id of the country to get the products
     * @return Array array with all productus for the suppiers in a specific country
     */
    public function getSuppliersProducts($idCountry = 0, $idProduct = 0){
        return $this->suppliersProducts->getSuppliersProducts($idCountry, $idProduct);
    }

    /**
     * check if supplier data is valid
     * @param  HashArray $supplierData suppliers input
     * @return Array             empty array if vali or error message array
     */
    private function validateSupplierData($supplierData, $action){
        global $database;
        $data = [];

        $whereSql = $action === 'edit' ? ' AND s.id!='.$supplierData['idSupplier'] : '';
        $sql = "SELECT s.id
                FROM ".TABLES['suppliers']." s
                WHERE s.name='".$supplierData['name']."' $whereSql
                LIMIT 1";
        $query = $database->query($sql);
        if($database->numRows($query) !== 0){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'DUPLICATE_SUPPLIER_NAME'
            ];

            return $data;
        }

        $checkMessage = $database->isEmpty('name', $supplierData['name']);
        if($checkMessage){
            $data['messages'][] = $checkMessage;
        }
        $checkMessage = $database->invalidLength('name', $supplierData['name'], 70);
        if($checkMessage){
            $data['messages'][] = $checkMessage;
        }
        $checkMessage = $database->isEmpty('phone', $supplierData['phone']);
        if($checkMessage){
            $data['messages'][] = $checkMessage;
        }
        $checkMessage = $database->invalidLength('phone', $supplierData['phone'], 40);
        if($checkMessage){
            $data['messages'][] = $checkMessage;
        }
        if(!preg_match('/^([0-9\(\)\/\+ \-]*)$/', $supplierData['phone'])){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'INVALID_NUMBER',
                'key' => 'phone'
            ];
        }
        $checkMessage = $database->isEmpty('mail', $supplierData['mail']);
        if($checkMessage){
            $data['messages'][] = $checkMessage;
        }
        $checkMessage =  $database->invalidLength('mail', $supplierData['mail'], 200);
        if($checkMessage){
            $data['messages'][] = $checkMessage;
        }
        if(!filter_var( $supplierData['mail'], FILTER_VALIDATE_EMAIL)){
            $data['messages'][] = [
                    'code' => 'error',
                    'message' => 'INVALID_MAIL',
                    'key' => 'mail'
            ];
        }

        return $data;
    }

    /**
     * eddit supplier
     * @param  HashArray $supplierData supplier data input
     * @return Array               update message
     */
    public function editSupplier($supplierData){
        global $database;
        $affectedRows = 0;

        foreach ($supplierData as $key => $value) {
            $supplierData[$key] = $database->escapeValue($value);
        }
        $data = $this->validateSupplierData($supplierData, 'edit');

        if(!empty($data)){
            return $data;
        }

        $sql = "UPDATE ".TABLES['suppliers']."
                SET name='".$supplierData['name']."',
                phone='".$supplierData['phone']."'
                WHERE id='".$supplierData['idSupplier']."'
                LIMIT 1";
        $query = $database->query($sql);
        $affectedRows = $database->affectedRows();

        $sql = "UPDATE ".TABLES['users']."
                SET mail='".$supplierData['mail']."'
                WHERE id=(
                    SELECT idUser
                        FROM ".TABLES['suppliers']."
                    WHERE id = ".$supplierData['idSupplier']."
                    )";
        $query = $database->query($sql);
        $affectedRows += $database->affectedRows();

        if($affectedRows < 1){
            $data['messages'][] = [
                'code' => 'warning',
                'message' => 'NO_CHANGES'
            ];

            return $data;
        }

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

        return $data;
    }

    /**
     * add new product
     * @param HashArray $productData product data input
     * @return Array insert message
     */
    public function addSupplierProduct($productData){
        return $this->suppliersProducts->addSupplierProduct($productData);
    }

    /**
     * edit product data
     * @param  HashArray $productData product data input
     * @return Array             update message
     */
    public function editSupplierProduct($productData){
        return $this->suppliersProducts->editSupplierProduct($productData);
    }

    /**
     * @return Array id and name of the available product categories
     */
    public function getProductCategories() {
        return $this->suppliersProducts->getProductCategories();
    }

    /**
     * upload document for a product
     * @param  INT $idDocumentType     id for document type
     * @param  INT $idSupplierProduct id for product
     * @param  String $documentName    name for the document
     * @param  INT $visibleToCustomer  document will be visible for customer
     * @param  FILE $file              file to be uploaded
     * @return ARRAY                  upload message
     */
    public function uploadProductDocument($idDocumentType, $idSupplierProduct, $documentName, $visibleToCustomer, $file) {
        return $this->suppliersProducts->uploadProductDocument($idDocumentType, $idSupplierProduct, $documentName, $visibleToCustomer, $file);
    }

    /**
     * remove product documents
     * @param  INT $idDocument  id for document
     * @return Array            update message
     */
    public function removeProductDocument($idDocument){
        return $this->suppliersProducts->removeProductDocument($idDocument);
    }

}
?>
