<?php

class InterestRate{
    const SYSTEM_FINANCING_RATE_ID = 1;

    /**
     * get interest rate
     * @return HashArray interest rate value
     */
    public function getInterestRate(){
        global $database;
        $data = [];
        $sql = "SELECT
                    f.interestRate
                FROM ".TABLES['financing']." f
                WHERE f.id=".self::SYSTEM_FINANCING_RATE_ID;
        $query = $database->query($sql);
        $row = $database->fetchArray($query);
        $data['interestRate'] = isset($row['interestRate']) ? $row['interestRate'] : 0;

        return $data;
    }

    /**
     * get interest rate for each customer
     * @param Int $idCustomer the id of the customer for which to take the inters rate for
     * @return HashArray interest rate value for every customer or specific customer in the system
     */
    public function getInterestRateForCustomers($idCustomer = 0){
        global $database;
        $data = [];
        $interestRate = $this->getInterestRate()['interestRate'];
        $whereSql = $idCustomer ? "WHERE rcd.idCustomer=".$idCustomer : '';

        $sql = "SELECT
                  rcd.discount,
                  rcd.idCustomer
                FROM
                  ".TABLES['rel_customer_discount']." rcd
                $whereSql";
        $query = $database->query($sql);
        while($row = $database->fetchArray($query)) {
            $data[$row['idCustomer']] = $interestRate - $row['discount'];
        }

        return $idCustomer && isset($data[$idCustomer]) ? $data[$idCustomer] : $data;
    }

    /**
     * save interest rate
     * @param  Float $interestRateValue interest rate value
     * @return Array                    update message
     */
    public function saveInterestRate($interestRate){
        global $database;
        $interestRate = $database->escapeValue($interestRate);
        $data = [];

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

            return $data;
        }

        $checkMessage = $database->invalidNumber('interestRate', $interestRate, 0, 100);
        if($checkMessage){
            $data['messages'][] = $checkMessage;
        }

        $sql = "UPDATE ".TABLES['financing']."
                SET interestRate = $interestRate
                WHERE id=".self::SYSTEM_FINANCING_RATE_ID;
        $query = $database->query($sql);

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

        return $data;
    }

    /**
     * get customers discounts
     * @return HashArray interest rate value
     */
    public function getCustomersAndDiscount() {
        global $database;
        $data = $this->getInterestRate();

        $sql = "SELECT
                  c.id AS idCustomer,
                  c.name,
                  IFNULL(rcd.discount, 0) AS discount
                FROM
                  ".TABLES['customers']." c
                  LEFT JOIN ".TABLES['rel_customer_discount']." rcd
                    ON c.id = rcd.idCustomer
                ORDER BY c.name";
        $data['customers'] = $database->fetchResultArray($sql);

        return $data;
    }

    /**
     * save discount for customer - financing
     * @param  Array $details  id of the customer and the discount applied for each
     * @return Array             update message
     */
    public function saveCustomersDiscount($details) {
        global $database;
        $interestRate = $this->getInterestRate()['interestRate'];
        $insertValues = '';
        $affectedRows = 0;
        $data = [];

        if(!count($details)) {
            $data['messages'][] = [
                'code' => 'warning',
                'message' => 'CUSTOMERS_DISCOUNT_EMPTY'
            ];

            return $data;
        }

        foreach($details as $customerDiscounts) {
            $discount = floatval($customerDiscounts['discount']);
            if($discount > $interestRate || $discount < 0) {
                $data['messages'][] = [
                    'code' => 'error',
                    'message' => 'DISCOUNT_NOT_VALID',
                    'key' => $customerDiscounts['name']
                ];
            } else {
                $sql = "INSERT INTO ".TABLES['rel_customer_discount']."
                            (idCustomer, discount)
                        VALUES (".$customerDiscounts['idCustomer'].", '$discount')
                            ON DUPLICATE KEY
                            UPDATE
                                discount = '$discount'";
                $row = $database->query($sql);
                $affectedRows += $database->affectedRows();
            }
        }

        if($affectedRows) {
            $data['messages'][] = [
                'code' => 'success',
                'message' => 'DISCOUNT_UPDATED'
            ];
        }

        return $data;
    }
}
