<?php 
namespace PortalPeople\magento\controllers;

use PhpParser\Node\Stmt\Expression;
use Yii;
use yii\web\Controller;


class MagentoController extends Controller
{
    public function actionOrders()
    {
        $searchModel = new \backend\models\Cartsbesearch();
        $searchModel->account_code = 'GAR001';
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('@backend/views/cart/index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    public function actionProducts()
    {
        $searchModel = new \backend\models\Productsbesearch();
        $searchModel->magento_enabled = true;
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('@backend/views/products/index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
    /**
     * Sync all price1 fields to Magento for products in the same set as actionProducts
     */
    public function actionSyncAllPrice1()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        
        $magento_enabled = new yii\db\Expression("json_value(data, '$.magento.enabled')");
        $products = \backend\models\Productsbe::find()->where(['=', $magento_enabled, 1]);
        Yii::warning($products->count(), 'magento-sync');
        $syncComponent = Yii::$app->magentoSync ?? null;
        if (!$syncComponent) {
            return ['success' => false, 'message' => 'Magento sync component not configured'];
            }
            
            $successCount = 0;
            $failCount = 0;
        foreach ($products->each() as $product) {
            Yii::warning($product->price1, 'magento-sync');
            if (!isset($product->price1)) {
                continue;
            }

            $result = $syncComponent->syncPrice1($product);
            Yii::warning($product->stock_code . ' price1 sync result: ' . ($result ? 'success' : 'failure'), 'magento-sync');
            if ($result) {
                $successCount++;
            } else {
                $failCount++;
            }
        }

        return [
            'success' => $failCount === 0,
            'message' => "Synced $successCount products to Magento. " . ($failCount ? "$failCount failed." : "")
        ];
    }
}