<?php

namespace RxConnexionBundle\Repository;

/**
 * AccountUserRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class AccountUserRepository extends \Doctrine\ORM\EntityRepository
{
    public function validate($accountUser_form) {

        $errors = array();

        $action = $accountUser_form['action'];


        // d = delete
        if($action !== 'd') {

            $accountUserExist = $this->getEntityManager()->getRepository('RxConnexionBundle:AccountUserEntity')
                ->createQueryBuilder('ep')
                ->where('ep.id != :id')
                ->andWhere('ep.isDeleted != :isDeleted')
                ->andWhere('ep.username = :username')
                ->setParameters(array(
                    'id' => $accountUser_form['id'],
                    'isDeleted' => 1,
                    'username' => $accountUser_form['username']
                ))
                ->getQuery()->getResult();

            if($accountUserExist)
                $errors[] = 'Username already exist.';

            if(empty($accountUser_form['username'])) {
                $errors[] = 'Username should not be blank.';
            } else {

                if(!preg_match("/^[a-zA-Z0-9]+$/", $accountUser_form['username'])) {
                    $errors[] = 'Username must not contain any special character/spaces.';
                }

                if(strlen($accountUser_form['username']) < 3) {
                    $errors[] = 'Username must be at least 3 characters.';
                }
            }

            if($action === 'n' && empty($accountUser_form['password']['first']) && empty($accountUser_form['password']['second'])) {
                $errors[] = 'Please enter your password.';
            } else if($accountUser_form['password']['first'] !== $accountUser_form['password']['second']) {
                $errors[] = 'Password does not match.';
            }

            if(empty($accountUser_form['first_name'])) {
                $errors[] = 'First name should not be blank.';
            }

            if(empty($accountUser_form['last_name'])) {
                $errors[] = 'Last name should not be blank.';
            }
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('a.`description`', 'a.`description`', 'account_desc'),
            array('cr.`description`', 'cr.`description`', 'account_user_type_desc'),
            array('c.`username`', 'c.`username`'),
            array('c.`full_name`', 'c.`full_name`'),
            array('c.`is_active`', 'c.`is_active`'),
            array('c.`id`', "c.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `account_user` c";
        $joins = "LEFT JOIN `account_user_type` cr ON c.`account_user_type_id` = cr.`id`";
        $joins .= " LEFT JOIN `account` a ON cr.`account_id` = a.`id`";
        $sqlWhere = "WHERE c.`is_deleted` = 0";
        $groupBy = "";
        $orderBy = "";
        $limit = "";
        $stmtParams = array();

        foreach($columns as $key => $column) {
            $select .= ($key > 0 ? ', ' : ' ') . $column[1] . (isset($column[2]) ? ' AS ' . $column[2] : '');
        }

        /*
         * Ordering
         */
        foreach($get['columns'] as $key => $column) {
            if($column['orderable']=='true') {
                if(isSet($get['order'])) {
                    foreach($get['order'] as $order) {
                        if($order['column']==$key) {
                            $orderBy .= (!empty($orderBy) ? ', ' : 'ORDER BY ') . $columns[$key][0] . (!empty($order['dir']) ? ' ' . $order['dir'] : '');
                        }
                    }
                }
            }
        }

        /*
         * Filtering
         */
        if(isset($get['search']) && $get['search']['value'] != ''){
            $aLikes = array();
            foreach($get['columns'] as $key => $column) {
                if($column['searchable']=='true') {
                    $aLikes[] = $columns[$key][0] . ' LIKE :searchValue';
                }
            }
            foreach($asColumns as $asColumn) {
                $aLikes[] = $asColumn . ' LIKE :searchValue';
            }
            if(count($aLikes)) {
                $sqlWhere .= (!empty($sqlWhere) ? ' AND ' : 'WHERE ') . '(' . implode(' OR ', $aLikes) . ')';
                $stmtParams['searchValue'] = "%" . $get['search']['value'] . "%";
            }
        }
        if($get['status']){
            if($get['status'] == 1) {
                $status = 1;
            } else {
                $status = 0;
            }

            $sqlWhere .= (!empty($sqlWhere) ? ' AND ' : 'WHERE ') . 'c.`is_active` = :status';
            $stmtParams['status'] = $status;
        }

        /* Set Limit and Length */
        if(isset( $get['start'] ) && $get['length'] != '-1'){
            $limit = 'LIMIT ' . (int)$get['start'] . ',' . (int)$get['length'];
        }

        $sql = "$select $from $joins $sqlWhere $groupBy $orderBy";
        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);
        $result_count = $query->fetchAll();

        $sql = "$select $from $joins $sqlWhere $groupBy $orderBy $limit";
        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);
        $result = $query->fetchAll();

        return array(
            'results' => $result,
            'total' => count($result_count)
        );
    }

    public function moa_autocomplete_suggestions($q) {

        $sql = "
            SELECT
                p.`id`,
                p.`full_name` AS data,
                p.`full_name` AS value
            FROM `account_user` p
            LEFT JOIN `account_user_type` aut ON p.`account_user_type_id` = aut.`id`
            WHERE p.`full_name` LIKE :description
            AND (aut.`description` = 'MOA' OR aut.`description` = 'MOA Manager')
            AND p.`is_deleted` = 0 
            ORDER BY p.`full_name`
            LIMIT 0,20
        ";

        $query = $this->getEntityManager()->getConnection()->prepare($sql);

        $query->execute(array(
            'description' => "%$q%"
        ));

        $result = $query->fetchAll();

        return $result;
    }

    public function autocomplete_suggestions($q) {

        $sql = "
            SELECT
                p.`id`,
                p.`full_name` AS data,
                p.`full_name` AS value
            FROM `account_user` p
            LEFT JOIN `account_user_type` aut ON p.`account_user_type_id` = aut.`id`
            WHERE (p.`full_name` LIKE :description OR 
                    p.`username` LIKE :description OR 
                    p.`first_name` LIKE :description OR 
                    p.`last_name` LIKE :description OR 
                    CONCAT_WS(', ',p.`last_name`, p.`first_name`) LIKE :description OR 
                    CONCAT_WS(' ',p.`first_name`, p.`last_name`) LIKE :description
                    )
            AND p.`is_active` = 1
            AND p.`is_deleted` = 0
            ORDER BY p.`full_name`
            LIMIT 0,20
        ";

        $query = $this->getEntityManager()->getConnection()->prepare($sql);

        $query->execute(array(
            'description' => "%$q%"
        ));

        $result = $query->fetchAll();

        return $result;
    }

    public function getMOAUserType() {

        $conn = $this->getEntityManager()->getConnection();
        $sql = $conn->prepare(
            "
            SELECT
                au.`full_name`,
                au.`id`
            FROM `account_user` au
            LEFT JOIN `account_user_type` aut ON au.`account_user_type_id` = aut.`id`
            WHERE (aut.`description` = 'MOA' OR aut.`description` = 'MOA Manager')
            AND au.`is_deleted` = 0
        "
        );
        $sql->execute();
        return $sql->fetchAll();
    }

    public function reportLoginTracker($params) {
        $sqlWhere = "";
        $stmtParams = array();

        if (!is_null($params['date_from']) && $params['date_from'] !== 'null' && $params['date_from'] !== 'all' && !empty($params['date_from']) && !is_null($params['date_to']) && $params['date_to'] !== 'null' && $params['date_to'] !== 'all' && !empty($params['date_to'])) {
            $sqlWhere .= (empty($sqlWhere) ? "WHERE " : " AND ") . "lr.`start_date` BETWEEN :date_from AND :date_to";
            $stmtParams['date_from'] = date('Y-m-d 00:00:00', strtotime(str_replace('-',  '/', $params['date_from'])));
            $stmtParams['date_to'] = date('Y-m-d 23:59:59', strtotime(str_replace('-', '/', $params['date_to'])));
        }

        if(isset($params['users']) && !empty($params['users']) && 'NULL' !== strtoupper($params['users'])){
            $branches = explode(',' , $params['users']);
            if(count($branches) > 0){
                $hf_ors = '';
                foreach($branches as $key => $branchId){
                    $hf_ors .= (empty($hf_ors) ? '' : ' OR ') . "lr.`account_user_id` = :users_id_$key";
                    $stmtParams["users_id_$key"] = $branchId;
                }
                $sqlWhere .= " AND ($hf_ors) ";
            }
        }

        $sql = "
            SELECT
                au.`username`,
                au.`full_name`,
                DATE_FORMAT(lr.`start_date`, '%Y/%m/%d %r') AS dateLog,
                lr.`note` AS statusLog
            FROM `login_tracker` lr
            LEFT JOIN `account_user` au ON au.`username` = lr.`username` 
            $sqlWhere
            ORDER BY lr.`username` DESC, 
        ";

        $query = $this->getEntityManager()->getConnection()->prepare($sql);
        $query->execute($stmtParams);

        $result = $query->fetchAll();

        return $result;
    }

}
