<?php

declare(strict_types=1);

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\web\HttpException;

use app\models\Product;

class ProductController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index'],
                        'roles' => ['@']
                    ],
                    [
                        'allow' => false,
                        'roles' => ['?']
                    ],
                ]
            ]
        ];
    }

    public function actionIndex(string $catn)
    {
        if ($model = Product::searchByCatn($catn)) {
            // Товар найден

            // Инициализация
            $model = $model->getAttributes();

            if (Yii::$app->request->isAjax) {
                // AJAX-POST-запрос

                Yii::$app->response->format = Response::FORMAT_JSON;

                return [
                    'main' => $this->renderPartial('index', compact('model')),
                    'redirect' => '/product/' . $catn,
                    '_csrf' => Yii::$app->request->getCsrfToken()
                ];
            }

            return $this->render('index', compact('model'));
        } else {
            throw new HttpException(404);
        }
    }
}
