<?php

class ClCustomers{
    /**
     * get customers list linked to the commercial lead
     * @return Array    list of customers linked to a commercial lead
     */
    public function getComercialLeadCustomers(){
        global $database, $user;
        $idUser = $user->getUserId();
        $data = [];

        $sql = "SELECT
                    rclc.id as idCustomerInstance,
                    c.name AS customerName,
                    rclc.idOrderType,
                    IF(u.idCompany = clCompany.idCompany, 1, 0) AS isSameCompanyAsCl
                FROM
                    ".TABLES['customers']." c
                INNER JOIN ".TABLES['rel_commercial_lead_customers']." rclc
                  ON rclc.idCustomer=c.id AND isLinkEnabled=1
                INNER JOIN ".TABLES['commercial_leads']." cl
                  ON cl.id=rclc.idCommercialLead
                INNER JOIN ".TABLES['users']." u
                  ON u.id = c.idUser
                INNER JOIN
                  (SELECT
                    us.idCompany,
                    us.id
                  FROM
                    ".TABLES['users']." us
                  WHERE us.id = $idUser) clCompany
                  ON clCompany.id = cl.idUser
                WHERE cl.idUser=$idUser
                 ";
        return $database->fetchResultArray($sql);
    }

    public function getClCustomerInfo($idCommercialLead){
        global $database, $user;
        $idUser = $user->getUserId();
        $data = [];

        $sql = "SELECT
                    rclc.id as idCustomerInstance,
                    c.name AS customerName,
                    c.id AS idCustomer,
                    rclc.idOrderType,
                    IF(u.idCompany = clCompany.idCompany, 1, 0) AS isSameCompanyAsCl
                FROM
                    ".TABLES['customers']." c
                INNER JOIN ".TABLES['rel_commercial_lead_customers']." rclc
                  ON rclc.idCustomer=c.id AND isLinkEnabled=1
                INNER JOIN ".TABLES['commercial_leads']." cl
                  ON cl.id=rclc.idCommercialLead
                INNER JOIN ".TABLES['users']." u
                  ON u.id = c.idUser
                INNER JOIN
                  (SELECT
                    us.idCompany,
                    cl.id
                  FROM
                    ".TABLES['users']." us
                   INNER JOIN ".TABLES['commercial_leads']." cl
                   ON cl.idUser=us.id
                  WHERE cl.id = $idCommercialLead) clCompany
                  ON clCompany.id = cl.id
                WHERE c.idUser=$idUser AND rclc.idCommercialLead=$idCommercialLead";

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

        return $data;
    }
}
