<?php

class Bids {
    public function getBids($filter){
        global $database, $user;
        $data = [];
        $bids = [];
        $pricesHandler = new Prices();
        $interestRate = new InterestRate();
        $supplierBidsHandler = new SupplierBids();
        $interestRateValue = $interestRate->getInterestRate()['interestRate'];
        $interestRateCustomers = $interestRate->getInterestRateForCustomers();

        $supplierBids = $supplierBidsHandler->getLinkedSupplierBids();
        $clSql = "";

        if($user->getUserType() === USER_TYPES['COMMERCIAL_LEAD']){
            $clSql = " AND cl.idUser=".$user->getUserId();
        }

        $sql = "SELECT
                    pb.id AS idBid,
                    pb.bidNumber,
                    pb.idPackage,
                    p.name AS packageName,
                    pb.idCustomerInstance,
                    pb.fixedExtra,
                    pb.recurrentExtra,
                    pb.servicesExtra,
                    c.id AS idCustomer,
                    c.name AS customer,
                    cl.name AS commercialLead,
                    pb.idPaymentType,
                    pt.payType,
                    pt.packagePayPeriod,
                    pt.periodUnit,
                    pb.startDate,
                    pb.endDate,
                    pb.fixedPrice,
                    pb.principalAmount,
                    pb.servicesPrice,
                    CASE WHEN pb.endDate >= NOW() THEN 'available' ELSE 'expired' END AS status,
                    CASE WHEN rop.idBid IS NULL THEN 0 ELSE 1 END AS isUsed
                FROM ".TABLES['packages_bids']." pb
                INNER JOIN ".TABLES['packages']." p
                    ON p.id=pb.idPackage
                INNER JOIN ".TABLES['rel_commercial_lead_customers']." rclc
                    ON rclc.id=pb.idCustomerInstance
                INNER JOIN ".TABLES['customers']." c
                    ON c.id=rclc.idCustomer
                INNER JOIN ".TABLES['commercial_leads']." cl
                    ON cl.id=rclc.idCommercialLead
                INNER JOIN ".TABLES['payment_types']." pt
                    ON pt.id=pb.idPaymentType
                LEFT OUTER JOIN (
                    SELECT DISTINCT idBid
                    FROM ".TABLES['rel_order_packages']."
                ) rop
                    ON rop.idBid=pb.id
                WHERE 1=1 $clSql
                ORDER BY pb.bidNumber DESC";
        $query = $database->query($sql);
        while($row = $database->fetchArray($query)){
            $interestRateCust = $row['idCustomer'] && isset($interestRateCustomers[$row['idCustomer']]) ?
                                floatval($interestRateCustomers[$row['idCustomer']]) :
                                $interestRateValue;
            $row['recurrentPrice'] = $row['packagePayPeriod'] > 0
                ? $pricesHandler->PMT($interestRateCust / 100, $row['packagePayPeriod'], $row['principalAmount'])
                : 0;
            $row['supplierBids'] = isset($supplierBids[$row['idBid']]) ? $supplierBids[$row['idBid']] : [];
            $row['status'] = intval($row['isUsed']) === 1 ? 'used' : $row['status'];
            $bids[] = $row;
        }
        $data['bids'] = $bids;
        $data['userType'] = $user->getUserType();

        return $data;
    }

    private function validateBidData($bid){
        $messages = [];
        $requiredFields = ['idPackage', 'idCustomerInstance', 'idPaymentType', 'startDate', 'endDate', 'fixedPrice', 'principalAmount', 'servicesPrice'];

        foreach ($requiredFields as $field) {
            if(!property_exists($bid , $field)){
                $messages[] = [
                    'code' => 'error',
                    'message' => $field.'_REQUIRED'
                ];

                return $messages;
            }
        }

        return $messages;
    }

    private function linkSupplierBids($idBid, $supplierBids){
        global $database;
        $data = [];

        $sqlValues = "";
        foreach ($supplierBids as $supplierBid) {
            $sqlValues .= "($idBid, ".$supplierBid->idSupplierBid."),";
        }
        $sqlValues = rtrim($sqlValues, ',');

        $sql = "INSERT INTO ".TABLES['rel_bid_supplier_bids']."
        (idBid, idSupplierBid)
        VALUES $sqlValues";
        $query = $database->query($sql);

        if($database->affectedRows() < 1){
            $data['messages'][] =[
                'code' => 'error',
                'message' => 'SUPPLIER_BIDS_NOT_LINKED'
            ];
        }else{
            $data['messages'][] = [
                'code' => 'success',
                'message' => 'SUPPLIER_BIDS_LINKED'
            ];
        }

        return $data;
    }

    public function addBid($bid){
        global $database;

        $bid = json_decode($bid);
        $checkData = $this->validateBidData($bid);

        if(!empty($checkData)){
            $data['messages'] = $checkData;

            return $data;
        }

        $sql = "SELECT MAX(id) as maxBidId FROM ".TABLES['packages_bids']." ";
        $maxVals = $database->fetchResultArray($sql);
        $maxId = !empty($maxVals) ? $maxVals[0]['maxBidId'] : 0;
        $bid->bidNumber = 10000001 + $maxId;

        $sql = "INSERT INTO ".TABLES['packages_bids']."
                (bidNumber, idPackage, idCustomerInstance, idPaymentType, startDate, endDate, fixedPrice, principalAmount, servicesPrice)
                VALUES(
                    '".$bid->bidNumber."',
                    '".$bid->idPackage."',
                    '".$bid->idCustomerInstance."',
                    '".$bid->idPaymentType."',
                    '".$bid->startDate."',
                    '".$bid->endDate."',
                    '".$bid->fixedPrice."',
                    '".$bid->principalAmount."',
                    '".$bid->servicesPrice."'
                    )";

        $query = $database->query($sql);

        if($database->affectedRows() !== 1){
            $data['messages'][] =[
                'code' => 'error',
                'message' => 'SERVER_ERROR'
            ];

            return $data;
        }else{
            $data['messages'][] = [
                'code' => 'success',
                'message' => 'BID_ADDED'
            ];
        }

        $newBidId = $database->getInsertId();

        if(property_exists($bid , 'supplierBids') && !empty($bid->supplierBids)){
            $insrtSupplierBidsMessage =  $this->linkSupplierBids($newBidId, $bid->supplierBids);
            $data['messages'] = array_merge($data['messages'], $insrtSupplierBidsMessage['messages']);
        }

        return $data;
    }

    public function removeBid($idBid){
        global $database;
        $data = [];

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

            return $data;
        }

        $database->beginTransaction();
        $affectedRows = 0;
        $sql = "DELETE FROM ".TABLES['rel_bid_supplier_bids']."
                WHERE idBid=".$database->escapeValue($idBid);
        $query = $database->query($sql);
        $affectedRows = $database->affectedRows();

        $sql = "DELETE FROM ".TABLES['packages_bids']."
            WHERE id=".$database->escapeValue($idBid);
        $query = $database->query($sql);
        $affectedRows += $database->affectedRows();

        if($affectedRows < 1){
            $database->rollback();

            $data['messages'][] =[
                'code' => 'error',
                'message' => 'SERVER_ERROR'
            ];

            return $data;
        }else{
            $database->commit();

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


        return $data;
    }
}
