<?php

declare(strict_types=1);

namespace PortalPeople\reports\services;

use backend\models\Reportsbe;
use Yii;
use yii\widgets\ActiveForm;

/**
 * ReportsService wraps NGauge_Base Reportsbe model interactions.
 *
 * Note: Reportsbe is resolved from NGauge_Base at runtime via the application
 * autoloader. This module must be installed into a NGauge_Base application.
 */
class ReportsService
{
    /**
     * Build AJAX validation response for a Reportsbe form submission.
     *
     * @return array<string, mixed>
     */
    public function validate(): array
    {
        $model = new Reportsbe();

        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = 'json';
            return ActiveForm::validate($model);
        }

        return [];
    }

    /**
     * Run a named report and return results.
     *
     * @return array<string, mixed>
     */
    public function runReport(): array
    {
        $params = new Reportsbe();
        $params->center = Yii::$app->request->cookies->getValue('center') ?? null;

        if ($params->load(Yii::$app->request->post()) && $params->validate()) {
            $report = $params->report;
            return Reportsbe::$report($params, $params->outputtype);
        }

        Yii::$app->response->statusCode = 400;
        Yii::$app->response->format = 'json';
        return $params->errors;
    }

    /**
     * Run bestsellers report and return model + result for rendering.
     *
     * @return array{model: Reportsbe, result: mixed}
     */
    public function bestsellers(): array
    {
        $model = new Reportsbe();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            return ['model' => $model, 'result' => $model->Bestsellers()];
        }

        if (Yii::$app->request->isAjax) {
            Yii::$app->response->statusCode = 400;
            Yii::$app->response->format = 'json';
        }

        return ['model' => $model, 'result' => null];
    }

    /**
     * Run turnover-by-day report and return model + result for rendering.
     *
     * @return array{model: Reportsbe, result: mixed}
     */
    public function turnoverbyday(): array
    {
        $model = new Reportsbe();

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            return ['model' => $model, 'result' => $model->Turnoverbyday()];
        }

        if (Yii::$app->request->isAjax) {
            Yii::$app->response->statusCode = 400;
            Yii::$app->response->format = 'json';
        }

        return ['model' => $model, 'result' => null];
    }
}
