<?php

namespace frontend\controllers;

use Yii;
use common\models\Card;
use backend\models\CardSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\base\Object;
use yii\db\Query;
use common\models\Customer;
use yii\helpers\Json;

/**
 * CardController implements the CRUD actions for Card model.
 */
class CardController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }






    /**
     * Finds the Card model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Card the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Card::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    
    /**
     * Your controller action to fetch the list
     */
    public function actionList($search = null) {
    	$query = new Query();
    
    	$query->select ( [
    			'card.number as number',
    			'customer.name as name',
    			"concat( card.number , case when  customer.name is null then  '' else customer.name end  ) as txt ",
    	] )->from (Card::tableName() )->join("left join", Customer::tableName(), 'card.id_card = customer.id_customer_card')->where ( ' lower(number) LIKE "%' . strtolower ( $search ) . '%"' )->orderBy ( 'number' ) ;
    
    	if ( isset($_GET['onlyFree'])  && $_GET['onlyFree'] == '1'){
    		$query->andWhere( 'customer.id_customer is null' );
    	}
    	
    	$command = $query->createCommand ();
    	$data = $command->queryAll ();
    	$out = [ ];
    	foreach ( $data as $d ) {
    		$out [] = [
    				'number' => $d ['number'],
    				'name' => $d ['name'],
    				'txt' => $d ['txt'],
    		];
    	}
    	echo Json::encode ( $out );
    }
    
    public function actionIndex(){
    	$searchModel = new \common\models\CardSearch();
    	$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
    	
    	return $this->render('index', [
    			'searchModel' => $searchModel,
    			'dataProvider' => $dataProvider,
    	]);
    }
    
    
    
}
