<?php
class DashboardsModel{

    /**
     * get all gadgets in a dashborad
     * @param  INT $idDashboard id of the dashborad
     * @return Array            array of gadgets
     */
    private function getGadgets($idDashboard){
        global $database;

        $sql = "SELECT
                    g.id AS idGadget,
                    g.name,
                    g.module,
                    rdg.position
                FROM ".TABLES['gadgets']." g
                INNER JOIN  ".TABLES['rel_dashboard_gadgets']." rdg
                    ON rdg.idGadget=g.id
                WHERE rdg.idDashboard=$idDashboard
                ORDER by rdg.position";

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

    /**
     * get information to show for dashborad view
     * @param  INT $idDashboard id of the dashborad
     * @return HASHARRAY        dahsborad info
     */
    public function getMyDashboard($idDashboard){
        global $database, $user;
        $data = [];
        $whereSql = $user->getUserType() === USER_TYPES['BROKER']
            ? "(d.idUser=".$user->getUserId()." OR d.visibility='public')"
            : "(d.idUser=".$user->getUserId()." OR (d.visibility='public' AND d.idUserType=".$user->getIdUserType()."))";
        $isOwner = $user->getUserType() === USER_TYPES['BROKER']
            ? "1 AS isOwner"
            : "CASE WHEN d.idUser=".$user->getUserId()." THEN 1 ELSE 0 END AS isOwner";
        $idDashboard = intval($database->escapeValue($idDashboard));
        if($idDashboard !== 0){
            $whereSql .= "AND d.id=$idDashboard";
        }

        $sql = "SELECT d.id AS idDashboard,
                       d.name,
                       $isOwner
                FROM ".TABLES['dashboards']." d
                WHERE $whereSql
                ORDER BY d.lastUpdated DESC
                LIMIT 1";
        $data['info'] = $database->fetchResultArray($sql);
        $data['info'] = isset($data['info'][0]) ? $data['info'][0] : [];
        if(!empty($data['info'])){
            $data['gadgets'] = $this->getGadgets($data['info']['idDashboard']);
        }else{
            return $this->getMyDashboard(0);
        }

        return $data;
    }

    /**
     * get information for next actions gadget
     * @param  Array $filters array of filters to be applied
     * @return Array          array with next actions
     */
    public function getNextActionsInfo($filters, $sortBy){
        global $database, $user;

        $filters = json_decode($filters);
        $whereSql = UtilsModel::setFilterSql($filters);
        $orderBySql = UtilsModel::setOrderBySql($sortBy);
        $data = [];
        if(!$orderBySql){
            $orderBySql = "idOrder DESC";
        }
        if($user->getUserType() === USER_TYPES['BROKER']){
            $sql = "SELECT * FROM(
                    SELECT
                        DISTINCT o.id as  idOrder,
                        o.orderNumber,
                        ps.shortDesc as stepAction,
                        'in-progress' AS status
                    FROM ".TABLES['rel_order_process_step']." rops
                    INNER JOIN ".TABLES['orders']." o
                        ON o.id=rops.idOrder
                    INNER JOIN ".TABLES['rel_process_steps']." rps
                        ON rps.id=rops.idProcessStep
                    INNER JOIN ".TABLES['process_step']." ps
                        ON ps.id=rps.idStep
                    WHERE rops.status='in-progress'
                    ) actions
                    WHERE $whereSql
                    ORDER BY $orderBySql
                    LIMIT 7";

            $data = $database->fetchResultArray($sql);
        }else{
            $sqlTemp= "CREATE TEMPORARY TABLE temp_next_actions AS (
                SELECT * FROM(
                        SELECT
                            o.id as idOrder,
                            o.orderNumber,
                            ps.shortDesc as stepAction,
                            ps.idActionCode
                        FROM ".TABLES['rel_order_process_step']." rops
                        INNER JOIN ".TABLES['orders']." o
                            ON o.id=rops.idOrder
                        INNER JOIN ".TABLES['rel_commercial_lead_customers']." rclc
                            ON rclc.id=o.idCustomerInstance
                        INNER JOIN ".TABLES['customers']." c
                            ON c.id=rclc.idCustomer
                        INNER JOIN ".TABLES['rel_process_steps']." rps
                            ON rps.id=rops.idProcessStep
                        INNER JOIN ".TABLES['process_step']." ps
                            ON ps.id=rps.idStep
                        WHERE c.idUser=" .$user->getUserId(). " AND rops.status='in-progress' AND ps.idActionCode IN(4,6,8)
                        ) actions
                        WHERE $whereSql
                        ORDER BY $orderBySql
                        LIMIT 7
            )";
            $query = $database->query($sqlTemp);

            //questionnaiire validation
            $sql = "SELECT
                        tna.idOrder,
                        tna.orderNumber,
                        tna.stepAction,
                        rod.validation as status
                    FROM temp_next_actions tna
                    INNER JOIN ".TABLES['rel_order_documents']." rod
                        ON rod.idOrder=tna.idOrder
                    WHERE tna.idActionCode=4 AND rod.validation='invalid'";
            $data = $database->fetchResultArray($sql);

            //customer acceptance
            $sql = "SELECT
                        tna.idOrder,
                        tna.orderNumber,
                        tna.stepAction,
                        'not-accepted' as status
                    FROM temp_next_actions tna
                    INNER JOIN ".TABLES['rel_order_packages']." rop
                        ON rop.idOrder=tna.idOrder
                    WHERE tna.idActionCode=6 AND rop.customerAccepted=0";
            $data = array_merge($data, $database->fetchResultArray($sql) );

            //schedule meeting
            $sql = "SELECT
                        DISTINCT tna.idOrder,
                        tna.orderNumber,
                        tna.stepAction,
                        'pending' as status
                    FROM temp_next_actions tna
                    INNER JOIN ".TABLES['rel_order_scheduled_dates']." rosd
                        ON rosd.idOrder=tna.idOrder
                    WHERE tna.idActionCode=8 AND rosd.isDateConfirmed=0";
            $data = array_merge($data, $database->fetchResultArray($sql) );

            $delSql = "DROP TABLE temp_next_actions";
            $query = $database->query($delSql);
        }

