<?php

declare(strict_types=1);

namespace app\controllers;

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

use app\models\Product;
use app\models\Settings;
use app\models\SupplyEdgeProduct;
use app\models\Supply;
use app\models\Account;
use app\models\Notification;
use app\models\OrderEdgeSupply;

use Exception;

class SupplyController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => [
                            'index',
                        ]
                    ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                        'actions' => []
                    ],
                    [
                        'allow' => true,
                        'actions' => [
                            'read'
                        ],
                        'matchCallback' => function ($rule, $action): bool {
                            if (
                                !yii::$app->user->isGuest
                                && (yii::$app->user->identity->type === 'administrator'
                                    || yii::$app->user->identity->type === 'moderator')
                            ) return true;

                            return false;
                        }
                    ],
                    [
                        'allow' => false,
                        'roles' => ['?'],
                        'denyCallback' => [$this, 'accessDenied']
                    ]
                ]
            ]
        ];
    }

    /**
     * Чтение поставок
     *
     * @param int $page Страница
     *
     * @return string|array|null
     */
    public function actionRead(int $page = 1): string|array|null
    {
        if (yii::$app->request->isPost) {
            // POST-запрос

            // Инициализация входных параметров
            $amount = yii::$app->request->post('amount') ?? yii::$app->request->get('amount') ?? 20;
            $order = yii::$app->request->post('order') ?? yii::$app->request->get('order') ?? ['DESC'];

            // Инициализация cookie
            $cookies = yii::$app->response->cookies;

            // Чтение поставок
            $supplies = Supply::read(limit: $amount, page: $page, order: $order);

            // Запись формата ответа
            yii::$app->response->format = Response::FORMAT_JSON;

            return [
                'supplies' => $this->renderPartial('/supply/list', compact('supplies', 'amount', 'page')),
                '_csrf' => yii::$app->request->getCsrfToken()
            ];
        }

        return false;
    }
}
