<?php

namespace App\Services;

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

class FacebookServices
{
	use Notify;

	public static function getMenu($store, $senderId)
	{
		try {
			$url = "https://graph.facebook.com/v2.6/me/messages?access_token=" . $store->messenger_token;
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => json_encode([
					'recipient' => [
						'id' => $senderId
					],
					'message' => [
						'attachment' => [
							'type' => 'template',
							'payload' => [
								'template_type' => 'generic',
								'elements' => [
									[
										'title' => 'Welcome',
										'image_url' => getFile($store->messenger_bot_image_driver, $store->messenger_bot_image),
										'subtitle' => $store->messenger_initiate_message ?? 'Welcome please open menu and order food.',
										'default_action' => [
											'type' => 'web_url',
											'url' => route('public.view', [$senderId, $store->link]),
											'webview_height_ratio' => "tall",
											'webview_share_button' => 'hide',
											'messenger_extensions' => true,
										],
										'buttons' => [
											[
												'type' => 'web_url',
												'url' => route('public.view', [$senderId, $store->link]),
												'title' => "See Menu",
												'messenger_extensions' => true,
												'webview_height_ratio' => "tall",
												'webview_share_button' => 'hide'
											]
										]
									]
								]
							]
						]
					]
				]),
				CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
			]);
			$res = curl_exec($curl);
			$error = curl_error($curl);
			curl_close($curl);

			info($res);
			return !$error ? json_decode($res, true) : false;
		} catch (\Exception $e) {
			return config('bot_error_msg.msg');
		}
	}

	public static function getLastOrder($store, $senderId)
	{
		try {
			$facebookObj = new FacebookServices();
			$order = $facebookObj->lastOrder($senderId, $store);
			$order_text = "";
			if ($order) {
				$params = [
					'amount' => $order->payment_amount,
					'orderNumber' => $order->order_number,
					'currency' => basicControl()->base_currency,
				];
				$order_text = $facebookObj->botCommandText($store, 'lastorder', $params);
			}

			$url = "https://graph.facebook.com/v2.6/me/messages?access_token=" . $store->messenger_token;
			$curl = curl_init();

			if ($order_text == "") {
				curl_setopt_array($curl, [
					CURLOPT_URL => $url,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_POSTFIELDS => json_encode([
						'recipient' => [
							'id' => $senderId
						],
						'messaging_type' => 'RESPONSE',
						'message' => [
							'text' => "You have no order yet"
						],
					]),
					CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
				]);
			} else {
				curl_setopt_array($curl, [
					CURLOPT_URL => $url,
					CURLOPT_RETURNTRANSFER => true,
					CURLOPT_POSTFIELDS => json_encode([
						'recipient' => [
							'id' => $senderId
						],
						'message' => [
							'attachment' => [
								'type' => 'file',
								'payload' => [
									'url' => route('downloadPdf', $order ? $order->id : '0'),
									'is_reusable' => true
								]
							]
						]
					]),
					CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
				]);
			}

			$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 getTotalOrders($store, $senderId)
	{
		try {
			$facebookObj = new FacebookServices();
			$order_text = "You have no order yet";
			$orderCount = $facebookObj->totalOrders($senderId, $store);
			if ($orderCount) {
				$params = [
					'total' => $orderCount,
				];
				$order_text = $facebookObj->botCommandText($store, 'totalorders', $params);
			}

			$url = "https://graph.facebook.com/v2.6/me/messages?access_token=" . $store->messenger_token;
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => json_encode([
					'recipient' => [
						'id' => $senderId
					],
					'messaging_type' => 'RESPONSE',
					'message' => [
						'text' => $order_text
					],
				]),
				CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
			]);
			$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 {
			$facebookObj = new FacebookServices();
			$orderStatus = $facebookObj->lastOrderStatus($senderId, $store);
			$order_text = "You have no order yet";
			if ($orderStatus) {
				$params = [
					'status' => $orderStatus,
				];
				$order_text = $facebookObj->botCommandText($store, 'lastorderstatus', $params);
			}

			$url = "https://graph.facebook.com/v2.6/me/messages?access_token=" . $store->messenger_token;
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => json_encode([
					'recipient' => [
						'id' => $senderId
					],
					'messaging_type' => 'RESPONSE',
					'message' => [
						'text' => $order_text
					],
				]),
				CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
			]);
			$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 {
			$facebookObj = new FacebookServices();
			$totalAmount = $facebookObj->totalorderamount($senderId, $store);
			$order_text = "You have no order yet";
			if ($totalAmount) {
				$params = [
					'amount' => getAmount($totalAmount, 2),
					'currency' => config('basic.base_currency'),
				];
				$order_text = $facebookObj->botCommandText($store, 'totalorderamount', $params);
			}

			$url = "https://graph.facebook.com/v2.6/me/messages?access_token=" . $store->messenger_token;
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => json_encode([
					'recipient' => [
						'id' => $senderId
					],
					'messaging_type' => 'RESPONSE',
					'message' => [
						'text' => $order_text
					],
				]),
				CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
			]);
			$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 {
			$facebookObj = new FacebookServices();
			$orders = $facebookObj->last10transaction($senderId, $store);
			$order_text = "You have no order yet";
			if (count($orders) > 0) {
				$order_text = "";
				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 .= $facebookObj->botCommandText($store, 'last10transaction', $params) . PHP_EOL;
				}
			}

			$url = "https://graph.facebook.com/v2.6/me/messages?access_token=" . $store->messenger_token;
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => json_encode([
					'recipient' => [
						'id' => $senderId
					],
					'messaging_type' => 'RESPONSE',
					'message' => [
						'text' => $order_text
					],
				]),
				CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
			]);
			$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://graph.facebook.com/v2.6/me/messages?access_token=" . $store->messenger_token;
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => json_encode([
					'recipient' => [
						'id' => $senderId
					],
					'messaging_type' => 'RESPONSE',
					'message' => [
						'text' => $text
					],
				]),
				CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
			]);
			$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 {
			$facebookObj = new FacebookServices();
			$url = "https://graph.facebook.com/v2.6/me/messages?access_token=" . $store->messenger_token;
			$params = [
				'orderNumber' => $order->order_number,
			];
			$text = $facebookObj->botCommandText($store, 'orderconfirm', $params);
			$curl = curl_init();
			curl_setopt_array($curl, [
				CURLOPT_URL => $url,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_POSTFIELDS => json_encode([
					'recipient' => [
						'id' => $senderId
					],
					'messaging_type' => 'RESPONSE',
					'message' => [
						'text' => $text
					],
				]),
				CURLOPT_HTTPHEADER => ['Content-Type:application/json'],
			]);
			$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::select(['order_number', 'created_at', 'payment_amount'])->where('store_id', $store->id)->where('status', 1)
			->where('sender_id', $senderId)
			->orderBy('id', 'desc')->take(10)->get();
		return $orders;
	}

	public static function getId($store)
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/v17.0/me?fields=id%2Cname&access_token=' . $store->messenger_token);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');

		$response = curl_exec($ch);

		curl_close($ch);
		$res = json_decode($response);
		if (isset($res) && isset($res->id)) {
			return [
				'status' => 'success',
				'data' => $res->id
			];
		} else {
			return [
				'status' => 'error',
			];
		}
	}

}
