<?php

namespace PortalPeople\virtualstock\jobs;

use Yii;
use yii\base\BaseObject;
use common\components\Queue\JobInterface;
use PortalPeople\virtualstock\exceptions\ApiException;
use PortalPeople\virtualstock\exceptions\RateLimitException;
use PortalPeople\virtualstock\Module;
use common\components\Tracing;
use backend\models\{ActionLog, Productsbe};

/**
 * Queue job that runs a VirtualStock order import batch.
 *
 * Push via:
 *   Yii::$app->get($module->queueComponent)->push(new ImportOrderBatchJob([
 *       'limit'   => 100,
 *       'cursor'  => null,
 *       'dryRun'  => false,
 *   ]));
 */
class UpdateStockAuto extends BaseObject implements JobInterface
{
    /**
     * @inheritdoc
     */
    public function execute($queue)
    {
        $json = new yii\db\Expression("JSON_VALUE(data, '$.virtualstock.enabled')");
        $VSProducts = Productsbe::find()
            ->where(['=', $json, true]);
        $module = Yii::$app->getModule('virtualstock');
        if (!($module instanceof Module) || !$module->isConfigured()) {
            return print_r(['success' => false, 'error' => 'VirtualStock module not configured']);
        }
        foreach ($VSProducts->each() as $product) {
            $qty = $product->free_stock;
            $sku = $product->data->virtualstock->supplier_code;
            try{
                $client = new \GuzzleHttp\Client();
                $response = $client->request('PATCH', "https://api.virtualstock.com/api/v4/products/{$sku}/?format=json", [
                    'json' =>  ['data'=>['free_stock' => intval($qty)]],
                    'headers' => [
                        'Authorization' => 'Basic c2Z4LWFocy1yZXN0YXBpOlNvczVfR2V6MSZTZWYw'
                    ]
                ]);
            //    print_r($client);
            $data = $response->getBody();
                echo $data->stock_updated_at; 
                ActionLog::create(['class' => self::class, 'action' => 'update-stock', 'relatedid' => $product->id, 'type' => 'info', 'message' => "VirtualStock - Stock Update Successful for SKU: {$sku} with quantity: {$qty}."]);
            } catch (\GuzzleHttp\Exception\RequestException $ex) {
                ActionLog::create(['class' => self::class, 'action' => 'update-stock', 'relatedid' => $product->id, 'type' => 'error', 'message' => "VirtualStock - Stock Update Failed for SKU: {$sku} with quantity: {$qty}. Error: " . $ex->getMessage()]);
                echo $ex;
            }
            echo "Updated SKU: $sku with quantity: $qty\n";
        }
        Yii::$app->queue
            ->delay(1800)
            ->jobname('ScrewFix - Update Stock')
            ->push(new \PortalPeople\virtualstock\jobs\UpdateStockAuto([]));
    }
}
