<?php

/**
 * Rate Import Controller – GForce Module
 *
 * @category    PortalPeople
 * @package     GForce
 * @author      Portal People Development Team
 * @copyright   Copyright (c) 2026 Portal People (https://portalpeople.co.uk)
 */

namespace PortalPeople\gforce\controllers;

use Yii;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\filters\AccessControl;
use PortalPeople\gforce\components\RateSheetImporter;
use PortalPeople\gforce\models\RateUploadForm;

/**
 * RateImportController
 *
 * Single-step upload of a GForce pricing spreadsheet that creates one
 * Shippingcosts record per individual postcode (no consolidation step).
 */
class RateImportController extends Controller
{
    /** @inheritdoc */
    public function behaviors(): array
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Upload form (GET) and direct import pipeline (POST).
     */
    public function actionIndex(): mixed
    {
        $form = new RateUploadForm();

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

            if ($form->validate()) {
                $ext = $form->priceFile->extension;
                $tmp = tempnam(sys_get_temp_dir(), 'pp_gforce_rate_') . '.' . $ext;

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

                    $importer = new RateSheetImporter();
                    $results  = $importer->import($tmp);

                    return $this->render('result', ['results' => $results]);
                } catch (\Throwable $e) {
                    $form->addError('priceFile', 'Import failed: ' . $e->getMessage());
                    Yii::warning('RateSheetImporter upload failed: ' . $e->getMessage(), __METHOD__);
                } finally {
                    if (file_exists($tmp)) {
                        unlink($tmp);
                    }
                }
            }
        }

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