<?php

namespace App\Services;

use App\Models\Order;
use App\Traits\Notify;

class TelegramServices
{
	use Notify;

	public static function getMenu($store, $senderId)
	{
		try {
			$hi_text = $store->telegram_initiate_message ?? "Welcome please open menu and order food.";

			$url = "https://api.telegram.org/bot" . $store->telegram_token . "/sendPhoto";

			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => [
					'chat_id' => $senderId,
					'photo' => getFile($store->telegram_bot_image_driver, $store->telegram_bot_image),
					'caption' => $hi_text,
					'parse_mode' => 'HTML',
					'reply_markup' => json_encode([
						'inline_keyboard' => [
							[
								['text' => "Menu", 'web_app' => ['url' => route('public.view', [$senderId, $store->link, "telegram"])]]
							]
						]
					])
				],
				CURLOPT_HTTPHEADER => ['Content-Type:multipart/form-data'],
			]);
			$res = curl_exec($curl);
			$error = curl_error($curl);
			curl_close($curl);
			return !$error ? json_decode($res, true) : false;
		} catch (\Exception $e) {
			return config('bot_error_msg.msg');
		}
	}

	public static function getLastOrder($store, $senderId)
	{
		try {
			$telegramObj = new TelegramServices();
			$order = $telegramObj->lastOrder($senderId, $store);

			$order_text = "You have no order yet";
			if ($order) {
				$params = [
					'amount' => getAmount($order->payment_amount, 2),
					'orderNumber' => $order->order_number,
					'currency' => config(basicControl()->base_currency),
				];
				$order_text = $telegramObj->botCommandText($store, 'lastorder', $params);
			}

			$url = "https://api.telegram.org/bot" . $store->telegram_token . "/sendDocument";
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => [
					'chat_id' => $senderId,
					'document' => route('downloadPdf', $order ? $order->id : '0'),
					'caption' => $order_text,
					'parse_mode' => 'HTML',
				],
				CURLOPT_HTTPHEADER => ['Content-Type:multipart/form-data'],
			]);
			$res = curl_exec($curl);
			$error = curl_error($curl);
			curl_close($curl);
			info("abc", json_decode($res, true));
			return !$error ? json_decode($res, true) : false;
		} catch (\Exception $e) {
			return config('bot_error_msg.msg');
		}
	}

	public static function getTotalOrders($store, $senderId)
	{
		try {
			$telegramObj = new TelegramServices();
			$orderCount = $telegramObj->totalOrders($senderId, $store);
			$order_text = "You have no order yet";
			if ($orderCount) {
				$params = [
					'total' => $orderCount,
				];
				$order_text = $telegramObj->botCommandText($store, 'totalorders', $params);
			}

			$url = "https://api.telegram.org/bot" . $store->telegram_token . "/sendMessage";
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => [
					'chat_id' => $senderId,
					'text' => $order_text,
					'parse_mode' => 'HTML',
				],
				CURLOPT_HTTPHEADER => ['Content-Type:multipart/form-data'],
			]);
			$res = curl_exec($curl);
			$error = curl_error($curl);
			curl_close($curl);
			return !$error ? json_decode($res, true) : false;
		} catch (\Exception $e) {
			return config('bot_error_msg.msg');
		}
	}

	public static function getLastOrderStatus($store, $senderId)
	{
		try {
			$telegramObj = new TelegramServices();
			$orderStatus = $telegramObj->lastOrderStatus($senderId, $store);
			$order_text = "You have no order yet";
			if ($orderStatus) {
				$params = [
					'status' => $orderStatus,
				];
				$order_text = $telegramObj->botCommandText($store, 'lastorderstatus', $params);
			}
			$url = "https://api.telegram.org/bot" . $store->telegram_token . "/sendMessage";
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => [
					'chat_id' => $senderId,
					'text' => $order_text,
					'parse_mode' => 'HTML',
				],
				CURLOPT_HTTPHEADER => ['Content-Type:multipart/form-data'],
			]);
			$res = curl_exec($curl);
			$error = curl_error($curl);
			curl_close($curl);
			return !$error ? json_decode($res, true) : false;
		} catch (\Exception $e) {
			return config('bot_error_msg.msg');
		}
	}

	public static function getTotalorderAmount($store, $senderId)
	{
		try {
			$telegramObj = new TelegramServices();
			$totalAmount = $telegramObj->totalorderamount($senderId, $store);
			$order_text = "You have no order yet";
			if ($totalAmount) {
				$params = [
					'amount' => getAmount($totalAmount, 2),
					'currency' => basicControl()->base_currency,
				];
				$order_text = $telegramObj->botCommandText($store, 'totalorderamount', $params);
			}
			$url = "https://api.telegram.org/bot" . $store->telegram_token . "/sendMessage";
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => [
					'chat_id' => $senderId,
					'text' => $order_text,
					'parse_mode' => 'HTML',
				],
				CURLOPT_HTTPHEADER => ['Content-Type:multipart/form-data'],
			]);
			$res = curl_exec($curl);
			$error = curl_error($curl);
			curl_close($curl);
			return !$error ? json_decode($res, true) : false;
		} catch (\Exception $e) {
			return config('bot_error_msg.msg');
		}
	}

	public static function getLast10Transaction($store, $senderId)
	{
		try {
			$order_text = "";
			$telegramObj = new TelegramServices();
			$orders = $telegramObj->last10transaction($senderId, $store);
			if ($orders) {
				foreach ($orders as $order) {
					$params = [
						'orderNumber' => $order->order_number,
						'date' => dateTime($order->created_at, 'd/M/Y H:i'),
						'payAmount' => getAmount($order->payment_amount, 2),
						'currency' => basicControl()->base_currency,
					];
					$order_text .= $telegramObj->botCommandText($store, 'last10transaction', $params) . PHP_EOL;
				}
			}
			$url = "https://api.telegram.org/bot" . $store->telegram_token . "/sendMessage";
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => [
					'chat_id' => $senderId,
					'text' => $order_text ?? 'you have no order yet',
					'parse_mode' => 'HTML',
				],
				CURLOPT_HTTPHEADER => ['Content-Type:multipart/form-data'],
			]);
			$res = curl_exec($curl);
			$error = curl_error($curl);
			curl_close($curl);
			return !$error ? json_decode($res, true) : false;
		} catch (\Exception $e) {
			return config('bot_error_msg.msg');
		}
	}

	public static function getHelp($store, $senderId)
	{
		try {
			$text = "/menu - To start the webpage and orders unlimited foods" . PHP_EOL . PHP_EOL;
			$commands = $store->bot_command;
			if ($commands) {
				foreach ($commands as $key => $command) {
					if ($key != 'orderconfirm') {
						$text .= "/" . $key . " - " . $command->description . PHP_EOL . PHP_EOL;
					}
				}
			}
			$url = "https://api.telegram.org/bot" . $store->telegram_token . "/sendMessage";
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => [
					'chat_id' => $senderId,
					'text' => $text ?? "No help found",
					'parse_mode' => 'HTML',
				],
				CURLOPT_HTTPHEADER => ['Content-Type:multipart/form-data'],
			]);
			$res = curl_exec($curl);
			$error = curl_error($curl);
			curl_close($curl);
			return !$error ? json_decode($res, true) : false;
		} catch (\Exception $e) {
			return config('bot_error_msg.msg');
		}
	}

	public static function unrecognized($store, $senderId)
	{
		try {
			$url = "https://api.telegram.org/bot" . $store->telegram_token . "/sendMessage";
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => [
					'chat_id' => $senderId,
					'text' => 'Unrecognized command. Say what? /help for more details',
					'parse_mode' => 'HTML',
				],
				CURLOPT_HTTPHEADER => ['Content-Type:multipart/form-data'],
			]);
			$res = curl_exec($curl);
			$error = curl_error($curl);
			curl_close($curl);
			return !$error ? json_decode($res, true) : false;
		} catch (\Exception $e) {
			return config('bot_error_msg.msg');
		}
	}


	public static function orderConfirm($store, $senderId, $order)
	{
		try {
			$telegramObj = new TelegramServices();
			$url = "https://api.telegram.org/bot" . $store->telegram_token . "/sendMessage";
			$params = [
				'orderNumber' => $order->order_number,
			];
			$order_text = $telegramObj->botCommandText($store, 'orderconfirm', $params);

			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => [
					'chat_id' => $senderId,
					'text' => $order_text,
					'parse_mode' => 'HTML',
				],
				CURLOPT_HTTPHEADER => ['Content-Type:multipart/form-data'],
			]);
			$res = curl_exec($curl);
			$error = curl_error($curl);
			curl_close($curl);
			return !$error ? json_decode($res, true) : false;
		} catch (\Exception $e) {
			return config('bot_error_msg.msg');
		}
	}


	public function lastOrder($senderId, $store)
	{
		$order = Order::where('store_id', $store->id)->where('status', 1)
			->where('sender_id', $senderId)
			->orderBy('id', 'desc')->first();
		return $order;
	}

	public function totalOrders($senderId, $store)
	{
		$order = Order::where('store_id', $store->id)->where('status', 1)
			->where('sender_id', $senderId)
			->orderBy('id', 'desc')->get();
		return count($order);
	}

	public function lastOrderStatus($senderId, $store)
	{
		$order = Order::where('store_id', $store->id)->where('status', 1)
			->where('sender_id', $senderId)
			->orderBy('id', 'desc')->first();
		if ($order) {
			switch ($order->stage) {
				case 0:
					return 'Arrived';
				case 1:
					return 'Delivery Completed';
				case 2:
					return 'In Process';
				case 3:
					return 'Out For Delivery';
				case 4:
					return 'Cancel';
			}

		}
	}

	public function totalorderamount($senderId, $store)
	{
		$order = Order::where('store_id', $store->id)->where('status', 1)
			->where('sender_id', $senderId)
			->sum('payment_amount');
		return $order;
	}

	public function last10transaction($senderId, $store)
	{
		$orders = Order::where('store_id', $store->id)->where('status', 1)
			->where('sender_id', $senderId)
			->orderBy('id', 'desc')->take(10)->get();
		return $orders;
	}
}
