<?php

class OrderType{
    /**
     * returns all the invoice processes existing in the application
     * @return Array   all the invoice processes from the application
     */
    public function getOrderTypes() {
        global $database;

        $sql = "SELECT
                  id AS idOrderType,
                  name,
                  details
                FROM
                  ".TABLES['order_types'];
        return $database->fetchResultArray($sql);
    }

    /**
     * save Default Order Type
     * @param  INT $defaultIdOrderType id for default order type
     * @return Array                    update message
     */
    public function saveDefaultOrderType($defaultIdOrderType){
        global $database, $user;
        $idUser = $user->getUserId();
        $data = [];
        $defaultIdOrderType = $database->escapeValue($defaultIdOrderType);

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

            return $data;
        }

        $sql = "UPDATE ".TABLES['commercial_leads']."
               SET defaultIdOrderType=$defaultIdOrderType
               WHERE idUser=$idUser";
        $query = $database->query($sql);
        if($database->affectedRows() > 0){
            $data['messages'][] = [
                'code' => 'success',
                'message' => 'DEFAULT_VALUE_UPDATED'
            ];
        }else{
            $data['messages'][] = [
                'code' => 'warning',
                'message' => 'NO_CHANGES'
            ];
        }

         return $data;
    }

    /**
     *  save Customers Order Types
     * @param  Object $customers list of customers containg alos the id for order type
     * @return Array            update message
     */
    public function saveCustomersOrderTypes($customers){
        global $database, $user;
        $idUser = $user->getUserId();
        $data = [];
        $customers = json_decode($customers);
        $idCustomerInstances = [];
        foreach ($customers as $customer) {
            if($customer->idOrderType){
                $idCustomerInstances[] = $database->escapeValue($customer->idCustomerInstance);
            }

        }
        $totalCustomers = count($idCustomerInstances);
        $customerList = $totalCustomers > 0 ? implode($idCustomerInstances, ',') : '0';
        $sql = "SELECT COUNT(rclc.id) AS validCustomers
               FROM ".TABLES['rel_commercial_lead_customers']." rclc
               INNER JOIN ".TABLES['commercial_leads']." cl
                   ON cl.id=rclc.idCommercialLead
               WHERE cl.idUser=$idUser AND rclc.id IN($customerList) ";
        $query = $database->query($sql);
        $row = $database->fetchArray($query);
        if($row['validCustomers'] != $totalCustomers){
            $data['messages'][] = [
                'code' => 'error',
                'message' => 'NOT_AUTHORIZED'
            ];

            return $data;
        }

        $uppdated = 0;
        foreach ($customers as $customer) {
            if($customer->idOrderType){
                $customer->idOrderType = $database->escapeValue($customer->idOrderType);
                $customer->idCustomerInstance = $database->escapeValue($customer->idCustomerInstance);
                $sql = "UPDATE ".TABLES['rel_commercial_lead_customers']."
                       SET idOrderType=".$customer->idOrderType."
                       WHERE id=".$customer->idCustomerInstance;
                $query = $database->query($sql);
                $uppdated += $database->affectedRows($query);
            }
        }

       if($uppdated > 0){
           $data['messages'][] = [
               'code' => 'success',
               'message' => 'ORDER_TYPES_UPDATED'
           ];
       }else{
           $data['messages'][] = [
               'code' => 'warning',
               'message' => 'NO_CHANGES'
           ];
       }

       return $data;
    }

    public function getCLDefaultOrderType(){
        global $database, $user;

        $sql = "SELECT
                   cl.defaultIdOrderType
                 FROM ".TABLES['commercial_leads']." cl
                 WHERE cl.idUser=".$user->getUserId()."
                 LIMIT 1";
        $query = $database->query($sql);
        $row = $database->fetchArray($query);

        return $row['defaultIdOrderType'];
    }
}
