<?php

namespace App\Http\Controllers\Shop;


use session;
use Exception;
use Carbon\Carbon;
use App\Models\User;
use App\Models\Order;
use App\Models\Product;
use App\Models\Customer;
use App\Models\Reseller;
use App\Models\OrderItem;
use App\Models\OrderSource;
use Illuminate\Http\Request;
use App\Models\OrderItemVariant;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Gloudemans\Shoppingcart\Facades\Cart;

class OrderController extends Controller
{
    
    public function order(Request $request)
    {
        $request->validate([
            'mobile_no' => 'required|digits:11',
            'name' => 'required ',
            'address' => 'required'
        ]);

        if (Cart::count() <= 0) {
            return response()->json([
                'status' => 'your cart is empty',
            ]);
        }
        //=======================set variable =============================
        $delivery_charge = 0;
        $discount = 0;
        // =======================================================================
        # Rule of customer create and update.
        # customer buy product with phone number.
        # when customer info is exit then customer info update
        # when customer not exit then create new customer with customer phone number.
        # customer is authentic.
        //========================================================================
        
        DB::beginTransaction();
        try {

            $customer = Customer::where('phone', $request->mobile_no)->first();
            if ($customer) {
                $customer->address = $request->address;
                $customer->name    = $request->name;
                $customer->save();
            }else{
                $customer = new Customer();
                $customer->name = $request->name;
                $customer->phone = $request->mobile_no;
                $customer->password = Hash::make($request->mobile_no);;
                $customer->address = $request->address;
                $customer->status = 1;
                $customer->customer_type = 1;
                $customer->save();
            }

            $total = Cart::total();
           //======================delivery charge===========================
            # set delivery charge if shipping charge have request 
            # other wise session
            //================================================================
            
            $delivery_charge_id = session()->get('shipping')['delivery_charge_id'];
            if($request->shipping_charge_id){
                $location_wise_delivery_charge = DB::table('delivery_charges')->where('id', $request->shipping_charge_id)->first();
                $delivery_charge = $location_wise_delivery_charge->delivery_charge;
            }else{
                if($delivery_charge_id){
                    $location_wise_delivery_charge = DB::table('delivery_charges')->where('id', $delivery_charge_id)->first();
                    $delivery_charge = $location_wise_delivery_charge->delivery_charge;
                } 
            }
            
            //====================coupon check and set discount=============================
            # check coupon
            # check coupon expire date
            # set coupon discount
            //===============================================================================
            
            $coupon_id = session()->get('coupon_id');
            $shipping_charge = session()->get('shipping');
            $coupon = DB::table('coupons')->where('id', $coupon_id)->where('status', 1)->first();
            if($coupon){
                if(Carbon::today()<= $coupon->expire_date){
                    if($coupon->discount_amount > 0){
                        $discount = intval($coupon->discount_amount);
                    }
                }
            }


            //save the order
            $order = new Order();
            $order->customer_id = $customer->id;
            $order->customer_phone = $request->mobile_no;
            $order->invoice_no = 123;
            $order->order_type = 4;
            $order->shipping_cost = $delivery_charge ?? 0;
            $order->regular_shipping_cost = $delivery_charge ?? 0;
            $order->discount = $discount;
            $order->total = $total;
            $order->status = 1;
            $order->save();

            $source = OrderSource::where('is_default', 1)->select('id')->first();
            if (!empty($source)) {
                $order->order_source = $source->id;
            }
            $order->save();

            //inserting order items
            $items = [];
            $profit = 0;
            $total_sale_price = 0;
            foreach (Cart::content() as $cart) {
                $orderItem = OrderItem::create([
                    'order_id' => $order->id,
                    'product_id' => $cart->id,
                    'price' => $cart->price,
                    'quantity' => $cart->qty,
                    'total' => $cart->qty * $cart->price,
                    'admin_sale_price' => $cart->options->original_price,
                ]);


                
                OrderItemVariant::create([
                    'order_item_id' => $orderItem->id,
                    'variant_atribute' => $cart->options->attribute_name ?? null,
                    'variant_name' => $cart->options->variant_name ?? null,
                ]);
                    

                
                $profit += ($cart->price * $cart->qty) - ($cart->options->original_price * $cart->qty);
                $total_sale_price += $cart->options->original_price * $cart->qty;
                
                


                $data = [];
                $data['product_id'] = $cart->id;
                $data['item_id'] = $cart->options->product_code;
                $data['item_name'] = $cart->name;
                $data['affiliation'] = "Google Merchandise Store";
                $data['coupon'] = $coupon != null ? $coupon->code : "";
                $data['discount'] = intval($cart->options->discount);
                $data['index'] = 0;
                $data['item_brand'] = "Google";
                $data['item_category'] = $cart->options->category_name;
                $data['item_category2'] = $cart->options->subcategory_name;
                $data['item_category3'] = $cart->options->sub_subcategory_name;
                $data['item_category4'] = "";
                $data['item_category5'] = "";
                $data['item_list_id'] = "related_products";
                $data['item_list_name'] = "Related Products";
                $data['item_variant'] = $cart->options->variant ?? "";
                $data['location_id'] = "ChIJIQBpAG2ahYAR_6128GcTUEo";
                $data['price'] = intval($cart->price) ?? 0;
                $data['quantity'] = intval($cart->qty) ?? 0;
                array_push($items, $data);
            }
            //---------this 123 is prefix for invoice_no----------------
            $order->profit = $profit;
            $order->total_sale_price = $total_sale_price;
            if (strlen($order->id) > 3) {
                $order->invoice_no = rand(1, 9) . $order->id . rand(1, 9);
            } else if (strlen($order->id) > 2) {
                $order->invoice_no = rand(11, 99) . $order->id . rand(1, 9);
            } else if (strlen($order->id) > 1) {
                $order->invoice_no = rand(11, 99) . $order->id . rand(11, 99);
            } else {
                $order->invoice_no = rand(111, 999) . $order->id . rand(11, 99);
            }
            $order->reseller_id = $request->reseller_id;

            $order->save();
            
            Auth::guard('customer')->loginUsingId($customer->id);
            DB::commit();
           
            return response()->json([
                'status' => true,
                'items' => $items,
                'transaction_id' => $order->invoice_no,
                'invoice_no' => $order->invoice_no,
                'shipping' => $order->shipping_cost,
                'coupon' => $coupon->code ?? "",
                'message' => 'order successfully',
            ]);

           
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json([
                'success' => false,
                'message' => $e->getMessage(),
            ]);
        }
    }


