<?php

namespace PortalPeople\qvc\controllers;

use PortalPeople\qvc\components\CsvParser;
use PortalPeople\qvc\components\QvcImportService;
use Yii;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\web\UploadedFile;

class QvcController extends Controller
{
    private const SESSION_PREVIEW_KEY  = 'qvc_order_import_preview';
    private const SESSION_CSV_KEY      = 'qvc_csv_upload';
    private const SESSION_MAPPING_KEY  = 'qvc_csv_mapping';

    public function actionUploader()
    {
        $previewData = Yii::$app->session->get(self::SESSION_PREVIEW_KEY, []);
        $error = null;
        $parser = new CsvParser();
        $importService = new QvcImportService();

        if (Yii::$app->request->isPost) {
            $file = UploadedFile::getInstanceByName('order-csv-file');

            if ($file === null) {
                $error = 'Please select a CSV file.';
            } elseif (strtolower($file->extension) !== 'csv') {
                $error = 'Only CSV files are supported.';
            } else {
                $parseResult = $parser->parseCsvFile($file->tempName);
                if ($parseResult['error'] !== null) {
                    $error = $parseResult['error'];
                } else {
                    $conversion = $importService->convertRowsToOrders($parseResult['rows']);
                    $previewData = [
                        'fileName' => $file->name,
                        'headers' => $parseResult['headers'],
                        'summary' => $importService->buildSummary($conversion['orders'], $conversion['skippedRows']),
                        'orders' => $conversion['orders'],
                        'skippedRows' => $conversion['skippedRows'],
                        'createdAt' => date('c'),
                    ];
                    Yii::$app->session->set(self::SESSION_PREVIEW_KEY, $previewData);
                }
            }
        }

        return $this->render('uploader', [
            'previewData' => $previewData,
            'error' => $error,
            'importResult' => Yii::$app->session->getFlash('qvc-order-import-result'),
        ]);
    }

