<?php

namespace PortalPeople\shippingcosts\controllers;

use Yii;
use PortalPeople\shippingcosts\components\PriceConsolidator;
use PortalPeople\shippingcosts\components\PriceImporter;
use PortalPeople\shippingcosts\models\ColumnMapForm;
use PortalPeople\shippingcosts\models\PriceUploadForm;
use PortalPeople\shippingcosts\models\Shippingcosts;
use PortalPeople\shippingcosts\models\Shippingcostssearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;
use yii\base\Model;

/**
 * ShippingcostsController implements the CRUD actions for Shippingcosts model.
 */
class ShippingcostsController extends Controller
{
    /**
     * Is this used in this Project, Display in Permissions Force 403 if false
     *
        * @var bool
     */
    private $used = true;

    public function behaviors()
    {
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::class,
                'rules' => \common\models\Permissions::getPermissions(self::class),
            ],
            'verbs' => [
                'class' => \yii\filters\VerbFilter::class,
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => yii\web\ErrorAction::class,
            ],
        ];
    }

    /**
     * Lists all Shippingcosts models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new Shippingcostssearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Shippingcosts model.
     * @param string $id
     * @param string $language
     * @return mixed
     */
    public function actionView($id, $language)
    {
        return $this->render('view', [
            'model' => $this->findModel($id, $language),
        ]);
    }

    /**
     * Upload a pricing spreadsheet, consolidate via PriceConsolidator,
     * store the named-array in session, then redirect to actionMap.
     */
    public function actionUpload()
    {
        $uploadForm = new PriceUploadForm();

        if (Yii::$app->request->isPost) {
            $uploadForm->priceFile = UploadedFile::getInstance($uploadForm, 'priceFile');

            if ($uploadForm->validate()) {
                $tmp = tempnam(sys_get_temp_dir(), 'pp_priceupload_') . '.' . $uploadForm->priceFile->extension;

                try {
                    $uploadForm->priceFile->saveAs($tmp);

                    $consolidator = new PriceConsolidator($tmp);
                    $consolidator->load();

                    Yii::$app->session->set('price_upload_rows', $consolidator->toNamedArray());
                    Yii::$app->session->set('price_upload_stats', [
                        'input'   => $consolidator->getInputRowCount(),
                        'output'  => $consolidator->getOutputRowCount(),
                        'merged'  => $consolidator->getMergedRowCount(),
                        'skipped' => $consolidator->getSkippedRowCount(),
                    ]);

                    return $this->redirect(['map']);
                } catch (\Throwable $e) {
                    $uploadForm->addError('priceFile', $e->getMessage());
                    Yii::warning('PriceConsolidator upload failed: ' . $e->getMessage(), __METHOD__);
                } finally {
                    if (file_exists($tmp)) {
                        unlink($tmp);
                    }
                }
            }
        }

        return $this->render('upload', ['uploadForm' => $uploadForm]);
    }

    /**
     * Step 2 – show the column-mapping form.
     * Reads headers from the session rows; on POST stores assignments and redirects to import.
     */
    public function actionMap()
    {
        $rows = Yii::$app->session->get('price_upload_rows', []);
        if (empty($rows)) {
            return $this->redirect(['upload']);
        }

        $headers  = array_keys($rows[0]);
        $mapForm  = new ColumnMapForm();
        $mapForm->headers = $headers;

        if (Yii::$app->request->isPost) {
            if ($mapForm->load(Yii::$app->request->post()) && $mapForm->validate()) {
                Yii::$app->session->set('price_upload_map', $mapForm->assignments);
                return $this->redirect(['import']);
            }
        } else {
            $mapForm->autoAssign();
        }

        return $this->render('map', [
            'mapForm'  => $mapForm,
            'preview'  => array_slice($rows, 0, 3),
            'stats'    => Yii::$app->session->get('price_upload_stats', []),
        ]);
    }

    /**
     * Step 3 – run the import.
     * Reads rows + column assignments from session, creates Shippingcosts records.
     */
    public function actionImport()
    {
        $rows        = Yii::$app->session->get('price_upload_rows', []);
        $assignments = Yii::$app->session->get('price_upload_map',  []);

        if (empty($rows) || empty($assignments)) {
            return $this->redirect(['upload']);
        }

        $results = null;

        try {
            $importer = new PriceImporter($assignments);
            $results  = $importer->import($rows);
        } catch (\Exception $e) {
            Yii::$app->session->setFlash('error', 'Import failed: ' . $e->getMessage());
            Yii::warning('Price import failed: ' . $e->getMessage(), __METHOD__);
        } finally {
            // Always clear session data regardless of outcome
            Yii::$app->session->remove('price_upload_rows');
            Yii::$app->session->remove('price_upload_map');
            Yii::$app->session->remove('price_upload_stats');
        }

        if ($results === null) {
            return $this->redirect(['map']);
        }

        if (!empty($results['errors'])) {
            foreach ($results['errors'] as $entry) {
                Yii::warning(
                    'PriceImporter row error – ' . json_encode($entry['errors'])
                    . ' | row: ' . json_encode($entry['row']),
                    __METHOD__
                );
            }
            Yii::$app->session->setFlash(
                'error',
                count($results['errors']) . ' row(s) failed to import. Please review the column mapping and try again.'
            );
            return $this->redirect(['map']);
        }

        return $this->render('import-result', ['results' => $results]);
    }

    /**
     * Creates a new Shippingcosts model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Shippingcosts();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['update', 'id' => $model->id, 'language' => $model->language]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Shippingcosts model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @param string $language
     * @return mixed
     */
    public function actionUpdate($id, $language)
    {
        $model = $this->findModel($id, $language);
        $pricing = $model->prices;
        if (
                Model::loadMultiple($pricing, Yii::$app->request->post())
                && Model::validateMultiple($pricing)
                && $model->load(Yii::$app->request->post())
                && $model->save()
        ) {
            return $this->redirect(['view', 'id' => $model->id, 'language' => $model->language]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'pricing' => $pricing,
            ]);
        }
    }

    /**
     * Deletes an existing Shippingcosts model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @param string $language
     * @return mixed
     */
    public function actionDelete($id, $language)
    {
        $this->findModel($id, $language)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Shippingcosts model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @param string $language
     * @return Shippingcosts the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id, $language)
    {
        if (($model = Shippingcosts::findOne(['id' => $id, 'language' => $language])) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
