<?php

namespace App\Http\Controllers;

use App\Models\cartview;
use App\Models\mainproducts;
use App\Models\normaluseraddress;
use App\Models\normalusercart;
use App\Models\order;
use App\Models\admin;
use App\Models\shippingcity;
use App\Models\country;
use App\Models\vendor;
use App\Models\coupon;
use App\Models\selectedShippingCities;
use App\Models\dashboardNotification;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use App\Events\orderNotification;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Mail;
use App\Services\NotificationService;
use App\Mail\vendor\newOrder;

class CheckoutController extends Controller
{
    public function checkoutView(Request $request)
    {
        $normalUserCart_UserId = $request->session()->get('userID');
        $websiteID = Session::get('website_id');

        $cartPrice = cartview::select(DB::raw('sum(mainProductsPrice) as mainProductsPrice'))->where(['normalUserCart_UserId' => Session::get('userID'), 'normaluserCart_vendor_id' => Session::get('website_id')])->value('mainProductsPrice');

        $normalUser_id = Session::get('userID');
        $addressData = DB::select("SELECT * FROM normaluseraddress
        INNER JOIN normalusers ON normalusers.normalUser_id = $normalUser_id
        AND normaluseraddress.normaluserAddress_userid = $normalUser_id
        INNER JOIN selected_shipping_cities ON selected_shipping_cities.selected_shipping_city_id = normaluseraddress.normaluserAddress_cityID
        WHERE normaluserAddress_vendor_id = $websiteID
        ");

        if (empty($addressData)) {
            $cartdata = cartview::with('country')->where(['normalUserCart_UserId' => Session::get('userID'), 'normaluserCart_vendor_id' => Session::get('website_id')])->get();

            $cartEquation = 0;
            foreach ($cartdata as $cartdataa) {
                $cartEquation += ($cartdataa->cartitems * $cartdataa->mainProductSale);
            }
            session()->flash('swal_alert', []);

            return view('checkout.checkout')->with(['cartdata' => $cartdata, 'addressData' => $addressData, 'cartPrice' => $cartPrice, 'cartEquation' => $cartEquation, 'noaddresses' => 'noaddresses']);
        } else {
            $cartdata = cartview::with('country')->where(['normalUserCart_UserId' => Session::get('userID'), 'normaluserCart_vendor_id' => Session::get('website_id')])->get();

            $cartEquation = 0;
            foreach ($cartdata as $cartdataa) {
                $cartEquation += ($cartdataa->cartitems * $cartdataa->mainProductSale);
            }

            return view('checkout.checkout')->with(['cartdata' => $cartdata, 'addressData' => $addressData, 'cartPrice' => $cartPrice, 'cartEquation' => $cartEquation]);
        }
    }

    public function shippingPrice(Request $request)
    {
        $addressid = $request->input('addressid');
        $address = normaluseraddress::with(['city'])->where(['normaluserAddress_id' => $addressid, 'normaluserAddress_vendor_id' => Session::get('website_id')])->get();
        return convertCurrency($address[0]->city[0]->selected_shipping_city_Cost, 'EGP', Session::get('currency'));
    }
    public function totalPrice(Request $request)
    {
        $price = $request->input('price');
        $discount = $request->input('discount');
        $shippingPrice = $request->input('shippingPrice');

        return $address = $price - $discount + $shippingPrice;
    }

    public function checkout(Request $request)
    {

        $country = country::where(['country_currency_en' => 'EGP'])->get();
        $normaluserOrders_UserId = $request->session()->get('userID');
        $normaluserOrders_AddressId = $request->input('normaluserOrders_AddressId');
        $normaluserOrders_PaymentMethod = $request->input('normaluserOrders_PaymentMethod');
        $normaluserOrders_Delivery = $request->input('normaluserOrders_Delivery');
        $normaluserOrders_Coupon = $request->input('normaluserOrders_Coupon');
        $normaluserOrders_Price = $request->input('normaluserOrders_Price');
        $normaluserOrders_discount = $request->input('normaluserOrders_discount');

        // Get The Estimated Date
        $GetAddress = normaluseraddress::with('city')->where(['normaluserAddress_id' => $normaluserOrders_AddressId])->get();
        if ($GetAddress[0]->city[0]['selected_shipping_city_DayOrHour'] == 'day') {
            $today = Carbon::now();
            $days = $GetAddress[0]->city[0]['selected_shipping_city_Time'];
            $EstimatedDate = $today->addDays($days);
        } else {
            $today = Carbon::now();
            $Hours = $GetAddress[0]->city[0]['selected_shipping_city_Time'];
            $EstimatedDate = $today->addHours($Hours);
        }

        // Get The Estimated Date

        $insertOrder = order::create([
            'order_userid' => $normaluserOrders_UserId,
            'order_addressid' => $normaluserOrders_AddressId,
            'order_paymentmethod' => $normaluserOrders_PaymentMethod,
            'order_delivery' => $normaluserOrders_Delivery,
            'order_paymentStatus' => $normaluserOrders_PaymentMethod == "0" ? "0" : "1",
            'order_state_id' => "1",
            'order_coupon' => $normaluserOrders_Coupon,
            'order_price' => $normaluserOrders_Price,
            'order_discount' => $normaluserOrders_discount,
            'order_vendor_id' => Session::get('website_id'),
            'order_country_id' => $country[0]->country_id,
            'order_EstimatedDate' => $EstimatedDate,
        ]);

        $orderMaxId = order::max("order_id");

        //   Number of products in the cart "Not The QNT"
        $updateOrderId = normalusercart::where(['normalUserCart_UserId' => $normaluserOrders_UserId, 'normaluserCart_Order' => "0"])
            ->update(['normaluserCart_Order' => $orderMaxId]);


        $products = normalusercart::where('normaluserCart_Order', $orderMaxId)->distinct()->get();


        foreach ($products as $product) {
            $stock = mainproducts::where('mainProductID', $product->normalUserCart_productId)->get();
            $stock =  $stock[0]->mainProductStock;
            $cartStock = normalusercart::where(['normalUserCart_productId' => $product->normalUserCart_productId, 'normaluserCart_Order' => $orderMaxId])->get();
            $cartStock = $cartStock[0]->normaluserCart_OrderQNT;
            json_encode(['products' => $product->normalUserCart_productId]);
            echo  $changeQNT = $stock - 1;
            $updateQNT = mainproducts::select('mainProductStock')->where('mainProductID', $products[0]->normalUserCart_productId)->update([
                'mainProductStock' => $changeQNT
            ]);
        }

        // Coupon
        if ($normaluserOrders_Coupon > 0) {
            $coupon = coupon::where([
                'coupon_id' => Session::get('coupon')['coupon_id']
            ])->decrement('coupon_Count', 1);
            session()->forget('coupon');
        }


        if ($insertOrder) {
            echo json_encode("Insert Order Done");
            $name = \request()->name;
            $admins = admin::where(['admin_vendor_id' => Session::get('website_id')])->get();

            // foreach ($admins as $admin) {
            //     echo  $this->fcmService->sendNotification($admin->admin_token, "طلب جديد", "تم إستلام طلب جديد");
            // }


            // Send Notification To the dashboard

            // Check
            $sendNotificationToTheDashboard = dashboardNotification::create([
                'dashboard_notifications_vendorid' => Session::get('website_id'),
                'dashboard_notifications_title' => "",
                'dashboard_notifications_body' => "",
                'dashboard_notifications_type' => null,
                'dashboard_notifications_seen' => 0,
                'order_id' => $orderMaxId,
            ]);

            // Send Notification To the dashboard

            // Send Email To the vendor
            $vendor = vendor::where(["vendor_id" => Session::get("website_id")])->get();
            Mail::to($vendor[0]->vendor_email)->send(new newOrder($vendor[0]->vendor_name, $vendor[0]->vendor_email));
            // Send Email To the vendor

            // event(new orderNotification($name));
        } else {
            echo json_encode("Insert Order Failed");
        }
    }
    protected $fcmService;

    public function __construct(NotificationService $fcmService)
    {
        $this->fcmService = $fcmService;
    }

    public function orderplaced()
    {
        return view('checkout.orderplaced')->with([]);
    }
}
