<?php namespace AhmadFatoni\ApiGenerator\Controllers\API;

use Cms\Classes\Controller;
use Illuminate\Http\Request;
use AhmadFatoni\ApiGenerator\Helpers\Helpers;
use Illuminate\Support\Facades\Validator;

use TPS\Birzha\Models\Product;
use TPS\Birzha\Models\Orders;
use TPS\Birzha\Models\OrderItems;
use TPS\Birzha\Models\VendorSales;
use RainLab\User\Models\User as UserClient;

class OrderApiController extends Controller
{
	protected $Order;

    protected $helpers;

    public function __construct(Orders $Order, Helpers $helpers)
    {
        parent::__construct();
        $this->Orders    = $Order;
        $this->helpers          = $helpers;
    }

    public function createOrder(Request $request){
        $data = $request->all();
        
        $validator = Validator::make($data, [
           'note' => 'required',
           'address' => 'required',
           'items' => 'required',
        ]);
        
       

       // $validator = $this->validateForm($data, $rules);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }
       
        //dd($data);
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        $order = new Orders;
        
        $order->user_id = $currentUser->id;
        $order->note = $data["note"];
        $order->address = $data["address"];
        $order->status = "new";
        $order->save();
        
        
        //   [{"item":34,"qty":1},{"item":35,"qty":3}]
        
        $orderItem = new OrderItems;
        $orderItem->order_id = $order->id;
        $orderItem->items = json_decode($data["items"]);
        $orderItem->save();
        
       // dd($orderItem->items[0]["item"]);
        
        for ($i = 0; $i < count($orderItem->items); $i++) {
            
            $vendorSale = new VendorSales;
            $vendorSale->order_id = $order->id;
            $vendorSale->vendor_id =  $orderItem->items[$i]["vendor_id"];
            $vendorSale->product_id = $orderItem->items[$i]["item"];
            $vendorSale->qty = $orderItem->items[$i]["qty"];
            $vendorSale->price = $orderItem->items[$i]["price"];
            $vendorSale->save();
            
        }
        
        
        if ($order && $orderItem && $vendorSale){
            
            //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$order]);
            return response()->json($order, 200);
            
        }else{
        
            return $this->helpers->apiArrayResponseBuilder(400, 'fail');
            
        }
       
    }
    
    
    public function myOrders(Request $request){
        
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        
        $orders = Orders::where("user_id", $currentUser->id)->with("order_items")->orderBy('id', 'DESC')->paginate(12);
        
        return response()->json($orders, 200);
        //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$orders]);
        
    }
    
    
    
    
    public function mySales(Request $request){
        
        $data = $request->all();
        
        $validator = Validator::make($data, [
           'order_id' => 'required',
        ]);
        
       

       // $validator = $this->validateForm($data, $rules);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }
        
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        
        $sales = VendorSales::where('vendor_id', $currentUser->id)->where('order_id', $data["order_id"])->with(['order.user', 'product'])->orderBy('id', 'DESC')->paginate(15);
        
       
        
        return response()->json($sales, 200);
        //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$orders]);
        
    }
    
    public function mySaleOrders(Request $request){
        
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        
        $sales = VendorSales::select('id', 'order_id', 'created_at', 'status')->where('vendor_id', $currentUser->id)->groupBy('order_id')->orderBy('id', 'DESC')->paginate(15);
        
       
        
        return response()->json($sales, 200);
        //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$orders]);
        
    }
    
    
    public function checkVendorSales(){
        
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        $counter = 0;
        
        $sales = VendorSales::where('vendor_id', $currentUser->id)->where('status', 'new')->get();
        
        
        
        $newOrders = array(
            "new_order_count" => count($sales),
        );
        
        return response()->json($newOrders, 200);
        //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$orders]);
        
    }
    
    
    public function confirmOrder(Request $request){
        $data = $request->all();
        
        $validator = Validator::make($data, [
           'order_id' => 'required',
        ]);
        
       // $validator = $this->validateForm($data, $rules);
        if($validator->fails()) {
            return $this->helpers->apiArrayResponseBuilder(400, 'fail', $validator->errors() );
        }
       
       
        //dd($data);
        $currentUser = \JWTAuth::parseToken()->authenticate(); 
        $vendorOrders = VendorSales::where('order_id', $data["order_id"])->get();
        
        if((count($vendorOrders) != 0) && ($vendorOrders[0]->vendor_id == $currentUser->id)){
        
            for ($i = 0; $i < count($vendorOrders); $i++) {
                
                $vendorOrders[$i]->status = "completed";
                $vendorOrders[$i]->save();
                
            }
        
        }
        
        
        if ($vendorOrders){
            
            //return $this->helpers->apiArrayResponseBuilder(200, 'ok', [$order]);
            return response()->json($vendorOrders, 200);
            
        }else{
        
            return $this->helpers->apiArrayResponseBuilder(400, 'fail');
            
        }
       
    }

    public static function getAfterFilters() {return [];}
    public static function getBeforeFilters() {return [];}
    public static function getMiddleware() {return [];}
    public function callAction($method, $parameters=false) {
        return call_user_func_array(array($this, $method), $parameters);
    }

}
