<?php

namespace App\Console\Commands;

use App\Models\Logs;
use App\Models\OpOrder;
use App\Models\OpOrderOption;
use App\Models\OpOrderProduct;
use App\Models\OpOrderTotal;
use App\Models\OpProduct;
use App\Models\OpProductOptionValue;
use App\Models\ProjectSettings;
use App\Providers\NebimProvider;
use Config;
use Cron\CronExpression;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Str;

class NebimOrdersSync extends Command {
	/**
	 * The name and signature of the console command.
	 *
	 * @var string
	 */
	protected $signature = 'nebim:order {--projectId=}';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Siparişleri Nebime aktarır.';

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

	/**
	 * Execute the console command.
	 *
	 * @return int
	 */
	public function handle() {
		$projectId = $this->option('projectId');

		$projects = ProjectSettings::all();
		$date = Date::now();

		foreach ($projects as $project) {
			if ($projectId) {
				if ($projectId != $project->id) {
					continue;
				}
			} else {
				$checkExpression = (new CronExpression($project->order_schedule))->isDue($date->toDateTimeString());
				if (!$checkExpression) {
					continue;
				}
			}
			Logs::createLog($project->id, "Transfer of orders to Nebim started.", 0);

			$databaseConfigName = Str::slug($project->project_name);
			Config::set('database.default', $databaseConfigName);

			$nebimProvider = new NebimProvider($project->nebim_url, $project->nebim_database_name, $project->nebim_user_group_code, $project->nebim_username, $project->nebim_password);
			$orders = OpOrder::where('order_status_id', $project->order_status_id)->where('nebim', '=', 0)->get();
			foreach ($orders as $order) {

				/**$email = $order->email . "_" . $project->project_name;
					                 *
					                 * $account = $nebimProvider->getAccountByEmail($email);
					                 *
					                 * if ($account) {
					                 * $customerCode = $account[0]['RetailCustomerCode'];
					                 * } else {
					                 * $account = $nebimProvider->createAccount($order->firstname, $order->lastname, $email, $project->OfficeCode);
					                 * $customerCode = $account['CurrAccCode'];
				*/

				$customerCode = $project->CustomerCode;

				if ($order->payment_code == "kapital_bank") {
					$paymentType = "2";
					$paymentCreditCardTypeCode = "CA";
					$paymentCode = "";
				} elseif ($order->payment_code == "cod") {
					$paymentType = "1";
					$paymentCode = $project->PaymentCode;
					$paymentCreditCardTypeCode = "";
				} else {
					$paymentType = "1";
					$paymentCode = $project->PaymentCode;
					$paymentCreditCardTypeCode = "";
				}

				$i = 0;
				$nebimOrder = [];
				$productInfos = OpOrderProduct::where('order_id', $order->order_id)->get();

				$totalPrice = OpOrderTotal::where('order_id', $order->order_id)->where('code', 'sub_total')->first();
				$discount = OpOrderTotal::where('order_id', $order->order_id)->where('code', 'xfeepro')->first();

				$discountAmount = 0;
				if (!empty($discount->value)) {
					$discountAmount = floatval(str_replace("-", "", $discount->value));
				}

				$shipment = OpOrderTotal::where('order_id', $order->order_id)->where('code', 'shipping')->first();

				$shipmentBarcode = "2007003870195";
				$shipmentprice = 0;
				if ($shipment) {
					$nebimShipment = array("OrderLineID" => null, "UsedBarcode" => "$shipmentBarcode", "PriceVI" => floatval($shipment->value), "LDisRate1" => 0, "Qty1" => 1, "ActualPriceCurrencyCode" => $project->CurrencyCode);
						$shipmentprice = floatval($shipment->value);
				} else {
					$nebimShipment = array("OrderLineID" => null, "UsedBarcode" => $shipmentBarcode, "PriceVI" => 0, "LDisRate1" => 0, "Qty1" => 1, "ActualPriceCurrencyCode" => $project->CurrencyCode);
				}

				foreach ($productInfos as $productInfo) {
					$findVariant = OpOrderOption::where('order_id', $productInfo->order_id)->where('order_product_id', $productInfo->order_product_id)->first();

					if ($findVariant) {
						$getOpProductOptionValue = OpProductOptionValue::where('product_option_value_id', $findVariant->product_option_value_id)->first();
						if ($getOpProductOptionValue) {
							$barcode = $getOpProductOptionValue->ean;
							$productReelPrice = $getOpProductOptionValue->price;
						} else {
							$findProduct = OpProduct::where('model', $productInfo->model)->first();
							$barcode = $findProduct->ean;
							$productReelPrice = $findProduct->price;
						}
					} else {
						$findProduct = OpProduct::where('model', $productInfo->model)->first();
						$barcode = $findProduct->ean;
						$productReelPrice = $findProduct->price;
					}

					$nebimOrder[$i] = array("OrderLineID" => null, "UsedBarcode" => '' . $barcode, "PriceVI" => floatval($productInfo->price), "LDisRate1" => 0, "Qty1" => $productInfo->quantity, "ActualPriceCurrencyCode" => $project->CurrencyCode);
					$i++;
				}

				$priceFix = floatval($order->total - $shipmentprice);

				$description = $order->order_id;

				$lines = [];
				$lines[0] = $nebimShipment;
				$lines = $nebimOrder;

				$nebimData = $nebimProvider->createOrder($project->project_name, $customerCode, $project->OfficeCode, $project->StoreCode, $project->WareHouseCode, $description, $lines, $paymentType, $paymentCode, $project->CurrencyCode, $paymentCreditCardTypeCode, $priceFix, $discountAmount, $project->CompanyCode, $project->Series);
				echo "<hr>";
				print_r($nebimData);
				echo "<hr>";
				if (isset($nebimData['ApplicationID'])) {
					OpOrder::where('order_id', $order->order_id)->update(['nebim' => 1]);
				} else {
					Logs::createLog($project->id, json_encode($nebimData, true), 1);
				}
			}
			Logs::createLog($project->id, "Transfer of orders to Nebim finished.", 0);

		}

		return 0;
	}
}
