<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\Category;
use yii\data\Pagination;
class CategoriesController extends \yii\web\Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['create'],
                'rules' => [
                    [
                        'actions' => ['create'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }
    public function actionCreate()
    {
        $categorie = new Category();
        if ($categorie->load(Yii::$app->request->post())) {
            if ($categorie->validate()) {
               // form inputs are valid, do something here
               //save data
               $categorie->save();
               \Yii::$app->getSession()->setFlash('success', 'Catégorie ajoutée.');
               return $this->redirect('index.php?r=categories');
            }
        }
        return $this->render('create', [
            'categorie' => $categorie,
        ]);
    }

    public function actionIndex()
    {
        //get all categories from database
        $query = Category::find();
        //use pagination
        $pagination = new Pagination([
            'defaultPageSize' => 10,
            'totalCount' => $query->count(),
        ]);
        $categories = $query->orderBy('name')
        ->offset($pagination->offset)
        ->limit($pagination->limit)
        ->all();
        return $this->render('index',[
            'categories' => $categories,
            'pagination'=>$pagination
        ]);
    }

}
