<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\http\Request;
use Illuminate\http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Input;
use Hash;


use DB;


class OrderController extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;


    public function AddOrderFatoorah (Request $request)
    { 
//return "Hello";
		
				
				
				$name=$request['name'];
				$address=$request['address'];
				$shipping_add=$request['shipping_add'];
               	$phone=$request['phone'];
				$email=$request['email'];
				$payment_method=$request['payment_method'];
                $order_total=$request['order_total'];
				$order_type=$request['order_type'];
				$order_receive_at=$request['order_receive_at'];
				$customer_type=$request['customer_type'];
				$order_details=$request['order_details'];
				
				
				$client = new \GuzzleHttp\Client
				([
					'base_uri' => 'https://test.myfatoorah.com'
				]);
				
				try {
					
					$data=[
                        'payCustomerDC' => [[
                            'name'=>'Ahmed Hafez',
                            'email'=>'payments@myfatoorah.com',
                            'mobile'=>'4444',
                        ]],
                        'payMerchantDC' => [[
                            'merchant_code'=>'999999',
                            'merchant_username'=>'testapi@myfatoorah.com',
                            'merchant_password'=>'E55D0',
                            'merchant_ReferenceID'=>'1256578',
                            'ReturnURL'=>'https://www.google.com',
                            'merchant_error_url'=>'https://www.google.com',
                            'udf1'=>'1',
                            'udf2'=>'2',
                            'udf3'=>'3',
                            'udf4'=>'4',
                            'udf5'=>'5',
                        ]],
                        'paylstProductDC' => [[
                            'product_name'=>$request->input('product_name'),
                            'unitPrice'=>$request->input('unitPrice'),
                            'qty'=>$request->input('qty'),
                        ]],
                        'prdTotal'=>$request->input('prdTotal'),
                        'paymentMode'=>$request->input('paymentMode'),
                        'paymentCurrency'=>$request->input('paymentCurrency'),
            
                    ];
				
					$response = $client->post('pg/PaymentGatewayRest.aspx/PaymentRequest',['json'=>$data]);
					$result=json_decode($response->getBody());
					$ref_id=$result->referenceID;
					$pay_url=$result->paymentURL;
				
				//,'paymentURL'=>$result->paymentURL
				
	
				try 
				{ 
					$order_id= mt_rand();
					$inserteed = DB::insert('insert into maktabti_orders (order_id,name,address,shipping_add,phone,email,payment_method,order_total,order_type,order_receive_at,customer_type) 
					values (?,?,?,?,?,?,?,?,?,?,?)',[$order_id,$name,$address,$shipping_add,$phone,$email,$payment_method,$order_total,$order_type,$order_receive_at,$customer_type]);
					if ($inserteed)
					{
						
							return response()->json(['status'=>'success','order_id'=>$order_id,'ref_id'=>$ref_id,'pay_url'=>$pay_url]);  
						
					}
					else 
					{
						return response()->json(['status'=>'failed','error'=>'Sql Error 2']);

					}
				} 
				catch(\Illuminate\Database\QueryException $ex)
				{ 		
					return response()->json(['status'=>'failed','error'=>'Sql Error 3']);
				}
				
					}
					
					
					catch (RequestException $ex)
					{

						return $this->outApiJson(false,'pdo_exception');
					} 
			
			
      
    }
	
	
     public function AddOrder (Request $request)
    { 
		if(isset($request['name']) && !empty($request['name']) AND isset($request['address']) && !empty($request['address'])
		AND isset($request['shipping_add']) && !empty($request['shipping_add']) AND isset($request['phone']) && !empty($request['phone'])
		AND isset($request['email']) && !empty($request['email']) AND isset($request['payment_method']) && !empty($request['payment_method'])
		AND isset($request['order_total']) && !empty($request['order_total'])AND isset($request['order_type']) && !empty($request['order_type'])
		AND isset($request['order_receive_at']) && !empty($request['order_receive_at'])AND isset($request['customer_type']) && !empty($request['customer_type'])) 
			{
				function addItems($order_id,$OrderDetails)
				{
	                $data = json_decode($OrderDetails);
					foreach ($data as $key)
					{
						$book_id        =  $key->book_id;
						$quantity      =  $key->quantity;
						
						try 
						{ 
							$inserted = DB::insert('insert into order_details (order_id,book_id,quantity) values (?,?,?)',[$order_id,$book_id,$quantity]);
							if($inserted)
							{
							    
							    	$order = DB::select('select * from maktabti_books where book_id = ?', [$book_id]);
                					if($order)
                					{
                					
                						foreach ($order as $od)
                						{
                							 $av = $od->quantity_avail;
                							 $sol = $od->books_sold;
                							 
                							 $new = $av - 	$quantity ;
                							 $new2 = $sol +	$quantity ;
                							 
                							 
                							 $user_new = DB::update('update maktabti_books  SET quantity_avail = ?, books_sold = ? where book_id = ?', [$new,$new2,$book_id]);
        										if ( $user_new)                             
        										{
        												$ff = 1;
        										}
        										else 
        										{
        										//	return response()->json(['status'=>'failed','error'=>'Sql Error']);
        										}
                						}
                						
                                    //return response()->json(['status'=>'success','data'=>$order]);
                
                					}
                					else 
                					{
                					//	return response()->json(['status'=>'failed','error'=>'No Information Found']);
                					}
			
							    
							    
							
							}
							else 
							{
								$ff = 0;
							}		
						} 
						catch(\Illuminate\Database\QueryException $ex)
						{ 		
							$ff = 0;
						}												
					}
					
					return $ff;
				}
				
				$name=$request['name'];
				$address=$request['address'];
				$shipping_add=$request['shipping_add'];
               	$phone=$request['phone'];
				$email=$request['email'];
				$payment_method=$request['payment_method'];
                $order_total=$request['order_total'];
				$order_type=$request['order_type'];
				$order_receive_at=$request['order_receive_at'];
				$customer_type=$request['customer_type'];
				$order_details=$request['order_details'];
				
	
				try 
				{ 
					$order_id= mt_rand();
					$inserteed = DB::insert('insert into maktabti_orders (order_id,name,address,shipping_add,phone,email,payment_method,order_total,order_type,order_receive_at,customer_type) 
					values (?,?,?,?,?,?,?,?,?,?,?)',[$order_id,$name,$address,$shipping_add,$phone,$email,$payment_method,$order_total,$order_type,$order_receive_at,$customer_type]);
					if ($inserteed)
					{
						if(addItems($order_id,$order_details)==1)
						{
							return response()->json(['status'=>'success','order_id'=>$order_id]);  
						}
						else 
						{
							return response()->json(['status'=>'failed','error'=>'Sql Error 1']);
						}
					}
					else 
					{
						return response()->json(['status'=>'failed','error'=>'Sql Error 2']);

					}
				} 
				catch(\Illuminate\Database\QueryException $ex)
				{ 		
					return response()->json(['status'=>'failed','error'=>'Sql Error 3']);
				}

			}

		else 
			{
				return response()->json(['status'=>'failed','error'=>'Incomplete Parameters']);
			}
      
    }
    
    
    public function ViewOrder (Request $request)
    { 
		if(isset($request['order_id']) && !empty($request['order_id']) ) 
			{
				$order_id=$request['order_id'];
				//$OrderStatus=$request['OrderStatus'];
				//$st = "All";
				
					$order = DB::select('select * from maktabti_orders where order_id = ?', [$order_id]);
					if($order)
					{
						//$order = Order::all();
						foreach ($order as $od)
						{
							$order_it= DB::select('select * from order_details where order_id = ?', [$order_id]);
							foreach ($order_it as $odd)
									{
										$book = $odd->book_id;
										$book_d= DB::select('select * from maktabti_books where book_id = ?', [$book]);
											 if($book_d)
											{
												foreach ($book_d as $b_id)
													{
														$name_english = $b_id->name_english;
														$name_arabic = $b_id->name_arabic;
														$price = $b_id->price;
														$cover_photo = $b_id->cover_photo;
													}
												$odd->name_english = $name_english;
												$odd->name_arabic = $name_arabic;
												$odd->price = $price;
												$odd->cover_photo = $cover_photo;
											}
											
											else 
											{
												
												$name_english = null;
												$name_arabic =null;
												$price = null;
												$cover_photo =null;
$odd->name_english = $name_english;
												$odd->name_arabic = $name_arabic;
												$odd->price = $price;
												$odd->cover_photo = $cover_photo;
											}
										
										
										//dd($od->toJson());
									
									}
							$od->items = $order_it;
							//dd($od->toJson());
						
						}
						
					return response()->json(['status'=>'success','data'=>$order]);

					}
					else 
					{
						return response()->json(['status'=>'failed','error'=>'No Information Found']);
					}

			}
			
			else if (isset($request['email']) && !empty($request['email']) ) 
			{
				$email=$request['email'];
				
					$order = DB::select('select * from maktabti_orders where email = ?', [$email]);
					if($order)
					{
						//$order = Order::all();
						foreach ($order as $od)
						{
							$o_id = $od->order_id;
							$order_it= DB::select('select * from order_details where order_id = ?', [$o_id]);
								foreach ($order_it as $odd)
									{
										$book = $odd->book_id;
										$book_d= DB::select('select * from maktabti_books where book_id = ?', [$book]);
											if($book_d)
											{
												foreach ($book_d as $b_id)
													{
														$name_english = $b_id->name_english;
														$name_arabic = $b_id->name_arabic;
														$price = $b_id->price;
														$cover_photo = $b_id->cover_photo;
													}
												$odd->name_english = $name_english;
												$odd->name_arabic = $name_arabic;
												$odd->price = $price;
												$odd->cover_photo = $cover_photo;
											}
											
											else 
											{
												$name_english = null;
												$name_arabic =null;
												$price = null;
												$cover_photo =null;
											}
										
										//dd($od->toJson());
									
									}
							$od->items = $order_it;
							//dd($od->toJson());
						
						}
						
					return response()->json(['status'=>'success','data'=>$order]);

					}
					else 
					{
						return response()->json(['status'=>'failed','error'=>'No Information Found']);
					}
			}

		else 
			{
				return response()->json(['status'=>'failed','error'=>'Incomplete Parameters']);
			}
      
    }
    
     public function ViewAllOrder (Request $request)
    { 
		
					$order = DB::select('select * from maktabti_orders order by created_at DESC');
					if($order)
					{
						//$order = Order::all();
						foreach ($order as $od)
						{
						    $o_id = $od->order_id;
							$order_it= DB::select('select * from order_details where order_id = ?', [$o_id]);
							foreach ($order_it as $odd)
									{
										$book = $odd->book_id;
										$book_d= DB::select('select * from maktabti_books where book_id = ?', [$book]);
											 if($book_d)
											{
												foreach ($book_d as $b_id)
													{
														$name_english = $b_id->name_english;
														$name_arabic = $b_id->name_arabic;
														$price = $b_id->price;
														$cover_photo = $b_id->cover_photo;
													}
												$odd->name_english = $name_english;
												$odd->name_arabic = $name_arabic;
												$odd->price = $price;
												$odd->cover_photo = $cover_photo;
											}
											
											else 
											{
												$name_english = null;
												$name_arabic =null;
												$price = null;
												$cover_photo =null;
											}
										
									
									}
							$od->items = $order_it;
							//dd($od->toJson());
						
						}
						
					return response()->json(['status'=>'success','data'=>$order]);

					}
					else 
					{
						return response()->json(['status'=>'failed','error'=>'No Information Found']);
					}

		
      
    }
    
     public function ViewOrderType (Request $request)
    { 
		
		if (isset($request['type']) && !empty($request['type']) ) 
			{
				$type =$request['type'];
				
					$order = DB::select('select * from maktabti_orders where order_type = ? order by created_at DESC ', [$type]);
					if($order)
					{
						//$order = Order::all();
						foreach ($order as $od)
						{
							$o_id = $od->order_id;
							$order_it= DB::select('select * from order_details where order_id = ?', [$o_id]);
								foreach ($order_it as $odd)
									{
										$book = $odd->book_id;
										$book_d= DB::select('select * from maktabti_books where book_id = ?', [$book]);
                                        if($book_d)
											{
												foreach ($book_d as $b_id)
													{
														$name_english = $b_id->name_english;
														$name_arabic = $b_id->name_arabic;
														$price = $b_id->price;
														$cover_photo = $b_id->cover_photo;
													}
												$odd->name_english = $name_english;
												$odd->name_arabic = $name_arabic;
												$odd->price = $price;
												$odd->cover_photo = $cover_photo;
											}
											
											else 
											{
												$name_english = null;
												$name_arabic =null;
												$price = null;
												$cover_photo =null;
$odd->name_english = $name_english;
												$odd->name_arabic = $name_arabic;
												$odd->price = $price;
												$odd->cover_photo = $cover_photo;
											}
										
											
										
										//dd($od->toJson());
									
									}
							$od->items = $order_it;
							//dd($od->toJson());
						
						}
						
					return response()->json(['status'=>'success','data'=>$order]);

					}
					else 
					{
						return response()->json(['status'=>'failed','error'=>'No Information Found']);
					}
			}

		else 
			{
				return response()->json(['status'=>'failed','error'=>'Incomplete Parameters']);
			}
      
    }


public function SuccessPay()
    { 
		
		return response()->json(['status'=>'success']);
    }
	

public function PayFail()
    { 
		
		return response()->json(['status'=>'failure']);
    }
	
	
	
public function AddOrderStore (Request $request)
		{ 
			if(isset($request['book_id']) && !empty($request['book_id']) AND isset($request['quantity']) && !empty($request['quantity'])) 
				{
					function addItems($order_id,$book_id,$quantity)
					{
							
							try 
							{ 
								$inserted = DB::insert('insert into order_details (order_id,book_id,quantity) values (?,?,?)',[$order_id,$book_id,$quantity]);
								if($inserted)
								{
									
										$order = DB::select('select * from maktabti_books where book_id = ?', [$book_id]);
										if($order)
										{
										
											foreach ($order as $od)
											{
												 $av = $od->quantity_avail;
												 $sol = $od->books_sold;
												 
												 $new = $av - 	$quantity ;
												 $new2 = $sol +	$quantity ;
												 
												 
												 $user_new = DB::update('update maktabti_books  SET quantity_avail = ?, books_sold = ? where book_id = ?', [$new,$new2,$book_id]);
													if ( $user_new)                             
													{
															$ff = 1;
													}
													else 
													{
													//	return response()->json(['status'=>'failed','error'=>'Sql Error']);
													}
											}
											
										//return response()->json(['status'=>'success','data'=>$order]);
					
										}
										else 
										{
										//	return response()->json(['status'=>'failed','error'=>'No Information Found']);
										}
				
									
									
								
								}
								else 
								{
									$ff = 0;
								}		
							} 
							catch(\Illuminate\Database\QueryException $ex)
							{ 		
								$ff = 0;
							}												
						
						
						return $ff;
					}
					
					
					$order_type="store";
					
					$book_id=$request['book_id'];
					$quantity=$request['quantity'];

					$name="-";
				$address="-";
				$shipping_add="-";
               	$phone="-";
				$email="-";
				$payment_method="-";
                $order_total="-";
				
				
				$customer_type="guest";
				//$order_details=$request['order_details'];
					
		
					try 
					{ 
						$order_id= mt_rand();
						$date1=date("Y-m-d") .",". date("H:i");


$inserteed = DB::insert('insert into maktabti_orders (order_id,name,address,shipping_add,phone,email,payment_method,order_total,order_type,order_receive_at,customer_type) 
					values (?,?,?,?,?,?,?,?,?,?,?)',[$order_id,$name,$address,$shipping_add,$phone,$email,$payment_method,$order_total,$order_type,$date1,$customer_type]);
					


						
						if ($inserteed)
						{
							if(addItems($order_id,$book_id,$quantity)==1)
							{
								return response()->json(['status'=>'success','order_id'=>$order_id]);  
							}
							else 
							{
								return response()->json(['status'=>'failed','error'=>'Sql Error 1']);
							}
						}
						else 
						{
							return response()->json(['status'=>'failed','error'=>'Sql Error 2']);

						}
					} 
					catch(\Illuminate\Database\QueryException $ex)
					{ 		
						return response()->json(['status'=>'failed','error'=>'Sql Error 3']);
					}

				}

			else 
				{
					return response()->json(['status'=>'failed','error'=>'Incomplete Parameters']);
				}
		  
		}

}

