<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use DB;
use Illuminate\Support\Str;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Order;
use App\Models\OrderProduct;
use Hash;
use Storage;
class CheckoutController extends Controller
{
    public function CheckOutPage($session){
        // $cart =
        $authTokenID = DB::table('personal_access_tokens')->where(['id'=>$session])->select('tokenable_id')->first();
        $userId = null;
        if($authTokenID){
            $userId = DB::table('users')->where(['id'=>$authTokenID->tokenable_id])->select('id','name','company_name','email','phone','address')->first();
            $cartItem = DB::table('carts')->where(['user_id'=>$userId->id])->get();
        }else{
            $cartItem = DB::table('carts')->where(['session_id'=>$session])->get();
        }
        foreach($cartItem as $key=>$c){
            $productCheck = DB::table('products')->where(['code'=>$c->product_code])->select('id')->count();
            if($productCheck > 0){
                $CartMinimumStock[] = DB::table('products')->where(['code'=>$c->product_code])->select('stock')->first();
                $CartMinimumOrder[] = DB::table('products')->where(['code'=>$c->product_code])->select('min_order')->first();
                $productWeight[] = DB::table('products')->where(['code'=>$c->product_code])->select('weight')->first();
            }else{
                $CartMinimumStock[] = DB::table('product_attributes')->where(['sku'=>$c->product_code])->select('stock','product_id')->first();
                $CartMinimumOrder[] = DB::table('products')->where(['id'=>$CartMinimumStock[$key]->product_id])->select('min_order')->first();
                $productWeight[] = DB::table('products')->where(['id'=>$CartMinimumStock[$key]->product_id])->select('weight')->first();
            }
        }
        return response()->json([
            'CartMinimumOrder'=>$CartMinimumOrder,
            'CartMinimumStock'=>$CartMinimumStock,
            'productWeight'=>$productWeight,
            'user'=>$userId,
        ]);
    }
    public function AddOrderCheckout(Request $request, $session){
        // $authTokenID = DB::table('personal_access_tokens')->where(['id'=>$session])->select('tokenable_id')->first();
        // if($authTokenID){
        //     $userId = DB::table('users')->where(['id'=>$authTokenID->tokenable_id])->select('id','due_amount')->first();
        // }else{
        //     $user = new User;
        //     $user->phone = $request->customer_phone_no;
        //     $user->name = $request->customer_name;
        //     $user->email = $request->email;
        //     $user->address = $request->address;
        //     $user->password = Hash::make(Str::random(10));
        //     $user->save();
        //     DB::table('carts')->where(['session_id'=>$session])->update(['user_id'=>$user->id]);
        //     $userId = $user;
        // }
        $userCheck = DB::table('users')->where(['phone'=>$request->customer_phone_no])->count();
        if($userCheck == 0){
            $user = new User;
            $user->phone = $request->customer_phone_no;
            $user->name = $request->customer_name;
            $user->email = $request->email;
            $user->address = $request->address;
            $user->password = Hash::make(Str::random(10));
            $user->save();
            DB::table('carts')->where(['session_id'=>$session])->update(['user_id'=>$user->id]);
            DB::table('compares')->where(['session_id'=>$session])->update(['user_id'=>$user->id]);
            $userId = $user;
        }else{
            $userId =DB::table('users')->where(['phone'=>$request->customer_phone_no])->select('id','due_amount','lat','long')->first();
        }
        $cartTotalPrice = DB::table('carts')->where(['user_id'=>$userId->id])->sum('total_price');
        $order = new Order;
        $order->order_type = 'customers';
        $order->order_type = 'users';
        $order->user_id = $userId->id;
        $order->customer_phone_no = $request->customer_phone_no;
        $order->customer_name = $request->customer_name;
        $order->sub_amount = $cartTotalPrice;
        $requestVat = DB::table('settings')->select('vat')->first();
        $order->vat = $cartTotalPrice*($requestVat->vat*(1/100));
        $order->shipping_charge = $request->shipping;
        $order->total_amount = ($order->sub_amount)+$order->shipping_charge;
        $order->created_by = $userId->id;
        $order->method = $request->method;
        if($userId->lat && $userId->long){
            $order->lat = $userId->lat;
            $order->long = $userId->long;
        }
        $order->customer_address = $request->address;
        if($userId->due_amount){
            $order->due_amount = $userId->due_amount + $order->total_amount;
        }
        $order->notes = $request->note;
        $order->date_time = Carbon::now()->format('Y-m-d g:i A');
        $order->order_id = 0;
        $order->status = 2;
        $order->save();
        DB::table('orders')->where(['id'=>$order->id])->update(['order_id'=> date('d').''.date('m').''.date('Y').''.$order->id]);
        $cartAll = DB::table('carts')->where(['user_id'=>$userId->id])->select('product_code','product_image','product_name','product_color','product_size','quantity','product_price')->get();
        foreach($cartAll as $key=> $j){
            $manufactureOrderProduct = new OrderProduct;
            $manufactureOrderProduct->order_id =$order->id;
            $manufactureOrderProduct->status = $order->status;
            $manufactureOrderProduct->sku = $j->product_code;
            $manufactureOrderProduct->image = $j->product_image;
            $manufactureOrderProduct->product_name = $j->product_name;
            $manufactureOrderProduct->color = $j->product_color;
            $manufactureOrderProduct->size = $j->product_size;
            $manufactureOrderProduct->quantity = $j->quantity;
            $manufactureOrderProduct->price = $j->product_price;
            $manufactureOrderProduct->total_price = $j->quantity*$j->product_price;
            $manufactureOrderProduct->save();
            
        }
        DB::table('carts')->where(['user_id'=>$userId->id])->delete();
        return response()->json([
            'order'=>$order,
        ]);
    }
    public function OrderSuccessPageData($token, $id){
        $order = DB::table('orders')->where(['id'=>$id])->select('date_time','sub_amount')->first();
        $product = DB::table('order_products')->where(['order_id'=>$id])->select('product_name','sku','image','size','color','quantity','price','total_price')->get();
        return response()->json([
            'data'=>$product,
            'order'=>$order
        ]);
    }
    public function AutomaticShippingChecking($userId){
        $user_id = DB::table('personal_access_tokens')->where(['id'=>$userId])->select('tokenable_id')->first();
        $userIdddd = DB::table('users')->where(['id'=>$user_id->tokenable_id])->select('lat','long')->first();
        $amount = DB::table('settings')->select('per_kilo_amount')->first();
        $earthRadius = 6371; // KM
        $lat1 = $userIdddd->lat; // User latitude
        $lon1 = $userIdddd->long; // User longitude
        $lat2 = 22.683003; // Destination latitude
        $lon2 = 90.643728; // Destination longitude

        $lat1 = deg2rad($lat1);
        $lon1 = deg2rad($lon1);
        $lat2 = deg2rad($lat2);
        $lon2 = deg2rad($lon2);

        $latDiff = $lat2 - $lat1;
        $lonDiff = $lon2 - $lon1;

        $a = sin($latDiff / 2) * sin($latDiff / 2) +
            cos($lat1) * cos($lat2) *
            sin($lonDiff / 2) * sin($lonDiff / 2);

        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        $kilometres = round($earthRadius * $c, 2);
        return response()->json([
            'amount'=>$kilometres*$amount->per_kilo_amount,
        ]);
    }
}