        return $data;
    }

    /**
     * get information for the order central gadget
     * @param  Bool $viewAllOrders  true if the user is company admin and checks the view all orders
     * @param  Array $filters array of filters to be applied
     * @return Array          array with orders info
     */
    public function getOrderCentralInfo($viewAllOrders, $filters, $sortBy){
        global $database, $user;

        $filters = json_decode($filters);
        $sortBy = json_decode($sortBy);
        $whereSql = UtilsModel::setFilterSql($filters);
        $orderBySql = UtilsModel::setOrderBySql($sortBy);
        $extraJoin = '';
        $extraWhere = '';
        $extraHeaders = '';
        $countries = new Countries();
        $userType = $user->getUserType();
        $data = [];
        $idUser = $user->getUserId();

        if(!$orderBySql){
            $orderBySql = "idOrder DESC";
        }

        if($userType === USER_TYPES['BROKER']) {
            $extraWhere = "AND (
                                  b.idUser = $idUser
                                  OR o.assignedTo IS NULL
                              )";
        }

        if($userType === USER_TYPES['CUSTOMER']) {
            $extraJoin = "INNER JOIN ".TABLES['rel_commercial_lead_customers']." rclc
                             ON rclc.id = o.idCustomerInstance
                          INNER JOIN ".TABLES['customers']." c
                             ON rclc.idCustomer = c.id";
            if($viewAllOrders === 'true') {
                $extraHeaders = "c.name AS placedBy,";
                $extraJoin .= " INNER JOIN ".TABLES['users']." u
                                  ON u.id = c.idUser
                                INNER JOIN ".TABLES['users']." uc
                                  ON uc.idCompany = u.idCompany
                                  AND uc.id = $idUser";
            } else {
                $extraJoin .= " AND c.idUser = $idUser";
            }
        }

        if($userType === USER_TYPES['COMMERCIAL_LEAD']) {
            $extraJoin = "INNER JOIN ".TABLES['rel_commercial_lead_customers']." rclc
                             ON rclc.id = o.idCustomerInstance
                             INNER JOIN ".TABLES['commercial_leads']." cl
                                ON rclc.idCommercialLead = cl.id";
            if($viewAllOrders === 'true') {
                $extraHeaders = "cl.name AS placedBy,";
                $extraJoin .= " INNER JOIN ".TABLES['users']." u
                                  ON u.id = cl.idUser
                                INNER JOIN ".TABLES['users']." ucl
                                  ON ucl.idCompany = u.idCompany
                                  AND ucl.id = $idUser";
            } else {
                $extraJoin .= " AND cl.idUser = $idUser";
            }
        }

        if($userType === USER_TYPES['SUPPLIER']) {
            $extraJoin = "INNER JOIN ".TABLES['rel_package_products']." rpp
                            ON rpp.idPackage=rop.idPackage AND rop.packageInstance=rpp.packageInstance
                        INNER JOIN ".TABLES['suppliers_countries_products']." scp
                            ON scp.idProduct=rpp.idProduct
                        INNER JOIN ".TABLES['suppliers']." s
                            ON s.id=scp.idSupplier
                            AND s.idUser = $idUser";
        }

        $sql = "SELECT * FROM(
                    SELECT o.id AS idOrder,
                    o.orderNumber,
                    $extraHeaders
                    DATE_FORMAT(o.orderDate, '%D %b, %Y') AS orderDate,
                    o.reference,
                    IF(b.name IS NULL, 'unassigned', b.name) AS assignedTo,
                    SUM(rop.packageFixedPrice * rop.units) AS fixedPrice,
                    SUM((rop.packageRecuringPrice * rop.units) + (rop.packageServicePrice * rop.units)) AS recurringPrice,
                    o.status
                    FROM ".TABLES['orders']." o
                    INNER JOIN ".TABLES['rel_order_packages']." rop
                        ON rop.idOrder=o.id
                    $extraJoin
                    LEFT JOIN ".TABLES['brokers']." b
                        ON o.assignedTo = b.id
                    WHERE o.status!='production' AND o.status!='canceled' AND o.status!='end-of-life'
                        $extraWhere
                    GROUP BY o.id
                ) orders
                WHERE $whereSql
                ORDER BY $orderBySql
                LIMIT 5";
        $query = $database->query($sql);
        while($row = $database->fetchArray($query)){
            $row['currency'] = $countries->getCurrencyForOrder($row['idOrder']);
            $data[] = $row;
        }

        return $data;
    }

}
?>