    public function showOrderSuccess($username,$invoice_no){
        $order = Order::with(['orderItem'])->where('invoice_no', $invoice_no)->first();
        $resellers = Reseller::where('username', $username)->first();
        $pages = DB::table('pages')->where('reseller_id', $resellers->id)->get();
        $data = [
            'order'     => $order,
            'pages'     => $pages,
            'resellers' => $resellers,
        ];
        return view('shop.pages.order_success', $data);
    }
    
    public function index($username){
        $resellers = Reseller::where('username', $username)->first();
        $pages = DB::table('pages')->where('reseller_id', $resellers->id)->get();
        return view('shop.pages.order_tracking', compact('resellers','pages'));
    }

    public function orderTrack(Request $request){
        
        $data = $request->validate([
            'invoice_no' => 'required',
        ]);
        
        $order = Order::with(['customer:id,name,phone,address','courier:id,name,status','reseller:id,name,address,phone,email'])->select('id','invoice_no','customer_id','courier_id','status','customer_phone','total','reseller_id','created_at')->where('invoice_no', $request->invoice_no)->first();
            if (!empty($order)) {
                $order_status = '' ;
                switch ($order->status) {
                    case 1:
                        $order_status .= 'New';
                       break;
                    case 2:
                        $order_status .= 'Pending';
                       break;
    
                    case 3:
                        $order_status .= 'Approved';
                       break;
    
                    case 4:
                        $order_status .= 'Shipment';
                       break;
    
                    case 5:
                        $order_status .= ' Delivered';
                       break;
    
                    case 6:
                        $order_status .= 'Cancel';
                       break;
    
                    case 7:
                        $order_status .= 'Return';
                       break;

                    case 8:
                        $order_status .= 'Packaging Ready';
                        break;
        
                    default:
                        $order_status .= 'Unknown Order';
                        break;
                }
               return response()->json([
                   'status' => true,
                   'message' => 'order find successfully',
                   'courier_name' => @$order->courier->name ?? "",
                   'data' => view('shop.components.order_tracking_content',compact('order','order_status'))->render(),
               ]);
            } else {
               return response()->json([
                'status' => false,
                'message' => 'Unknown Order',
               ]);
            }
    }
}
