<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Cart;
use App\Models\Order;
use App\Models\Shipping;
use App\Models\Invoice;
use App\User;
use PDF;
use Notification;
use Helper;
use Illuminate\Support\Str;
use App\Notifications\StatusNotification;
use DB;

class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $orders=Order::orderBy('id','DESC')->paginate(10);
        return view('backend.order.index')->with('orders',$orders);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request,[
            'first_name' => 'required',
            'last_name' => 'required',
            'email' => 'required',
            'phone' => 'required',
            'country' => 'required',
            'province' => 'required',
            'city' => 'required',
            'address' => 'required',
            'post_code' => 'required',
            'houseNo' => 'required',
            'iossNumber' => 'nullable',
            'cartItems' => 'required',
            'selected' => 'required',
        ]);

        if(empty(Cart::where('user_id',auth()->user()->id)->where('order_id',null)->get())){
            request()->session()->flash('error','Cart is Empty !');
            return back();
        }

        try {
            $order=new Order();
            $order_data=$request->except(['selected']);
            $order_data['order_number']='ORD-'.strtoupper(Str::random(10));
            $order_data['user_id']=$request->user()->id;
            $order_data['quantity']=Helper::cartCount();
            $order_data['status']="new";
            $order->fill($order_data);
            // print_r($order);
            $status=$order->save();
            if($status){
                $selected = $request->selected;
                if(!empty($selected)){
                    $nft = array(
                        'order_id' => $order->id,
                        'token_id' => $selected['tokenId'],
                        'collection_address' => $selected['contract_address'],
                        'collection_name' => $selected['contract_name'],
                        'image' => $selected['image'],
                    );
                    $ordernft = DB::table('ordernft')->insert($nft);
                }
                $carts = $request->cartItems;
                if(!empty($carts)){
                    foreach($carts as $item){
                        $products = array(
                            'order_id' => $order->id,
                            'product_id' => $item['id'],
                            'title' => $item['name'],
                            'size' => $item['selectedSize'],
                            'color' => $item['selectedColor'],
                            'image' => $item['photo'],
                        );
                        $orderProducts = DB::table('orderproducts')->insert($products);
                    }
                }
            }
            // dd($order->id);
            $users=User::where('role','admin')->first();
            $details=[
                'title'=>'New order created',
                'actionURL'=>route('order.show',$order->id),
                'fas'=>'fa-file-alt'
            ];
            Notification::send($users, new StatusNotification($details));
            session()->forget('cart');
            session()->forget('coupon');
            Cart::where('user_id', auth()->user()->id)->where('order_id', null)->update(['order_id' => $order->id]);       
            return response()->json(['status'=>200, 'msg'=>'Your Products successfully placed in order']);

        } catch (\Throwable $th) {
            return response()->json(['status'=>400, 'msg'=>$th]);
        }

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $order=Order::find($id);
        // return $order;
        $orderDetails = DB::table('orderproducts')->where('order_id', $id)->get();
        $nftDetails = DB::table('ordernft')->where('order_id', $id)->first();
        return view('backend.order.show')->with('order',$order)->with('orderDetails',$orderDetails)->with('nftDetails',$nftDetails);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $order=Order::find($id);
        return view('backend.order.edit')->with('order',$order);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $order=Order::find($id);
        $this->validate($request,[
            'status'=>'required|in:new,process,delivered,cancel'
        ]);
        $data=$request->all();
        // return $request->status;
        if($request->status=='delivered'){
            foreach($order->cart as $cart){
                $product=$cart->product;
                // return $product;
                $product->stock -=$cart->quantity;
                $product->save();
            }
        }
        $status=$order->fill($data)->save();
        if($status){
            request()->session()->flash('success','Successfully updated order');
        }
        else{
            request()->session()->flash('error','Error while updating order');
        }
        return redirect()->route('order.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    // public function destroy($id)
    // {
    //     $order=Order::find($id);
    //     if($order){
    //         $status=$order->delete();
    //         if($status){
    //             request()->session()->flash('success','Order Successfully deleted');
    //         }
    //         else{
    //             request()->session()->flash('error','Order can not deleted');
    //         }
    //         return redirect()->route('order.index');
    //     }
    //     else{
    //         request()->session()->flash('error','Order can not found');
    //         return redirect()->back();
    //     }
    // }

    public function orderTrack(){
        return view('frontend.pages.order-track');
    }

    public function productTrackOrder(Request $request){
        // return $request->all();
        $order=Order::where('user_id',auth()->user()->id)->where('order_number',$request->order_number)->first();
        if($order){
            if($order->status=="new"){
            request()->session()->flash('success','Your order has been placed. please wait.');
            return redirect()->route('home');

            }
            elseif($order->status=="process"){
                request()->session()->flash('success','Your order is under processing please wait.');
                return redirect()->route('home');
    
            }
            elseif($order->status=="delivered"){
                request()->session()->flash('success','Your order is successfully delivered.');
                return redirect()->route('home');
    
            }
            else{
                request()->session()->flash('error','Your order canceled. please try again');
                return redirect()->route('home');
    
            }
        }
        else{
            request()->session()->flash('error','Invalid order numer please try again');
            return back();
        }
    }

    // PDF generate
    public function pdf(Request $request, $id){
        $order=Order::getAllOrder($request->id);
        // return $order;
        dd($id);
        $file_name=$order->order_number.'-'.$order->first_name.'.pdf';
        // return $file_name;
        return view('backend.order.pdf')->with('order',$order);
        // return $pdf->download($file_name);
    }
    // Income chart
    public function incomeChart(Request $request){
        $year=\Carbon\Carbon::now()->year;
        // dd($year);
        $items = Invoice::with(['invoiceItems'])->whereYear('created_at',$year)->where('is_paid','paid')->get()
            ->groupBy(function($d){
                return \Carbon\Carbon::parse($d->created_at)->format('m');
            });
            // dd($items);
        $result=[];
        foreach($items as $month=>$item_collections){
            foreach($item_collections as $item){
                $amount=$item->invoiceItems->sum('price');
                // dd($amount);
                $m=intval($month);
                // return $m;
                isset($result[$m]) ? $result[$m] += $amount :$result[$m]=$amount;
            }
        }
        $data=[];
        for($i=1; $i <=12; $i++){
            $monthName=date('F', mktime(0,0,0,$i,1));
            $data[$monthName] = (!empty($result[$i]))? number_format((float)($result[$i]), 2, '.', '') : 0.0;
        }
        return $data;
    }
}
