<?php

namespace App\Console\Commands;

use Config;
use Carbon\Carbon;
use App\Models\Logs;
use App\Models\OpOrder;
use Cron\CronExpression;
use App\Models\OpProduct;
use Illuminate\Support\Str;
use App\Models\OpOrderOption;
use App\Models\OpOrderProduct;
use App\Models\ProjectSettings;
use Illuminate\Console\Command;
use App\Models\OpProductSpecial;
use App\Providers\NebimProvider;
use App\Services\NebimDataService;
use App\Models\IntegrationProducts;
use App\Models\OpProductOptionValue;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\Storage;
use App\Models\IntegrationProductStocks;

class NebimStockAndPriceSync extends Command
{
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'nebim:stock-and-price';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Command description';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	public function handle()
	{
		$project = ProjectSettings::first();
		$date = Date::now();

		$checkExpression = (new CronExpression($project->stock_schedule))->isDue($date->toDateTimeString());
		if (!$checkExpression) {
			return; // Cron ifadesi uygun değilse işlemi sonlandır
		}

		Logs::createLog(1, "Updating stock and price.", 0);

		try {
			$nebimService = new NebimDataService();

			// 1.Servisten fiyatları getir.
			$stockList = $nebimService->fetchStockAndPriceFromNebim();

			foreach ($stockList as $stock) {
				$nebimService->updateOpenCartProductOptionValue($stock['Barcode'], $stock['Inventory'], $stock['ItemDim1Code']);
				$nebimService->updatePrice($stock['Barcode'], $stock['Price1'], $stock['Price2']);
			}

			Logs::createLog(1, "Stock and price updated.", 0);

		} catch (\Exception $e) {
			// Hata oluştuğunda bu blok çalışır
			// Loglama yapabilir veya uygun bir hata mesajı döndürebilirsiniz
			Logs::createLog(1, "Stock and price service error: " . $e->getMessage(), 1);
			return; // Hata durumunda işlemi sonlandır
		}

		return "ok";
	}

}
