<?php

namespace RxConnexionBundle\Repository;

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

        $errors = array();

        $action = $addInventoryPayment_form['action'];

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

            if(empty($addInventoryPayment_form['addInventory']))
                $errors[] = 'Invalid transaction. Please try again.';

            if(empty($addInventoryPayment_form['pay_date']))
                $errors[] = 'Date should not be blank.';

            if(empty($addInventoryPayment_form['type']))
                $errors[] = 'Please select type.';

            if(empty($addInventoryPayment_form['amount']))
                $errors[] = 'Amount should not be blank.';
        }

        return $errors;
    }

    public function ajax_list(array $get, $userData){

        $columns = array(
            array('aip.`pay_date`', "DATE_FORMAT(aip.`pay_date`, '%m/%d/%Y')", 'payDate'),
            array('aip.`type`', 'aip.`type`'),
            array('aip.`amount`', 'aip.`amount`'),
            array('aip.`check_date`', "DATE_FORMAT(aip.`check_date`, '%m/%d/%Y')", 'checkDate'),
            array('aip.`check_no`', 'aip.`check_no`'),
            array('b.`description`', 'b.`description`', 'bank_desc'),
            array('aip.`id`', "aip.`id`"),
            array('ai.`status`', "ai.`status`", 'addInventory_status')
        );
        $asColumns = array();

        $select = "SELECT";
        $from = "FROM `add_inventory_payment` aip";
        $joins = "
            LEFT JOIN `add_inventory` ai ON aip.`add_inventory_id` = ai.`id`
            LEFT JOIN `bank` b ON aip.`bank_id` = b.`id`
        ";
        $sqlWhere = "WHERE aip.`add_inventory_id` = :addInventory_id";
        $groupBy = "";
        $orderBy = "ORDER BY aip.`pay_date` DESC";
        $limit = "";
        $stmtParams = array('addInventory_id' => base64_decode($get['addInventory_id']));

        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();

        /* Data Count */
        $recordsTotal = count($result_count);

        /*
         * Output
         */
        $output = array(
            "draw" => intval($get['draw']),
            "recordsTotal" => $recordsTotal,
            "recordsFiltered" => $recordsTotal,
            "data" => array()
        );

        $hasUpdate = $userData['type'] === 'Super Admin' || in_array('Admin Add Inventory Payment Update', $userData['accesses']);

        $totalPayment = 0;

        foreach($result as $row) {

            $totalPayment += $row['amount'];
            $id = base64_encode($row['id']);

            $values = array(
                $row['payDate'],
                $row['type'],
                number_format($row['amount'], 2),
                $row['checkDate'],
                $row['check_no'],
                $row['bank_desc'],
                $row['addInventory_status'] === 'New' && $hasUpdate ? "<a class='action-button-style href-add-inventory-payment-form' data-action='u' data-id='$id'>Update</a>" : ""
            );

            $output['data'][] = $values;
        }

        $output['data'][] = array(
            '',
            'Total',
            number_format($totalPayment, 2),
            '',
            '',
            '',
            ''
        );

        unset($result);

        return $output;
    }
}