    public function actionApproveImport()
    {
        if (!Yii::$app->request->isPost) {
            throw new BadRequestHttpException('Invalid request method.');
        }

        $previewData = Yii::$app->session->get(self::SESSION_PREVIEW_KEY, []);
        if (empty($previewData['orders'])) {
            Yii::$app->session->setFlash('qvc-order-import-result', [
                'success' => false,
                'message' => 'No prepared orders found. Upload and preview a CSV file first.',
            ]);
            return $this->redirect(['uploader']);
        }

        $importResult = (new QvcImportService())->importOrders($previewData['orders']);
        Yii::$app->session->setFlash('qvc-order-import-result', $importResult);

        if ($importResult['success']) {
            Yii::$app->session->remove(self::SESSION_PREVIEW_KEY);
        }

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

    // -------------------------------------------------------------------------
    // CSV Column Mapping Flow (upload → map → preview → import)
    // -------------------------------------------------------------------------

    /**
     * Step 1 — Upload CSV file and capture headers + raw rows for the mapping step.
     */
    public function actionUploadCsv()
    {
        $error = null;
        $parser = new CsvParser();
        $importService = new QvcImportService();

        if (Yii::$app->request->isPost) {
            $file = UploadedFile::getInstanceByName('csv-file');

            if ($file === null) {
                $error = 'Please select a CSV file.';
            } elseif (strtolower($file->extension) !== 'csv') {
                $error = 'Only CSV files are supported.';
            } else {
                $parseResult = $parser->parseCsvFile($file->tempName);
                if ($parseResult['error'] !== null) {
                    $error = $parseResult['error'];
                } else {
                    $csvPayload = [
                        'fileName'  => $file->name,
                        'headers'   => $parseResult['headers'],
                        'rows'      => $parseResult['rows'],
                        'createdAt' => date('c'),
                    ];

                    Yii::$app->session->set(self::SESSION_CSV_KEY, $csvPayload);
                    Yii::$app->session->remove(self::SESSION_MAPPING_KEY);

                    $detectedMap = $importService->detectMappingProfile($parseResult['headers']);
                    if ($detectedMap !== null) {
                        $detectedTargetMapping = $importService->normalizeMappingToTarget($detectedMap['mapping']);
                        Yii::$app->session->set(self::SESSION_MAPPING_KEY, $detectedTargetMapping);

                        $conversion = $importService->convertRowsWithMapping($parseResult['rows'], $detectedTargetMapping);
                        $previewData = [
                            'fileName' => $csvPayload['fileName'],
                            'headers' => $csvPayload['headers'],
                            'summary' => $importService->buildSummary($conversion['orders'], $conversion['skippedRows']),
                            'orders' => $conversion['orders'],
                            'skippedRows' => $conversion['skippedRows'],
                            'createdAt' => date('c'),
                            'mode' => 'mapped',
                            'mapping' => $detectedTargetMapping,
                            'detectedProfile' => $detectedMap['profileName'],
                            'detectedProfileKey' => $detectedMap['profileKey'],
                            'detectedMatchedColumns' => $detectedMap['matchedCount'],
                        ];
                        Yii::$app->session->set(self::SESSION_PREVIEW_KEY, $previewData);

                        Yii::$app->session->setFlash(
                            'qvc-map-detected',
                            sprintf(
                                'Detected mapping profile "%s" (%d matched columns). Please review before import.',
                                $detectedMap['profileName'],
                                $detectedMap['matchedCount']
                            )
                        );

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

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

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

    /**
     * Step 2 — Display column mapping UI; on POST apply the mapping,
     *           build a Cartsbe/Cartlines preview, and store it for
     *           the approval action.
     */
    public function actionMapCsv()
    {
        $csvData = Yii::$app->session->get(self::SESSION_CSV_KEY, []);
        $importService = new QvcImportService();
        $savedMapping = $importService->normalizeMappingToTarget(Yii::$app->session->get(self::SESSION_MAPPING_KEY, []));
        if (empty($savedMapping)) {
            $savedMapping = $importService->normalizeMappingToTarget($importService->loadGlobalMapping());
        }

        if (empty($csvData['headers'])) {
            return $this->redirect(['upload-csv']);
        }

        $error = null;

        if (Yii::$app->request->isPost) {
            $mapping = $importService->normalizeMappingToTarget(Yii::$app->request->post('mapping', []));
            $savedMapping = $mapping;

            // Basic validation: at least one Cartlines qty and one Cartsbe identifier.
            $hasQty = isset($mapping['cartlines.qty'])
                && $mapping['cartlines.qty'] !== ''
                && $mapping['cartlines.qty'] !== '__skip__';
            $hasOrderIdent = false;
            foreach (['cartsbe.ordernumber', 'cartsbe.porderref', 'cartsbe.account_code'] as $target) {
                if (isset($mapping[$target]) && $mapping[$target] !== '' && $mapping[$target] !== '__skip__') {
                    $hasOrderIdent = true;
                    break;
                }
            }

            if (!$hasQty) {
                $error = 'You must map at least one column to Cartlines → Quantity.';
            } elseif (!$hasOrderIdent) {
                $error = 'You must map at least one column to an order identifier (Order Number, PO Reference, or Account Code).';
            } else {
                Yii::$app->session->set(self::SESSION_MAPPING_KEY, $mapping);
                $importService->saveGlobalMapping($mapping);

                // Convert raw rows using the new mapping.
                $conversion = $importService->convertRowsWithMapping($csvData['rows'], $mapping);
                $previewData = [
                    'fileName'   => $csvData['fileName'],
                    'headers'    => $csvData['headers'],
                    'summary'    => $importService->buildSummary($conversion['orders'], $conversion['skippedRows']),
                    'orders'     => $conversion['orders'],
                    'skippedRows'=> $conversion['skippedRows'],
                    'createdAt'  => date('c'),
                    'mode'       => 'mapped',
                    'mapping'    => $mapping,
                ];
                Yii::$app->session->set(self::SESSION_PREVIEW_KEY, $previewData);

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

        return $this->render('map-csv', [
            'headers'        => $csvData['headers'],
            'sampleRows'     => array_slice($csvData['rows'], 0, 3),
            'fileName'       => $csvData['fileName'] ?? '',
            'cartsbeFields'  => QvcImportService::cartsbeFields(),
            'cartlinesFields'=> QvcImportService::cartlinesFields(),
            'savedMapping'   => $savedMapping,
            'error'          => $error,
        ]);
    }

    /**
     * Step 3 — Show mapped preview and allow approval to write to DB.
     */
    public function actionMappedPreview()
    {
        $previewData = Yii::$app->session->get(self::SESSION_PREVIEW_KEY, []);
        if (empty($previewData['mode']) || $previewData['mode'] !== 'mapped') {
            return $this->redirect(['upload-csv']);
        }

        return $this->render('mapped-preview', [
            'previewData'  => $previewData,
            'importResult' => Yii::$app->session->getFlash('qvc-mapped-import-result'),
            'detectedMapMessage' => Yii::$app->session->getFlash('qvc-map-detected'),
        ]);
    }

    /**
     * Step 4 — Approve and write Cartsbe + Cartlines records to the database.
     */
    public function actionApproveMappedImport()
    {
        if (!Yii::$app->request->isPost) {
            throw new BadRequestHttpException('Invalid request method.');
        }

        $previewData = Yii::$app->session->get(self::SESSION_PREVIEW_KEY, []);
        if (empty($previewData['mode']) || $previewData['mode'] !== 'mapped' || empty($previewData['orders'])) {
            Yii::$app->session->setFlash('qvc-mapped-import-result', [
                'success' => false,
                'message' => 'No prepared mapped orders found. Please upload and map a CSV first.',
            ]);
            return $this->redirect(['upload-csv']);
        }

        $importResult = (new QvcImportService())->importMappedOrders($previewData['orders']);
        Yii::$app->session->setFlash('qvc-mapped-import-result', $importResult);

        if ($importResult['success']) {
            Yii::$app->session->remove(self::SESSION_PREVIEW_KEY);
            Yii::$app->session->remove(self::SESSION_CSV_KEY);
            Yii::$app->session->remove(self::SESSION_MAPPING_KEY);
        }

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