<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\OrderModel;
use App\Models\CartModel;
use App\Models\TransactionsModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use App\Models\ProductModel;

class OrderController extends Controller
{
  function getDataById($id)
  {

    $data = DB::table("orders")
    ->select('orders.*',
     'product.title',
     'images.image as product_image',
     'product.qty_text',
     'user_address.name',
     'user_address.s_phone',
     'user_address.flat_no',
     'user_address.apartment_name',
     'user_address.area',
     'user_address.city',
     'user_address.pincode',
     'user_address.lat',
     'user_address.lng'
     )
     ->leftJoin('images', function ($join) {
       $join->on('images.table_id', '=', 'orders.product_id')
       ->where('images.table_name','=',"product")
       ->where('images.image_type','=',1);
       })
     ->Join('product','orders.product_id', '=','product.id')
     ->Join('user_address','user_address.id', '=','orders.address_id')
     ->where("orders.id","=",$id)
     ->orderBy('orders.created_at','DESC')
      ->first();

          $response = [
              "response"=>200,
              'data'=>$data,
          ];
      
    return response($response, 200);
  }
  function addCardAndOrderData(Request $request)
  {
      
      $validator = Validator::make(request()->all(), [
          'user_id' => 'required',
          'status' => 'required',
          'address_id' => 'required',
          'order_type' => 'required'
          
  ]);
      
  if ($validator->fails())
    return response (["response"=>400],400);
      else{

        $dataCart = DB::table("cart")
        ->select('cart.*')
         ->where("cart.user_id","=",$request->user_id)
          ->get();
          $insertStatus=false;
          for( $i=0; $i<count($dataCart);$i++){
            $newDataCart=$dataCart[$i];
                try{
                  $timeStamp= date("Y-m-d H:i:s");
                  $dataModel=new OrderModel;
                  $dataModel->user_id  = $request->user_id;
                  $dataModel->qty  =  $newDataCart->qty;
                  $dataModel->price = $newDataCart->price;
                  $dataModel->order_amount = $newDataCart->total_price;
                  $dataModel->mrp = $newDataCart->mrp;
                  $dataModel->tax = $newDataCart->tax;
                  $dataModel->product_id  = $newDataCart->product_id;
                  $dataModel->address_id  = $request->address_id;
                  $dataModel->status = $request->status;
                  $dataModel->order_type = $request->order_type;
                  
                  if(isset($request->trasation_id)){
                      $dataModel->trasation_id = $request->trasation_id;
                  }
      
                  $dataModel->created_at=$timeStamp;
                  $dataModel->updated_at=$timeStamp;
                  $qResponce= $dataModel->save();
                     if($qResponce){
                      if($i==(count($dataCart)-1)){
                        $insertStatus=true;
                      }
                
                      $dataCartDeleteModel= CartModel::where("id",$newDataCart->id)->first();
                      $dataCartDeleteModel->delete();
        
                      }
                      else 
             {          $response = [
                         "response"=>201,
                         'status'=>false,
                         'message' => "error",
                         
               
                     ];
                     return response($response, 200);}
                  //  
                     
                             
                }catch(\Exception $e){
            
                  $response = [
                    "response"=>201,
                    'status'=>false,
                    'message' => "error",
            
                ];
                return response($response, 200);
                }
              }
              if( $insertStatus==true){
                 $dataModelProduct= ProductModel::where("id",$dataModel->product_id)->first();
                if($dataModelProduct->stock_qty>0){
                  $oldQty=$dataModelProduct->stock_qty;
                  if($oldQty>=$dataModel->qty){
                    $dataModelProduct->stock_qty=$oldQty- $dataModel->qty;
                    $dataModelProduct->save();
                  }
                
                }
                          $response = [
                           "response"=>200,
                           'status'=>true,
                           'message' => "successfully"
                 
                       ];
                    return response($response, 200);
          
                  }
                }
     
    }
  function getData()
  {

    $data = DB::table("orders")
    ->select('orders.*',
     'product.title',
     'images.image as product_image',
     'product.qty_text',
     'user_address.name',
     'user_address.s_phone',
     'user_address.flat_no',
     'user_address.apartment_name',
     'user_address.area',
     'user_address.city',
     'user_address.pincode',
     'users.wallet_amount'
     
    
     )
     ->leftJoin('images', function ($join) {
       $join->on('images.table_id', '=', 'orders.product_id')
       ->where('images.table_name','=',"product")
       ->where('images.image_type','=',1);
       })
       ->Join('users','users.id', '=','orders.user_id')
     ->Join('product','orders.product_id', '=','product.id')
     ->Join('user_address','user_address.id', '=','orders.address_id')
     ->orderBy('orders.created_at','DESC')
      ->get();
    
          $response = [
              "response"=>200,
              'data'=>$data,
          ];
      
    return response($response, 200);
  }
  function getDataByUId($id)
  {

    $data = DB::table("orders")
    ->select('orders.*',
     'product.title',
      'images.image as product_image',
     'product.qty_text',
     'user_address.name',
     'user_address.s_phone',
     'user_address.flat_no',
     'user_address.apartment_name',
     'user_address.area',
     'user_address.city',
     'user_address.pincode'
  
    )
         ->leftJoin('images', function ($join) {
       $join->on('images.table_id', '=', 'orders.product_id')
       ->where('images.table_name','=',"product")
       ->where('images.image_type','=',1);
       })
     ->Join('product','orders.product_id', '=','product.id')
     ->Join('user_address','user_address.id', '=','orders.address_id')
     ->where("orders.user_id","=",$id)
     ->orderBy('orders.created_at','DESC')
      ->get();
    
          $response = [
              "response"=>200,
              'data'=>$data,
          ];
      
    return response($response, 200);
  }
    function addData(Request $request)
    {
        
        $validator = Validator::make(request()->all(), [
            'user_id' => 'required',
            'order_amount' => 'required',
            'product_id' => 'required',
            'status' => 'required',
            'qty' => 'required',
            'price' => 'required',   
            'mrp' => 'required',
            'tax' => 'required'
            
    ]);
        
    if ($validator->fails())
      return response (["response"=>400],400);
        else{
                  try{
                    $timeStamp= date("Y-m-d H:i:s");
                    $dataModel=new OrderModel;
                    $dataModel->user_id  = $request->user_id;
                    $dataModel->qty  = $request->qty;
                    $dataModel->order_amount = $request->order_amount;
                    $dataModel->product_id  = $request->product_id;
                    $dataModel->address_id  = $request->address_id;
                    $dataModel->status = $request->status;
                    $dataModel->price  = $request->price;
                    $dataModel->mrp = $request->mrp;
                    $dataModel->tax = $request->tax;
                 
                    if(isset($request->order_status))
                    {$dataModel->order_status = $request->order_status;}
                    else{
                      $dataModel->order_status = 0;
                    }
                    if(isset($request->start_date))
                    {$dataModel->start_date = $request->start_date;}

                    if(isset($request->selected_days_for_weekly))
                    {$dataModel->selected_days_for_weekly = $request->selected_days_for_weekly;}

                    if(isset($request->subscription_type)){
                      $dataModel->subscription_type = $request->subscription_type;
                  }
                    if(isset($request->trasation_id)){
                        $dataModel->trasation_id = $request->trasation_id;
                    }
                    if(isset($request->order_type)){
                      $dataModel->order_type = $request->order_type;
                  }
                    
        
                    $dataModel->created_at=$timeStamp;
                    $dataModel->updated_at=$timeStamp;
                    $qResponce= $dataModel->save();
                       if($qResponce){
                  
                                     $dataModelProduct= ProductModel::where("id",$dataModel->product_id)->first();
                        if($dataModelProduct->stock_qty>0){
                          $oldQty=$dataModelProduct->stock_qty;
                          if($oldQty>=$dataModel->qty){
                            $dataModelProduct->stock_qty=$oldQty- $dataModel->qty;
                            $dataModelProduct->save();
                          }
                        
                        }   
                              
                       $response = [
                             "response"=>200,
                             'status'=>true,
                             'message' => "successfully"
                   
                         ];
                        }else 
                         $response = [
                           "response"=>201,
                           'status'=>false,
                           'message' => "error",
                 
                       ];
                       return response($response, 200);
                               
                  }catch(\Exception $e){
              
                    $response = [
                      "response"=>201,
                      'status'=>false,
                      'message' => "error",
              
                  ];
                  return response($response, 200);
                  }
            
       }
       
      }
      function updateOrderTxnAndAddNewTxn(Request $request){
        $initialCheck=false;
        $validator = Validator::make(request()->all(), [
          'order_id'=>'required',
          'payment_id'=>'required',
          
          
      ]);
      if ($validator->fails())
      $initialCheck=true;
      
        
        if ($initialCheck)
            return response (["response"=>400],400);
              else{
               try{
                $dataModel= OrderModel::where("id",$request->order_id)->first();
                  $timeStamp= date("Y-m-d H:i:s");

                  $dataModelTxn=new TransactionsModel;
                  $dataModelTxn->user_id  = $dataModel->user_id;
                  $dataModelTxn->payment_id  = $request->payment_id;
                  $dataModelTxn->amount = $dataModel->order_amount;
                  $dataModelTxn->type  = 2;
                  $productName=$dataModel->title;
                  $dataModelTxn->description  = "Amount debited from account - $productName";
          
                  $dataModelTxn->created_at=$timeStamp;
                  $dataModelTxn->updated_at=$timeStamp;
          
                  $qResponce= $dataModelTxn->save();
                  if($qResponce){
                    $dataModel->trasation_id = $dataModelTxn->id;
                    $dataModel->updated_at=$timeStamp;
                    $dataModel->save();
  
            $response = [
                    "response"=>200,
                    'status'=>true,
                    'message' => "successfully",
          
                ];}
                else 
                $response = [
                  "response"=>201,
                  'status'=>false,
                  'message' => "error",
        
              ];
              return response($response, 200);       
      
                }
                catch(\Exception $e){
                  $response = [
                    "response"=>201,
                    'status'=>false,
                    'message' => "error",
                ];
                return response($response, 200);
                }
          
                   
              } 
              

        
          }
      function updateDetails(Request $request){
        $initialCheck=false;
        $validator = Validator::make(request()->all(), [
          'id'=>'required'
      ]);
      if ($validator->fails())
      $initialCheck=true;
      
        
        if ($initialCheck)
            return response (["response"=>400],400);
              else{
               try{
                  $timeStamp= date("Y-m-d H:i:s");
                  $dataModel= OrderModel::where("id",$request->id)->first();
      
                  if(isset($request->qty))
                  $dataModel->qty  = $request->qty;
                  if(isset($request->order_amount))
                  $dataModel->order_amount = $request->order_amount;
                  if(isset($request->product_id))
                  $dataModel->product_id  = $request->product_id;
                  if(isset($request->address_id))
                  $dataModel->address_id  = $request->address_id;
                  if(isset($request->start_date))
                  $dataModel->start_date = $request->start_date;
                  if(isset($request->status))
                  $dataModel->status = $request->status;
                  if(isset($request->order_status))
                  $dataModel->order_status = $request->order_status;


                  if(isset($request->selected_days_for_weekly))
                  {$dataModel->selected_days_for_weekly = $request->selected_days_for_weekly;}

                  if(isset($request->subscription_type)){
                    $dataModel->subscription_type = $request->subscription_type;
                }
                  if(isset($request->trasation_id)){
                      $dataModel->trasation_id = $request->trasation_id;
                  }
                  if(isset($request->order_type)){
                    $dataModel->order_type = $request->order_type;
                }
                  
           
                     $dataModel->updated_at=$timeStamp;
                
               
             $qResponce= $dataModel->save();
       
              if($qResponce)
           {   
      
            // $imageFile=isset($request->image)?$request->image:null;
            // $imageId=isset($request->image_id)?$request->image_id:null;
         
            // app('App\Http\Controllers\ImageCountController')->uploadImage($imageFile, "buses", $userDetailsModel->id,1,$imageId);
            // //1=profile_image  
            
            $response = [
                    "response"=>200,
                    'status'=>true,
                    'message' => "successfully",
          
                ];}
                else 
                $response = [
                  "response"=>201,
                  'status'=>false,
                  'message' => "error",
        
              ];
              return response($response, 200);       
      
                }
                catch(\Exception $e){
                  $response = [
                    "response"=>201,
                    'status'=>false,
                    'message' => "error ",
                ];
                return response($response, 200);
                }
          
                   
              } 
              
        
        
          }
}
