<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $faq_form['action'];

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

//            $faq_formExist = $this->getEntityManager()->getRepository('RxConnexionBundle:FileTypeEntity')
//                ->createQueryBuilder('ep')
//                ->where('ep.id != :id')
//                ->andWhere('ep.description = :description')
//                ->andWhere('ep.isDeleted = 0')
//                ->setParameters(array(
//                    'id' => $fileType_form['id'],
//                    'description' => $fileType_form['description']
//                ))
//                ->getQuery()->getResult();
//
//            if($faq_formExist)
//                $errors[] = 'Description already exist.';

            if(empty($faq_form['description']))
                $errors[] = 'Description should not be blank.';
        }

        return $errors;
    }

    public function ajax_list(array $get){

        $columns = array(
            array('ft.`description`', 'ft.`description`', 'fileTypeDesc'),
            array('f.`description`', 'f.`description`'),
            array('temp_ae.`attachmentFile`', 'temp_ae.`attachmentFile`', 'attachmentFile'),
            array('f.`note`', 'f.`note`'),
            array('f.`id`', "f.`id`")
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `frequently_asked_question` f";
        $joins = "LEFT JOIN `file_type` ft ON ft.`id` = f.`file_type_id`";
        $joins .= "
            LEFT JOIN (
                SELECT
                    ae.`frequently_asked_question_id`,
                    GROUP_CONCAT(CONCAT_WS('~', ae.`id`, ae.`file_desc`, ae.`parsed_file_desc`) SEPARATOR ',' ) AS attachmentFile
                FROM `frequently_asked_question_file` ae
                WHERE ae.`is_deleted` = 0
                GROUP BY ae.`frequently_asked_question_id`
            ) temp_ae ON temp_ae.`frequently_asked_question_id` = f.`id`
        ";
        $sqlWhere = "WHERE f.`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'] . "%";
            }
        }

        /* 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)
        );
    }
}
