<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\UsersMoves;
use App\Models\ShippingType;
use App\Models\ShippingStatus;
use App\Models\ShippingOrder;
use App\Models\Places;
use App\Models\Addressses;
use DB ;
use Str ;
use App\Mail\AdminResetPassword;
use Carbon\Carbon;
use Mail;
use Auth;
use URL;
use SpamProtector;
use Storage;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use App\Models\Stores;
use App\Models\CostCenter;
use App\Models\Coins;
use App\Models\AcccountingManual;
use App\Models\Governrate;
use App\Models\Employess;
use App\Models\Customers;
use App\Models\Vendors;
use App\Models\Journalizing;
use App\Models\JournalizingDetails;
use App\Models\GeneralDaily;
use App\Models\Ticket;
use App\Models\TicketProducts;
use App\Models\ProductUnits;
use App\Models\Measuerments;
use App\Models\StoreCountSales;
use App\Models\Products;
use App\Models\ProductsQty;
use App\Models\ProductsPurchases;
use App\Models\ProductsStartPeriods;
use App\Models\ProductsStoresTransfers;
use App\Models\OutcomManufacturingModel;
use App\Models\ShippingList;
use App\Models\ShippingListTickets;
use App\Models\ShipmentReceipts;
use App\Models\ShipmentReceiptsList;
use App\Models\ShipmentReceiptsClients;
use App\Models\ShippingDefault;
use App\Models\ItemsGroups;
use App\Models\ClientAddress;

class ShippingController extends Controller
{
    
function __construct()
{

$this->middleware('permission:انواع الشحنات', ['only' => ['ShippingTypePage','AddShippingType','EditShippingType','DeleteShippingType']]);
$this->middleware('permission:حالات الشحنات', ['only' => ['ShippingStatusPage','AddShippingStatus','EditShippingStatus','DeleteShippingStatus']]);
$this->middleware('permission:امر الشحن', ['only' => ['ShippingOrderPage','AddShippingOrder','EditShippingOrder','DeleteShippingOrder']]);
$this->middleware('permission:طلباتي شحن', ['only' => ['MyOrdersEmpPage','ChangeStatusOrder','CustomerCollection','ReportMyOrdersEmpPage']]);
$this->middleware('permission:تحصيل مورد', ['only' => ['VendorCoolectionsPage','PostVendorCollection']]);
$this->middleware('permission:تقارير الطلبات', ['only' => ['ReportOrdersPage','FilterOrders']]);
$this->middleware('permission:البوليصه', ['only' => ['TicketsPage']]);
$this->middleware('permission:جدول البوليصات', ['only' => ['TicketsSechdule']]);
$this->middleware('permission:قائمه الشحن', ['only' => ['ShippingList']]);
$this->middleware('permission:جدول قوائم شحن', ['only' => ['ShippingListSechdule']]);
$this->middleware('permission:استلام شحنات', ['only' => ['ShipmentReceipts']]);
$this->middleware('permission:جدول استلام شحنات', ['only' => ['ShipmentReceiptsSechdule']]);
$this->middleware('permission:استلام شحنات عملاء', ['only' => ['ShipmentReceiptsClients']]);
$this->middleware('permission:جدول استلام شحنات عملاء', ['only' => ['ShipmentReceiptsClientsSechdule']]);

}
          //======  ShippingType ======= 
        public function ShippingTypePage(){
        $items=ShippingType::all();
         return view('admin.Shipping.ShippingType',['items'=>$items]);
    }
    
     public function AddShippingType(){
        
        $data= $this->validate(request(),[
             'Arabic_Name'=>'required',
     
             
               ],[
            'Arabic_Name.required' => trans('admin.Arabic_NameRequired'),    
            'English_Name.required' => trans('admin.English_NameRequired'),    
     
         ]);
   
         
           
         $data['Arabic_Name']=request('Arabic_Name');
         
         if(!empty(request('English_Name'))){
         $data['English_Name']=request('English_Name');
         }else{
             
             
           $data['English_Name']=request('Arabic_Name');   
         }
        
         ShippingType::create($data);
         
         
         
           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
           $dataUser['Screen']='انواع الشحن';
           $dataUser['ScreenEn']='Shipping Type';
           $dataUser['Type']='اضافه جديده';
           $dataUser['TypeEn']='New Add';
           $dataUser['Explain']=request('Arabic_Name');
           $dataUser['ExplainEn']=request('English_Name');
           UsersMoves::create($dataUser);
         
             session()->flash('success',trans('admin.Added_Successfully'));
             return back();
        
    }
    
     public function EditShippingType($id){ 
         
        $data= $this->validate(request(),[
             'Arabic_Name'=>'required',
            
             
               ],[
            'Arabic_Name.required' => trans('admin.Arabic_NameRequired'),    
            'English_Name.required' => trans('admin.English_NameRequired'),    
     
         ]);
   
         
           
         $data['Arabic_Name']=request('Arabic_Name');
         if(!empty(request('English_Name'))){
         $data['English_Name']=request('English_Name');
         }else{
             
             
           $data['English_Name']=request('Arabic_Name');   
         }
         
           ShippingType::where('id',$id)->update($data);
         
                $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
                 $dataUser['Screen']='انواع الشحن';
           $dataUser['ScreenEn']='Shipping Type';
           $dataUser['Type']='تعديل';
           $dataUser['TypeEn']='Edit';
           $dataUser['Explain']=request('Arabic_Name');
           $dataUser['ExplainEn']=request('English_Name');
           UsersMoves::create($dataUser);
         
         
            session()->flash('success',trans('admin.Updated'));
            return back();
     
     
     }
    
     public function DeleteShippingType($id){
                      
        $del=ShippingType::find($id);
         
         $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
                 $dataUser['Screen']='انواع الشحن';
           $dataUser['ScreenEn']='Shipping Type';
           $dataUser['Type']='حذف';
           $dataUser['TypeEn']='Delete';
            $dataUser['Explain']=$del->Arabic_Name;
            $dataUser['ExplainEn']=$del->English_Name;
           UsersMoves::create($dataUser);
         
        $del->delete();
        session()->flash('error',trans('admin.Deleted'));
        return back();

           }
    
              //======  ShippingStatus ======= 
        public function ShippingStatusPage(){
        $items=ShippingStatus::all();
         return view('admin.Shipping.ShippingStatus',['items'=>$items]);
    }
    
     public function AddShippingStatus(){
        
        $data= $this->validate(request(),[
             'Arabic_Name'=>'required',
     
             
               ],[
            'Arabic_Name.required' => trans('admin.Arabic_NameRequired'),    
            'English_Name.required' => trans('admin.English_NameRequired'),    
     
         ]);
   
         
           
         $data['Color']=request('Color');
         $data['Arabic_Name']=request('Arabic_Name');
         
         if(!empty(request('English_Name'))){
         $data['English_Name']=request('English_Name');
         }else{
             
             
           $data['English_Name']=request('Arabic_Name');   
         }
        
         ShippingStatus::create($data);
         
         
         
           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());

                 $dataUser['Screen']='حالات الشحن';
           $dataUser['ScreenEn']='Shipping Status';
           $dataUser['Type']='اضافه جديده';
           $dataUser['TypeEn']='New Add';
           $dataUser['Explain']=request('Arabic_Name');
           $dataUser['ExplainEn']=request('English_Name');
           UsersMoves::create($dataUser);
         
             session()->flash('success',trans('admin.Added_Successfully'));
             return back();
        
    }
    
     public function EditShippingStatus($id){ 
         
        $data= $this->validate(request(),[
             'Arabic_Name'=>'required',
            
             
               ],[
            'Arabic_Name.required' => trans('admin.Arabic_NameRequired'),    
            'English_Name.required' => trans('admin.English_NameRequired'),    
     
         ]);
   
         
           
         $data['Color']=request('Color');
         $data['Arabic_Name']=request('Arabic_Name');
         if(!empty(request('English_Name'))){
         $data['English_Name']=request('English_Name');
         }else{
             
             
           $data['English_Name']=request('Arabic_Name');   
         }
         
           ShippingStatus::where('id',$id)->update($data);
         
                $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
                     $dataUser['Screen']='حالات الشحن';
           $dataUser['ScreenEn']='Shipping Status';
           $dataUser['Type']='تعديل';
           $dataUser['TypeEn']='Edit';
           $dataUser['Explain']=request('Arabic_Name');
           $dataUser['ExplainEn']=request('English_Name');
           UsersMoves::create($dataUser);
         
         
            session()->flash('success',trans('admin.Updated'));
            return back();
     
     
     }
    
     public function DeleteShippingStatus($id){
                      
        $del=ShippingStatus::find($id);
         
         $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
                  $dataUser['Screen']='حالات الشحن';
           $dataUser['ScreenEn']='Shipping Status';
           $dataUser['Type']='حذف';
           $dataUser['TypeEn']='Delete';
            $dataUser['Explain']=$del->Arabic_Name;
            $dataUser['ExplainEn']=$del->English_Name;
           UsersMoves::create($dataUser);
         
        $del->delete();
        session()->flash('error',trans('admin.Deleted'));
        return back();

           }
    
// Shipping Order  
    
    public function ShippingOrderPage(){
        $items=ShippingOrder::orderBy('id','desc')->paginate(100);
        
               $CostCenters=CostCenter::all();
          
            $Coins=Coins::all();  
          
        
          $Types=ShippingType::all();
        $Status=ShippingStatus::all();
                      $Clients = AcccountingManual::
             where('Type',1)
              ->where('Parent',24)
              ->get();
        
                       $Vendors = AcccountingManual::
             where('Type',1)
              ->where('Parent',37)
              ->get();
         $Governrates=Governrate::all();
      $Employess = Employess::where("EmpSort",1)->where('Active',1)->get();

            $res=ShippingOrder::orderBy('id','desc')->first();
           
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
               
           }else{
               
              $Code=1; 
               
           }
        
                     $ress=Customers::orderBy('id','desc')->first();
           
           if(!empty($ress->Code)){
               
              $CodeUser=$ress->Code + 1 ; 
               
           }else{
               
              $CodeUser=1; 
               
           }
        
                  $resss=Vendors::orderBy('id','desc')->first();
           
           if(!empty($resss->Code)){
               
              $CodeUserr=$resss->Code + 1 ; 
               
           }else{
               
              $CodeUserr=1; 
               
           }
        
        
               $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
        
         return view('admin.Shipping.ShippingOrder',[
             'items'=>$items,
             'Code'=>$Code,
             'Clients'=>$Clients,
             'Vendors'=>$Vendors,
             'Employess'=>$Employess,
             'Types'=>$Types,
             'Status'=>$Status,
             'CostCenters'=>$CostCenters,
             'Coins'=>$Coins,
             'CodeUser'=>$CodeUser,
             'CodeUserr'=>$CodeUserr,
             'Governrates'=>$Governrates,
             'Safes'=>$Safes,
         
         ]);
    }
    
    public function AddShippingOrder(){
       
        $Emp=Employess::find(request('Delegate'));
        
        
         $data['Code']=request('Code');
         $data['Date']=request('Date');
         $data['Weight']=request('Weight');
         $data['Number']=request('Number');
         $data['Goods_Price']=request('Goods_Price');
         $data['Shipping_Price']=request('Shipping_Price');
         $data['Total']=request('Total');
         $data['Breakable']=request('Breakable');
         $data['Note']=request('Note');
         $data['Status']=request('Status');
         $data['Type']=request('Type');
         $data['Delegate']=request('Delegate');
         $data['Vendor']=request('Vendor');
         $data['Client']=request('Client');
         $data['Coin']=request('Coin');
         $data['Cost_Center']=request('Cost_Center');
         $data['Draw']=request('Draw');
         $data['Open']=request('Open');
         $data['Paid']=null;
         $data['Ship_Sort']=request('Ship_Sort');
         $data['Adderss']=request('Adderss');
         $data['Requests']=request('Requests');
         $data['Vend']=0;
         $data['Cli']=0;
         $data['Shipping_Delegate']=$Emp->Shipping_Precent;
         $data['Cancel']=0;
         $data['Cancel_Note']=null;
         $data['Cancel_Pay']=0;
         $data['Cancel_Not_Pay']=0;

         ShippingOrder::create($data);

           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
 
                  $dataUser['Screen']='امر الشحن';
           $dataUser['ScreenEn']='Shipping Order';
           $dataUser['Type']='اضافه جديده';
           $dataUser['TypeEn']='New Add';
           $dataUser['Explain']=request('Code');
           $dataUser['ExplainEn']=request('Code');
           UsersMoves::create($dataUser);
         
             session()->flash('success',trans('admin.Added_Successfully'));
             return back();
        
    }
    
     public function EditShippingOrder($id){ 
  $Emp=Employess::find(request('Delegate'));
         
    $data['Shipping_Delegate']=$Emp->Shipping_Precent;
         $data['Cancel']=0;
         $data['Cancel_Note']=null;
         $data['Cancel_Pay']=0;
         $data['Cancel_Not_Pay']=0;
         $data['Code']=request('Code');
         $data['Date']=request('Date');
         $data['Weight']=request('Weight');
         $data['Number']=request('Number');
         $data['Goods_Price']=request('Goods_Price');
         $data['Shipping_Price']=request('Shipping_Price');
         $data['Total']=request('Total');
         $data['Breakable']=request('Breakable');
         $data['Note']=request('Note');
         $data['Status']=request('Status');
         $data['Type']=request('Type');
         $data['Delegate']=request('Delegate');
         $data['Vendor']=request('Vendor');
         $data['Client']=request('Client');
         $data['Coin']=request('Coin');
         $data['Cost_Center']=request('Cost_Center');
         $data['Draw']=request('Draw');
         $data['Vend']=0;
         $data['Cli']=0;
         $data['Open']=request('Open');
         $data['Paid']=null;
         $data['Ship_Sort']=request('Ship_Sort');
         $data['Adderss']=request('Adderss');
         $data['Requests']=request('Requests');
         
           ShippingOrder::where('id',$id)->update($data);
         
                $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
                      $dataUser['Screen']='امر الشحن';
           $dataUser['ScreenEn']='Shipping Order';
           $dataUser['Type']='تعديل';
           $dataUser['TypeEn']='Edit';
           $dataUser['Explain']=request('Code');
           $dataUser['ExplainEn']=request('Code');
           UsersMoves::create($dataUser);
         
         
            session()->flash('success',trans('admin.Updated'));
            return back();
     
     
     }
    
     public function DeleteShippingOrder($id){
                      
        $del=ShippingOrder::find($id);
         
         $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
                     $dataUser['Screen']='امر الشحن';
           $dataUser['ScreenEn']='Shipping Order';
           $dataUser['Type']='حذف';
           $dataUser['TypeEn']='Delete';
            $dataUser['Explain']=$del->Code;
            $dataUser['ExplainEn']=$del->Code;
           UsersMoves::create($dataUser);
         
        $del->delete();
        session()->flash('error',trans('admin.Deleted'));
        return back();

           }
    
    public function ClientPlaceFilter($client,$weight,$address){
            
        $cust=Customers::where('Account',$client)->first();
            
        $Address=Addressses::find($address);
        $ratio=Places::find($Address->Place);
            $x=$ratio->Ship_Price;
  
  

            $states=['vvalue'=>$x];
           return response()->json($states);
        
    }

     public function AddressFilter($id) {
    
         $cust=Customers::where('Account',$id)->first();
         
       $states = Addressses::where("Customer",$cust->id)->pluck("Address_Name","id");
       return response()->json($states);
           
         }

    public function VendorCollectShipping(){
 
           ShippingOrder::where('id',request('ID'))->update(['Vendor_Shipping'=>1]);
          
          $Ship= ShippingOrder::where('id',request('ID'))->first();
          
                 $res=Journalizing::orderBy('id','desc')->first();
           
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
           }else{
              $Code=1; 
               
           }    




 $ID = DB::table('journalizings')->insertGetId(
            
        array(
            
            'Code' => $Code,
            'Type' => 'سند قبض',
            'TypeEn' => 'Receipt Voucher',
            'Code_Type' => $Ship->Code,
            'Date' => date('Y-m-d'),
            'Draw' => $Ship->Draw,
            'Coin' => $Ship->Coin,
            'Cost_Center' => $Ship->Cost_Center,
            'Total_Debaitor' => $Ship->Shipping_Price,
            'Total_Creditor' => $Ship->Shipping_Price,
            'Note' => $Ship->Note,
  
        )
    );
         

            
        $PRODUCTSS['Joun_ID']=$ID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('ShipCompane');
        $PRODUCTSS['Account']=$Ship->Vendor;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$Ship->Code;
        $Gen['Date']=date('Y-m-d');
        $Gen['Type']= 'سند قبض';
        $Gen['TypeEn']= 'Receipt Voucher';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('ShipCompane');
        $Gen['Statement']=null;
        $Gen['Draw']=$Ship->Draw;
        $Gen['Debitor_Coin']= $Ship->Draw * 0;
        $Gen['Creditor_Coin']=$Ship->Draw * request('ShipCompane');
        $Gen['Account']=$Ship->Vendor;
        $Gen['Coin']= $Ship->Coin;
        $Gen['Cost_Center']=$Ship->Cost_Center;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);      
   
        
            
        $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=request('ShipCompane');
        $PRODUCTSSS['Creditor']=0;
        $PRODUCTSSS['Account']=request('Safe');
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);      
   
        $Genn['Code']=$Code;
        $Genn['Code_Type']=$Ship->Code;
        $Genn['Date']=date('Y-m-d');
            $Genn['Type']= 'سند قبض';
        $Genn['TypeEn']= 'Receipt Voucher';
        $Genn['Debitor']=request('ShipCompane');
        $Genn['Creditor']=0;
        $Genn['Statement']=null;
        $Genn['Draw']=$Ship->Draw;
        $Genn['Debitor_Coin']= $Ship->Draw * request('ShipCompane');
        $Genn['Creditor_Coin']=$Ship->Draw * 0;
        $Genn['Account']=request('Safe');
        $Genn['Coin']= $Ship->Coin;
        $Genn['Cost_Center']= $Ship->Cost_Center;
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);      
        
        
           $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=0;
        $PRODUCTSSS['Creditor']=request('ShipDelegate');
        $PRODUCTSSS['Account']=request('Safe');
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);      
   
        $Genn['Code']=$Code;
        $Genn['Code_Type']=$Ship->Code;
        $Genn['Date']=date('Y-m-d');
        $Genn['Type']='سند قبض';
        $Genn['TypeEn']='Receipt Voucher';
        $Genn['Debitor']=0;
        $Genn['Creditor']=request('ShipDelegate');
        $Genn['Statement']=null;
        $Genn['Draw']=$Ship->Draw;
        $Genn['Debitor_Coin']= $Ship->Draw * 0;
        $Genn['Creditor_Coin']=$Ship->Draw * request('ShipDelegate');
        $Genn['Account']=request('Safe');
        $Genn['Coin']= $Ship->Coin;
        $Genn['Cost_Center']= $Ship->Cost_Center;
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);      
        
                   $Emp=Employess::find($Ship->Delegate);

        
                  $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=request('ShipDelegate');
        $PRODUCTSSS['Creditor']=0;
        $PRODUCTSSS['Account']=$Emp->Commission;
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);      
   
        $Genn['Code']=$Code;
        $Genn['Code_Type']=$Ship->Code;
        $Genn['Date']=date('Y-m-d');
        $Genn['Type']='سند قبض';
        $Genn['TypeEn']='Receipt Voucher';
        $Genn['Debitor']=request('ShipDelegate');
        $Genn['Creditor']=0;
        $Genn['Statement']=null;
        $Genn['Draw']=$Ship->Draw;
        $Genn['Debitor_Coin']= $Ship->Draw * request('ShipDelegate');
        $Genn['Creditor_Coin']=$Ship->Draw * 0;
        $Genn['Account']=$Emp->Commission;
        $Genn['Coin']= $Ship->Coin;
        $Genn['Cost_Center']= $Ship->Cost_Center;
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);     
        
            
          
             return back();
        
    }
    
     public function CustomerCollectionRequests(){

          $Ship= ShippingOrder::where('id',request('ID'))->first();
         
           ShippingOrder::where('id',request('ID'))->update([
               'Cli'=>1,
               'Sure'=>1,
               'Request_Done'=>2,
                'Shipping_Price'=>request('Shipping_Price'),
                'Total'=>$Ship->Total + request('Shipping_Price'),
           ]);

         
            $Ship= ShippingOrder::where('id',request('ID'))->first();
          
                 $res=Journalizing::orderBy('id','desc')->first();
           
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
           }else{
              $Code=1; 
               
           }    

          
 $ID = DB::table('journalizings')->insertGetId(
            
        array(
            
            'Code' => $Code,
            'Type' => 'سند قبض',
            'TypeEn' =>'Receipt Voucher',
            'Code_Type' => $Ship->Code,
            'Date' => date('Y-m-d'),
            'Draw' => $Ship->Draw,
            'Coin' => $Ship->Coin,
            'Cost_Center' => $Ship->Cost_Center,
            'Total_Debaitor' => $Ship->Total,
            'Total_Creditor' => $Ship->Total,
            'Note' => $Ship->Note,
  
        )
    );
         

            
        $PRODUCTSS['Joun_ID']=$ID;
        $PRODUCTSS['Debitor']=$Ship->Total;
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=$Ship->Safe;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$Ship->Code;
        $Gen['Date']=date('Y-m-d');
        $Gen['Type']='سند قبض';
        $Gen['TypeEn']='Receipt Voucher';
        $Gen['Debitor']=$Ship->Total;
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=$Ship->Draw;
        $Gen['Debitor_Coin']= $Ship->Draw * $Ship->Total;
        $Gen['Creditor_Coin']=$Ship->Draw * 0;
        $Gen['Account']=$Ship->Safe;
        $Gen['Coin']= $Ship->Coin;
        $Gen['Cost_Center']=$Ship->Cost_Center;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);      
   

          $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=0;
        $PRODUCTSSS['Creditor']=$Ship->Total;
        $PRODUCTSSS['Account']=$Ship->Client;;
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);      
   
        $Genn['Code']=$Code;
        $Genn['Code_Type']=$Ship->Code;
        $Genn['Date']=date('Y-m-d');
        $Genn['Type']='سند قبض';
        $Genn['TypeEn']='Receipt Voucher';
        $Genn['Debitor']=0;
        $Genn['Creditor']=$Ship->Total;
        $Genn['Statement']=null;
        $Genn['Draw']=$Ship->Draw;
        $Genn['Debitor_Coin']= $Ship->Draw * 0;
        $Genn['Creditor_Coin']=$Ship->Draw * $Ship->Total;
        $Genn['Account']=$Ship->Client;
        $Genn['Coin']= $Ship->Coin;
        $Genn['Cost_Center']= $Ship->Cost_Center;
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);         
            
          
             return back();
         
         
         
         
             return back();
        
    }
    
    
    
    //MyOrdersEmpPage
     public function MyOrdersEmpPage(){
        $items=ShippingOrder::orderBy('id','desc')
            ->where('Cli',0)
            ->where('Cancel',0)
            ->where('Request_Done',0)
            ->where('Delegate',auth()->guard('admin')->user()->emp)
            ->paginate(100);

          $status=ShippingStatus::all();
         return view('admin.Shipping.MyOrders',[
             'items'=>$items,
             'status'=>$status,

         ]);
    }
    
     public function ChangeStatusOrder(){
        
         ShippingOrder::where('id',request('ID'))->update(['Status'=>request('Status')]);
        
         return back();

    }
    
      public function CustomerCollection(){
 
           ShippingOrder::where('id',request('ID'))->update([
               'Cli'=>1,
               'Safe'=>request('Safe'),
               'Paid'=>request('Paid'),
               'Residual'=>request('Residual'),
               'Emp_Note'=>request('Emp_Note')
           ]);

             return back();
        
    }
    
      public function PrintShip($id){
        $item=ShippingOrder::find($id);
        $address=Addressses::find($item->Adderss);

         return view('admin.Shipping.PrintOrders',[
             'item'=>$item,
             'address'=>$address,
         ]);
    }
    
       public function SureCustomerCollection($id){
 
           ShippingOrder::where('id',$id)->update(['Sure'=>1]);
          
          $Ship= ShippingOrder::where('id',$id)->first();
          
                 $res=Journalizing::orderBy('id','desc')->first();
           
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
           }else{
              $Code=1; 
               
           }    

          
 $ID = DB::table('journalizings')->insertGetId(
            
        array(
            
            'Code' => $Code,
            'Type' =>'سند قبض',
            'TypeEn' => 'Receipt Voucher',
            'Code_Type' => $Ship->Code,
            'Date' => date('Y-m-d'),
            'Draw' => $Ship->Draw,
            'Coin' => $Ship->Coin,
            'Cost_Center' => $Ship->Cost_Center,
            'Total_Debaitor' => $Ship->Paid,
            'Total_Creditor' => $Ship->Paid,
            'Note' => $Ship->Note,
  
        )
    );
         

            
        $PRODUCTSS['Joun_ID']=$ID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=$Ship->Paid;
        $PRODUCTSS['Account']=$Ship->Client;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$Ship->Code;
        $Gen['Date']=date('Y-m-d');
        $Gen['Type']='سند قبض';
        $Gen['TypeEn']='Receipt Voucher';
        $Gen['Debitor']=0;
        $Gen['Creditor']=$Ship->Paid;
        $Gen['Statement']=null;
        $Gen['Draw']=$Ship->Draw;
        $Gen['Debitor_Coin']= $Ship->Draw * 0;
        $Gen['Creditor_Coin']=$Ship->Draw * $Ship->Paid;
        $Gen['Account']=$Ship->Client;
        $Gen['Coin']= $Ship->Coin;
        $Gen['Cost_Center']=$Ship->Cost_Center;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);      
   
        
            
        $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=$Ship->Paid;
        $PRODUCTSSS['Creditor']=0;
        $PRODUCTSSS['Account']=$Ship->Safe;
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);      
   
        $Genn['Code']=$Code;
        $Genn['Code_Type']=$Ship->Code;
        $Genn['Date']=date('Y-m-d');
        $Genn['Type']='سند قبض';
        $Genn['TypeEn']='Receipt Voucher';
        $Genn['Debitor']=$Ship->Paid;
        $Genn['Creditor']=0;
        $Genn['Statement']=null;
        $Genn['Draw']=$Ship->Draw;
        $Genn['Debitor_Coin']= $Ship->Draw * $Ship->Paid;
        $Genn['Creditor_Coin']=$Ship->Draw * 0;
        $Genn['Account']=$Ship->Safe;
        $Genn['Coin']= $Ship->Coin;
        $Genn['Cost_Center']= $Ship->Cost_Center;
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);  
           
           
           
           
         $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=0;
        $PRODUCTSSS['Creditor']=$Ship->Shipping_Delegate;
        $PRODUCTSSS['Account']=$Ship->Safe;
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);      
   
        $Genn['Code']=$Code;
        $Genn['Code_Type']=$Ship->Code;
        $Genn['Date']=date('Y-m-d');
        $Genn['Type']='سند قبض';
        $Genn['TypeEn']='Receipt Voucher';
        $Genn['Debitor']=0;
        $Genn['Creditor']=$Ship->Shipping_Delegate;
        $Genn['Statement']=null;
        $Genn['Draw']=$Ship->Draw;
        $Genn['Debitor_Coin']= $Ship->Draw * 0;
        $Genn['Creditor_Coin']=$Ship->Draw * $Ship->Shipping_Delegate;
        $Genn['Account']=$Ship->Safe;
        $Genn['Coin']= $Ship->Coin;
        $Genn['Cost_Center']= $Ship->Cost_Center;
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);    
           
           
           $Emp=Employess::find($Ship->Delegate);
           
             $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=$Ship->Shipping_Delegate;
        $PRODUCTSSS['Creditor']=0;
        $PRODUCTSSS['Account']=$Emp->Commission;
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);      
   
        $Genn['Code']=$Code;
        $Genn['Code_Type']=$Ship->Code;
        $Genn['Date']=date('Y-m-d');
        $Genn['Type']='سند قبض';
        $Genn['TypeEn']='Receipt Voucher';
        $Genn['Debitor']=$Ship->Shipping_Delegate;
        $Genn['Creditor']=0;
        $Genn['Statement']=null;
        $Genn['Draw']=$Ship->Draw;
        $Genn['Debitor_Coin']= $Ship->Draw * $Ship->Shipping_Delegate;
        $Genn['Creditor_Coin']=$Ship->Draw * 0;
        $Genn['Account']=$Emp->Commission;
        $Genn['Coin']= $Ship->Coin;
        $Genn['Cost_Center']= $Ship->Cost_Center;
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);         
           
        
            
          
             return back();
        
    }
    
     public function CancelOrder(){
 
         if(request('CancelType') == 0){
                $p=0;
                $pp =1;
         }else{
         
                 $p=1;
                $pp =0;
         }
         
           ShippingOrder::where('id',request('ID'))->update([
               'Cancel'=>1,
               'Cancel_Note'=>request('Cancel_Note'),
               'Cancel_Pay'=>$p,
               'Cancel_Not_Pay'=>$pp,
               'Paid'=>request('Paid'),
           ]);

             return back();
        
    }
    
     public function RequestDone(){

         $tot=request('Paid') + request('ShipDelegate') ;
           ShippingOrder::where('id',request('ID'))->update([
               'Vend'=>1,
               'Request_Done'=>1,
              'Safe'=>request('Safe'),
                'Paid'=>request('Paid'),
                'Total'=>$tot,
               'Emp_Note'=>request('Emp_Note')
           ]);

         
            $Ship= ShippingOrder::where('id',request('ID'))->first();
          
                 $res=Journalizing::orderBy('id','desc')->first();
           
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
           }else{
              $Code=1; 
               
           }    

          
 $ID = DB::table('journalizings')->insertGetId(
            
        array(
            
            'Code' => $Code,
            'Type' => 'سند صرف',
            'TypeEn' => 'Payment Voucher',
            'Code_Type' => $Ship->Code,
            'Date' => date('Y-m-d'),
            'Draw' => $Ship->Draw,
            'Coin' => $Ship->Coin,
            'Cost_Center' => $Ship->Cost_Center,
            'Total_Debaitor' => $Ship->Total,
            'Total_Creditor' => $Ship->Total,
            'Note' => $Ship->Note,
  
        )
    );
         

            
        $PRODUCTSS['Joun_ID']=$ID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=$Ship->Total;
        $PRODUCTSS['Account']=$Ship->Safe;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$Ship->Code;
        $Gen['Date']=date('Y-m-d');
        $Gen['Type']='سند صرف';
        $Gen['TypeEn']='Payment Voucher';
        $Gen['Debitor']=0;
        $Gen['Creditor']=$Ship->Total;
        $Gen['Statement']=null;
        $Gen['Draw']=$Ship->Draw;
        $Gen['Debitor_Coin']= $Ship->Draw * 0;
        $Gen['Creditor_Coin']=$Ship->Draw * $Ship->Total;
        $Gen['Account']=$Ship->Safe;
        $Gen['Coin']= $Ship->Coin;
        $Gen['Cost_Center']=$Ship->Cost_Center;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);      
   
           
           $Emp=Employess::find($Ship->Delegate);
           
        $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=$Ship->Shipping_Delegate;
        $PRODUCTSSS['Creditor']=0;
        $PRODUCTSSS['Account']=$Emp->Commission;
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);      
   
        $Genn['Code']=$Code;
        $Genn['Code_Type']=$Ship->Code;
        $Genn['Date']=date('Y-m-d');
        $Genn['Type']='سند صرف';
        $Genn['TypeEn']='Payment Voucher';
        $Genn['Debitor']=$Ship->Shipping_Delegate;
        $Genn['Creditor']=0;
        $Genn['Statement']=null;
        $Genn['Draw']=$Ship->Draw;
        $Genn['Debitor_Coin']= $Ship->Draw * $Ship->Shipping_Delegate;
        $Genn['Creditor_Coin']=$Ship->Draw * 0;
        $Genn['Account']=$Emp->Commission;
        $Genn['Coin']= $Ship->Coin;
        $Genn['Cost_Center']= $Ship->Cost_Center;
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);         
           
        
          $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=$Ship->Paid;
        $PRODUCTSSS['Creditor']=0;
        $PRODUCTSSS['Account']=$Ship->Client;;
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);      
   
        $Genn['Code']=$Code;
        $Genn['Code_Type']=$Ship->Code;
        $Genn['Date']=date('Y-m-d');
        $Genn['Type']='سند صرف';
        $Genn['TypeEn']='Payment Voucher';
        $Genn['Debitor']=$Ship->Paid;
        $Genn['Creditor']=0;
        $Genn['Statement']=null;
        $Genn['Draw']=$Ship->Draw;
        $Genn['Debitor_Coin']= $Ship->Draw * $Ship->Paid;
        $Genn['Creditor_Coin']=$Ship->Draw * 0;
        $Genn['Account']=$Ship->Client;
        $Genn['Coin']= $Ship->Coin;
        $Genn['Cost_Center']= $Ship->Cost_Center;
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);         
            
          
             return back();
         
        
    }
    
    
    //Report  My Order
    public function ReportMyOrdersEmpPage(){
        
             $Orders_Num=ShippingOrder::orderBy('id','desc')
            ->where('Delegate',auth()->guard('admin')->user()->emp)
            ->count();
        
             $Total_Orders=ShippingOrder::orderBy('id','desc')
            ->where('Cancel',0)     
            ->where('Delegate',auth()->guard('admin')->user()->emp)
            ->get()->sum('Total');
        
                     $Order_Num_Pending=ShippingOrder::orderBy('id','desc')
            ->where('Cli',0)              
            ->where('Delegate',auth()->guard('admin')->user()->emp)
            ->count();

        
                  $Order_Num_Recived=ShippingOrder::orderBy('id','desc')
            ->where('Cli',1)  
                      ->where('Cancel',0)                        
            ->where('Delegate',auth()->guard('admin')->user()->emp)
            ->count();
        
        
             $Order_Total_Recived=ShippingOrder::orderBy('id','desc')
            ->where('Cli',1)     
             ->where('Cancel',0)       
            ->where('Delegate',auth()->guard('admin')->user()->emp)
            ->get()->sum('Total');
        
         $Order_Total_Pending=ShippingOrder::orderBy('id','desc')
            ->where('Cli',0)      
              ->where('Cancel',0)  
            ->where('Delegate',auth()->guard('admin')->user()->emp)
            ->get()->sum('Total');
        
   $Money_Client_Recived=ShippingOrder::orderBy('id','desc')
            ->where('Cli',1)  
     ->where('Cancel',0)     
            ->where('Delegate',auth()->guard('admin')->user()->emp)
            ->get()->sum('Paid');

      $TotCanceled=ShippingOrder::orderBy('id','desc')
            ->where('Cli',1)      
            ->where('Cancel',1)      
            ->where('Delegate',auth()->guard('admin')->user()->emp)
            ->count();    
       
           $TotPrecent=ShippingOrder::orderBy('id','desc')
            ->where('Cli',1)      
            ->where('Delegate',auth()->guard('admin')->user()->emp)
            ->get()->sum('Shipping_Delegate');
        

        
         return view('admin.Shipping.ReportMyOrders',[
             
             'Orders_Num'=>$Orders_Num,
             'Total_Orders'=>$Total_Orders,
             'Order_Num_Pending'=>$Order_Num_Pending,
             'Order_Num_Recived'=>$Order_Num_Recived,
             'Order_Total_Recived'=>$Order_Total_Recived,
             'Order_Total_Pending'=>$Order_Total_Pending,
             'Money_Client_Recived'=>$Money_Client_Recived,
             'TotCanceled'=>$TotCanceled,
             'TotPrecent'=>$TotPrecent,
             
         ]);
    }
    
       public function FilterReportMyOrders(){
        
             $Orders_Num=ShippingOrder::orderBy('id','desc')
            ->where('Delegate',auth()->guard('admin')->user()->emp)
         ->whereBetween('Date', [request('From'), request('To')])          
            ->count();
        
             $Total_Orders=ShippingOrder::orderBy('id','desc')
                   ->where('Cancel',0)  
            ->where('Delegate',auth()->guard('admin')->user()->emp)
                 ->whereBetween('Date', [request('From'), request('To')])  
            ->get()->sum('Total');
        
                     $Order_Num_Pending=ShippingOrder::orderBy('id','desc')
            ->where('Cli',0)              
            ->where('Delegate',auth()->guard('admin')->user()->emp)
         ->whereBetween('Date', [request('From'), request('To')])                  
            ->count();

        
                  $Order_Num_Recived=ShippingOrder::orderBy('id','desc')
            ->where('Cli',1)    
               ->where('Cancel',0)           
            ->where('Delegate',auth()->guard('admin')->user()->emp)
         ->whereBetween('Date', [request('From'), request('To')])               
            ->count();
        
        
             $Order_Total_Recived=ShippingOrder::orderBy('id','desc')
            ->where('Cli',1)     
                    ->where('Cancel',0) 
            ->where('Delegate',auth()->guard('admin')->user()->emp)
         ->whereBetween('Date', [request('From'), request('To')])          
            ->get()->sum('Total');
        
         $Order_Total_Pending=ShippingOrder::orderBy('id','desc')
            ->where('Cli',0)  
               ->where('Cancel',0)  
            ->where('Delegate',auth()->guard('admin')->user()->emp)
             ->whereBetween('Date', [request('From'), request('To')])  
            ->get()->sum('Total');
        
   $Money_Client_Recived=ShippingOrder::orderBy('id','desc')
            ->where('Cli',1)   
        ->where('Cancel',0)   
            ->where('Delegate',auth()->guard('admin')->user()->emp)
      ->whereBetween('Date', [request('From'), request('To')])   
            ->get()->sum('Paid');

                $TotCanceled=ShippingOrder::orderBy('id','desc')
            ->where('Cli',1)      
            ->where('Cancel',1)      
            ->where('Delegate',auth()->guard('admin')->user()->emp)
           ->whereBetween('Date', [request('From'), request('To')])              
            ->count();    
       
           $TotPrecent=ShippingOrder::orderBy('id','desc')
            ->where('Cli',1)      
            ->where('Delegate',auth()->guard('admin')->user()->emp)
               ->whereBetween('Date', [request('From'), request('To')])     
            ->get()->sum('Shipping_Delegate');
   
           
         return view('admin.Shipping.ReportMyOrders',[
             
             'Orders_Num'=>$Orders_Num,
             'Total_Orders'=>$Total_Orders,
             'Order_Num_Pending'=>$Order_Num_Pending,
             'Order_Num_Recived'=>$Order_Num_Recived,
             'Order_Total_Recived'=>$Order_Total_Recived,
             'Order_Total_Pending'=>$Order_Total_Pending,
             'Money_Client_Recived'=>$Money_Client_Recived,
              'TotCanceled'=>$TotCanceled,
             'TotPrecent'=>$TotPrecent,
             
         ]);
    }
    
    //VendorCoolections 
      public function VendorCoolectionsPage(){
        $items=ShippingOrder::orderBy('id','desc')->where('Cli',1)
            ->where('Vend',0)
            ->where('Ship_Sort',2)
            ->paginate(100);
        
               $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
          
          $status=ShippingStatus::all();
         return view('admin.Shipping.VendorCoolections',[
             'items'=>$items,
             'status'=>$status,
             'Safes'=>$Safes,
         ]);
    }
    
      public function PostVendorCollection(){
 
           ShippingOrder::where('id',request('ID'))->update(['Vend'=>1]);
          
          $Ship= ShippingOrder::where('id',request('ID'))->first();
          
                 $res=Journalizing::orderBy('id','desc')->first();
           
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
           }else{
              $Code=1; 
               
           }    

          
 $ID = DB::table('journalizings')->insertGetId(
            
        array(
            
            'Code' => $Code,
            'Type' => 'سند صرف',
            'TypeEn' => 'Payment Voucher',
            'Code_Type' => $Ship->Code,
            'Date' => date('Y-m-d'),
            'Draw' => $Ship->Draw,
            'Coin' => $Ship->Coin,
            'Cost_Center' => $Ship->Cost_Center,
            'Total_Debaitor' => request('Amount'),
            'Total_Creditor' => request('Amount'),
            'Note' => $Ship->Note,
  
        )
    );
         

            
        $PRODUCTSS['Joun_ID']=$ID;
        $PRODUCTSS['Debitor']=request('Amount');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=$Ship->Vendor;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$Ship->Code;
        $Gen['Date']=date('Y-m-d');
        $Gen['Type']='سند صرف';
        $Gen['TypeEn']='Payment Voucher';
        $Gen['Debitor']=request('Amount');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=$Ship->Draw;
        $Gen['Debitor_Coin']= $Ship->Draw * request('Amount');
        $Gen['Creditor_Coin']=$Ship->Draw * 0;
        $Gen['Account']=$Ship->Vendor;
        $Gen['Coin']= $Ship->Coin;
        $Gen['Cost_Center']=$Ship->Cost_Center;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);      
   
        
            
        $PRODUCTSSS['Joun_ID']=$ID;
        $PRODUCTSSS['Debitor']=0;
        $PRODUCTSSS['Creditor']=request('Amount');
        $PRODUCTSSS['Account']=request('Safe');
        $PRODUCTSSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSSS);      
   
        $Genn['Code']=$Code;
        $Genn['Code_Type']=$Ship->Code;
        $Genn['Date']=date('Y-m-d');
        $Genn['Type']='سند صرف';
        $Genn['TypeEn']='Payment Voucher';
        $Genn['Debitor']=0;
        $Genn['Creditor']=request('Amount');
        $Genn['Statement']=null;
        $Genn['Draw']=$Ship->Draw;
        $Genn['Debitor_Coin']= $Ship->Draw * 0;
        $Genn['Creditor_Coin']=$Ship->Draw * request('Amount');
        $Genn['Account']=request('Safe');
        $Genn['Coin']= $Ship->Coin;
        $Genn['Cost_Center']= $Ship->Cost_Center;
        $Genn['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Genn);      
        
            
          
             return back();
        
    }
    
    //ReportOrdersPage
     public function ReportOrdersPage(){
        $items=ShippingOrder::orderBy('id','desc')->paginate(100);
        $CostCenters=CostCenter::all();
        $Coins=Coins::all();  
        $Types=ShippingType::all();
        $Status=ShippingStatus::all();
        $Clients = AcccountingManual::
             where('Type',1)
              ->where('Parent',24)
              ->get();
        $Vendors = AcccountingManual::
             where('Type',1)
              ->where('Parent',37)
              ->get();
      $Employess = Employess::where("EmpSort",1)->where('Active',1)->get();

           $count=ShippingOrder::all()->count();
           $TotCancel=ShippingOrder::where('Cancel',1)->count();
           $TotS=ShippingOrder::get()->sum('Shipping_Price');
           $Tot=ShippingOrder::where('Cancel',0)->get()->sum('Total');
           $TotPay=ShippingOrder::where('Cancel',0)->get()->sum('Paid');
           $TotDele=ShippingOrder::get()->sum('Shipping_Delegate');
  
         
         return view('admin.Shipping.FilterOrders',[
             'items'=>$items,
             'Clients'=>$Clients,
             'Vendors'=>$Vendors,
             'Employess'=>$Employess,
             'Types'=>$Types,
             'Status'=>$Status,
             'CostCenters'=>$CostCenters,
             'Coins'=>$Coins,
             'count'=>$count,
             'TotS'=>$TotS,
             'Tot'=>$Tot,
             'TotCancel'=>$TotCancel,
             'TotPay'=>$TotPay,
             'TotDele'=>$TotDele,
         
         ]);
    }
    
    function FilterOrders(Request $request)
             {
           
     if($request->ajax())
     { 
      $output = '';
      $from = $request->get('From');             
      $to = $request->get('To');             
      $client = $request->get('Client');             
      $vendor = $request->get('Vendor');             
      $type = $request->get('Type');             
      $status = $request->get('Status');             
      $delegate = $request->get('Delegate');             
      $code = $request->get('Code');             
      $Ship_Sort = $request->get('Ship_Sort');             
      $Cancel = $request->get('Cancel');             
                               
if($from != '' or $to != '' or  $client != '' or $vendor != '' or $type != '' or $status != '' or $delegate != '' or $code != '' or $Ship_Sort != '' or $Cancel != '')
    {

 if($from != '' and $to != ''){
            
        $f= 'Date' ; 
        $fR=  [$from,$to];        
         $fName= "whereBetween" ;    
 
         }elseif($from != '' and $to == ''){
         
           $f= 'Date' ; 
         $fR=  [$from,date('Y-m-d')];       
         $fName= "whereBetween" ;    

     }elseif($from == '' and $to != ''){
         
           $f= 'Date' ; 
         $fR=  ['2021-01-01',$to];       
         $fName= "whereBetween" ;    

     }elseif($from == '' and $to == ''){

         $f= 'id' ; 
        $fR=  'asc' ;      
          $fName=   "orderBy" ;
         }    
    

        if($client != ''){
            
          $cName= "where" ; 
        $c= 'Client' ; 
        $cR=  $client;        
          
 
     }else{

         $cName=   "orderBy" ;
         $c= 'id' ; 
        $cR=  'asc' ;      
         
         }    
    
     if($vendor != ''){
            
          $vName= "where" ; 
        $v= 'Vendor' ; 
        $vR=  $vendor;        
          
 
     }else{

         $vName=   "orderBy" ;
         $v= 'id' ; 
        $vR=  'asc' ;      
         
         }  
    
    if($type != ''){
            
          $tyName= "where" ; 
        $ty= 'Type' ; 
        $tyR=  $type;        
          
 
     }else{

         $tyName=   "orderBy" ;
         $ty= 'id' ; 
        $tyR=  'asc' ;      
         
         }  
    
      if($status != ''){
            
          $sName= "where" ; 
        $s= 'Status' ; 
        $sR=  $status;        
          
 
     }else{

         $sName=   "orderBy" ;
         $s= 'id' ; 
        $sR=  'asc' ;      
         
         }  
    
    if($delegate != ''){
            
          $dName= "where" ; 
        $d= 'Delegate' ; 
        $dR=  $delegate;        
          
 
     }else{

         $dName=   "orderBy" ;
         $d= 'id' ; 
        $dR=  'asc' ;      
         
         }  
    
     if($code != ''){
            
          $codeName= "where" ; 
        $code= 'Code' ; 
        $codeR=  $code;        
          
 
     }else{

         $codeName=   "orderBy" ;
         $code= 'id' ; 
        $codeR=  'asc' ;      
         
         }  
    
     if($Ship_Sort != ''){
            
          $SOrtName= "where" ; 
        $Sortd= 'Ship_Sort' ; 
        $SortR=  $Ship_Sort;        
          
 
     }else{

         $SOrtName=   "orderBy" ;
         $Sortd= 'id' ; 
        $SortR=  'asc' ;      
         
         }  
    
       if($Cancel != ''){
            
          $CancelName= "where" ; 
        $Canceld= 'Cancel' ; 
        $CancelR=  $Cancel;        
          
 
     }else{

         $CancelName=   "orderBy" ;
         $Canceld= 'id' ; 
        $CancelR=  'asc' ;      
         
         }  
    

    
        $data=ShippingOrder::orderBy('id','desc')
             ->$fName($f,$fR)
             ->$cName($c,$cR)
             ->$vName($v,$vR)
             ->$tyName($ty,$tyR)
             ->$sName($s,$sR)
             ->$dName($d,$dR)
             ->$codeName($code,$codeR)
             ->$SOrtName($Sortd,$SortR)
             ->$CancelName($Canceld,$CancelR)
          ->get(); 
    
      $OrNum=ShippingOrder::orderBy('id','desc')
             ->$fName($f,$fR)
             ->$cName($c,$cR)
             ->$vName($v,$vR)
             ->$tyName($ty,$tyR)
             ->$sName($s,$sR)
             ->$dName($d,$dR)
             ->$codeName($code,$codeR)
             ->$SOrtName($Sortd,$SortR)
             ->$CancelName($Canceld,$CancelR)
          ->count(); 
    
      $OrCancel=ShippingOrder::where('Cancel',1)
             ->$fName($f,$fR)
             ->$cName($c,$cR)
             ->$vName($v,$vR)
             ->$tyName($ty,$tyR)
             ->$sName($s,$sR)
             ->$dName($d,$dR)
             ->$codeName($code,$codeR)
              ->$SOrtName($Sortd,$SortR)
            ->$CancelName($Canceld,$CancelR)
          ->count(); 
    
    
         $OrShTo=ShippingOrder::orderBy('id','desc')
             ->$fName($f,$fR)
             ->$cName($c,$cR)
             ->$vName($v,$vR)
             ->$tyName($ty,$tyR)
             ->$sName($s,$sR)
             ->$dName($d,$dR)
             ->$codeName($code,$codeR)
                 ->$SOrtName($Sortd,$SortR)
               ->$CancelName($Canceld,$CancelR)
          ->get()->sum('Shipping_Price'); 

       $OrT=ShippingOrder::where('Cancel',0)
             ->$fName($f,$fR)
             ->$cName($c,$cR)
             ->$vName($v,$vR)
             ->$tyName($ty,$tyR)
             ->$sName($s,$sR)
             ->$dName($d,$dR)
             ->$codeName($code,$codeR)
               ->$SOrtName($Sortd,$SortR)
             ->$CancelName($Canceld,$CancelR)
          ->get()->sum('Total'); 
    
     $OrTP=ShippingOrder::where('Cancel',0)
             ->$fName($f,$fR)
             ->$cName($c,$cR)
             ->$vName($v,$vR)
             ->$tyName($ty,$tyR)
             ->$sName($s,$sR)
             ->$dName($d,$dR)
             ->$codeName($code,$codeR)
             ->$SOrtName($Sortd,$SortR)
           ->$CancelName($Canceld,$CancelR)
          ->get()->sum('Paid'); 
    
         $OrTD=ShippingOrder::orderBy('id','desc')
             ->$fName($f,$fR)
             ->$cName($c,$cR)
             ->$vName($v,$vR)
             ->$tyName($ty,$tyR)
             ->$sName($s,$sR)
             ->$dName($d,$dR)
             ->$codeName($code,$codeR)
                 ->$SOrtName($Sortd,$SortR)
               ->$CancelName($Canceld,$CancelR)
          ->get()->sum('Shipping_Delegate');
    

     }

         $total_row = $data->count();
      if($total_row > 0) 
      { 
         foreach($data as $row){  

                if($row->Breakable == 1){
                                      
                  $break=trans('admin.Yes');  
                }else{
                    
              $break=trans('admin.No'); 
                }
                        
             if($row->Open == 1){
                                      
                    $OPPEN=trans('admin.Yes'); 
                }else{
                    
                $OPPEN=trans('admin.No'); 
                } 

                 if($row->Ship_Sort == 1){
                                      
                  $SORT=trans('admin.Backup');  
    $REQ= '<button type="button" class="btn btn-default" data-toggle="modal" data-target="#Requests'.$row->id.'">   '.trans('admin.Requests').'      </button>';
                }else{
                    
                $SORT=trans('admin.DeropOff');    
                $REQ='';     
                } 

             
             
                if(!empty($row->Cost_Center)) {   
                    
                   if(app()->getLocale() == 'ar' ){     
                    $cost=$row->Cost_Center()->first()->Arabic_Name;
                   }else{
                     $cost=$row->Cost_Center()->first()->English_Name;        
                       
                   }
         }else{
                    
                 $cost='';   
                }
             
             
             
             
                 if(!empty($row->Vendor)) {   
                     
                      if(app()->getLocale() == 'ar' ){      
                    $vendo=$row->Vendor()->first()->Name;
                      }else{
                   $vendo=$row->Vendor()->first()->NameEn;          
                      }
                          
         }else{
                    
                 $vendo='';   
                }

                        if($row->Cancel == 1){
                           $style='style="background: darkred;color: white"'; 
                        }else{
                            $style='';
                        }
                
                  if(app()->getLocale() == 'ar' ){ 
                      $CoiName=$row->Coin()->first()->Arabic_Name; 
                      $StuName=$row->Status()->first()->Arabic_Name; 
                      $TypName=$row->Type()->first()->Arabic_Name; 
                      $DeleName=$row->Delegate()->first()->Name; 
                      $CliNemo=$row->Client()->first()->Name; 
                   
                   }else{
                 $CoiName=$row->Coin()->first()->English_Name; 
                      $StuName=$row->Status()->first()->English_Name; 
                      $TypName=$row->Type()->first()->English_Name; 
                      $DeleName=$row->Delegate()->first()->NameEn; 
                      $CliNemo=$row->Client()->first()->NameEn; 
                       
                   }   
             
             
        $output .= '
        
       <tr '.$style.'>
        <td>
        '.$row->Code.'
        </td>
           <td>
        '.$row->Date.'
        </td>
           <td>
        '.$row->Weight.'
        </td>
           <td>
        '.$row->Number.'
        </td>
           <td>
        '.$row->Goods_Price.'
        </td>
           <td>
        '.$row->Shipping_Price.'
        </td>
               <td>
        '.$row->Total.'
        </td>
        
        <td>
        '.$break.'
        </td>
   
          <td>
        '.$row->Note.'
        </td>
        
            <td>
        '.$CoiName.'
        </td>

           <td>
        '.$cost.'
        </td>
        
        <td>
        '.$row->Draw.'
        </td>
   
       <td>
        '.$StuName.'
        </td>
        
            <td>
        '.$TypName.'
        </td>
        
            <td>
        '.$DeleName.'
        </td>
                   <td>
        '.$row->Delegate()->first()->Shipping_Precent.'
        </td>
        
            <td>
        '.$vendo.'
        </td>
        
            <td>
        '.$CliNemo.'
        </td>


         <td>
               <button type="button" class="btn btn-default" data-toggle="modal" data-target="#client'.$row->id.'">
                      
                    '.trans('admin.Client_Address').'         
                                                        </button>
            </td>
                                                    
                                                              <td>
                                       '.$OPPEN.'    
                                                    </td>    
                                                    
                                                    <td>
                                                    '.$row->Paid.'
                                                    </td>
                                                    
                                                    <td>
                                        '.$SORT.'    
                                                    </td>  
                                                   
                                                    
                                                                                     <td>
                       '.$REQ.'         
                                                    </td>
                                                    



        </tr>

            ';

        
        }  

      }
      else
      {
       $output = '
        <div class="col-md-3">  '.trans('admin.No_Data_Find').'</div>
       ';
      }
      $data = array(
       'table_data'  => $output,
       'OrNum'  => $OrNum,
       'OrShTo'  => $OrShTo,
       'OrT'  => $OrT,
       'OrCancel'  => $OrCancel,
       'OrTP'  => $OrTP,
       'OrTD'  => $OrTD,
      );
      echo json_encode($data);
     }
    }
    
    
    
    // ================= Tickets ==============================
    
            public function TicketsPage(){
         if(auth()->guard('admin')->user()->emp == 0){
         
         $Stores=Stores::all();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->store)){
                
                   if(auth()->guard('admin')->user()->pos_stores == 0){
                       
                          $Stores=Stores::where('id',auth()->guard('admin')->user()->store)->get();
                   }else{
                       
                     $Stores=Stores::all();    
                   }    
                
                
            }else{
                
                 $Stores=Stores::all();
            }
         
     }   
     
       if(auth()->guard('admin')->user()->emp == 0){
         
          $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->safe)){
         $Safes=AcccountingManual::where('id',auth()->guard('admin')->user()->safe)->get();
            }else{
                
                  $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
            }
         
     }
          $ItemsGroups=ItemsGroups::all();
                    $Units=Measuerments::all();
          
          $Clients = AcccountingManual::
             where('Type',1)
              ->where('Parent',24)
              ->get();
          
                
      $res=Ticket::orderBy('id','desc')->first();
           
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
               
           }else{
               
              $Code=1; 
               
           }
                      
                $Coins=Coins::all();
                
                
                    $ress=Customers::orderBy('id','desc')->first();
           
           if(!empty($ress->Code)){
               
              $CodeUser=$ress->Code + 1 ; 
               
           }else{
               
              $CodeUser=1; 
               
           }
                
                    $Governrate=Governrate::all();
         return view('admin.Shipping.Tickets',[
             'Stores'=>$Stores,
             'Safes'=>$Safes,
             'Clients'=>$Clients,
             'Code'=>$Code,
             'Coins'=>$Coins,
             'CodeUser'=>$CodeUser,
             'Governrate'=>$Governrate,
             'ItemsGroups'=>$ItemsGroups,
             'Units'=>$Units,
         
         ]);
    }
    
         function ShippingTicketProductsFilter(Request $request)
             {  
     if($request->ajax())
     { 
      $output = '';
      $search = $request->get('search');             
      
    if($search != '')
    {

     $data =ProductUnits::    
              where('P_Ar_Name','ILIKE', "%{$search}%")                  
            ->orWhere('P_En_Name','ILIKE', "%{$search}%")    
             ->orWhere('Barcode','ILIKE', "%{$search}%")    
                      ->take(100)  
          ->get();   
        
        $def=ShippingDefault::orderBy('id','desc')->first();
                           
     }

         $total_row = $data->count();
      if($total_row > 0) 
      { 

         foreach($data as $rows){  
  

            if($rows->Product()->first()->Status == 0){
                
     $units=ProductUnits::where('Product',$rows->Product)->get();
         $rr=ProductUnits::where('Product',$rows->Product)->where('Def',1)->first();
         $pr= $rr->Price ;  
        
        if(auth()->guard('admin')->user()->emp != 0){
            
      
    
     if(auth()->guard('admin')->user()->ticket_price == 1){ 
          $show="";
     }else{
         
       $show="readonly";  
     }

    
        }else{
             $show="";  
            
        }          
               
                
            if($def->Show_Code == 1){
                $ShowCode='block';
            }else{
                 $ShowCode='none'; 
            } 
                
                 if($def->Show_Weight == 1){
                $Show_Weight='block';
            }else{
                 $Show_Weight='none'; 
            }   
                
                     if($def->Show_Width == 1){
                $Show_Width='block';
            }else{
                 $Show_Width='none'; 
            }   
                
                     if($def->Show_Length == 1){
                $Show_Length='block';
            }else{
                 $Show_Length='none'; 
            }   
                
                     if($def->Show_Height == 1){
                $Show_Height='block';
            }else{
                 $Show_Height='none'; 
            }   
               
         if(app()->getLocale() == 'ar' ){ 
                      $PrrroName=$rows->P_Ar_Name; 
                      $UniiName=$rr->Unit()->first()->Name; 

                   
                   }else{
                         $PrrroName=$rows->P_En_Name;  
                       $UniiName=$rr->Unit()->first()->NameEn;    
  
                       
                   }               
                
                
        $output .= '
        
       <tr id="Row'.$rows->id.'">
        <td>
        '.$PrrroName.'
 <input type="hidden"  id="P_Ar_Name'.$rows->id.'" value="'.$rows->P_Ar_Name.'">
        <input type="hidden"  id="P_En_Name'.$rows->id.'" value="'.$rows->P_En_Name.'">
        <input type="hidden"  id="Product'.$rows->id.'" value="'.$rows->Product.'">
        </td>
        
        <td>
             <select class="select2 form-control w-100"   id="UnitPurch'.$rows->id.'" onchange="UnitCodePurchh('.$rows->id.')">
                <option value="">  '.trans('admin.Choice_Unit').'</option>
              ';
             
            foreach($units as $uni){
                $nam=Measuerments::find($uni->Unit);
                
                       if(app()->getLocale() == 'ar' ){ 
                       $UnitNamme=$nam->Name;
                   }else{
                       
                       $UnitNamme=$nam->NameEn; 
                   }
                  $output .= '
            <option value="'.$uni->Unit.'"       ';  if($uni->Def == 1){    $output .= '  selected  ';  }   $output .= ' > '.$UnitNamme.'</option>
                 ';
                
          
                        }
            
                $output .= '      
                  
                        </select>
        </td>
        <td style="display:'.$ShowCode.'">
         <input type="text" id="CodePurch'.$rows->id.'" class="form-control" value="'.$rr->Barcode.'"  disabled> 
         <input type="hidden" id="UnitPurchName'.$rows->id.'" value="'.$UniiName.'"> 
          <input type="hidden" id="UnitDefault'.$rows->id.'" value="'.$rr->Unit.'">
             <input type="hidden" id="CodeDefault'.$rows->id.'" value="'.$rr->Barcode.'"> 
        </td>
        
  
              <td>

 <input type="number" id="Price'.$rows->id.'" '.$show.' step="any"  class="form-control" onkeyup="PurchTotal('.$rows->id.')" onclick="PurchTotal('.$rows->id.')" value="'.$pr.'"  >

        </td>
        
         <td style="display:'.$Show_Weight.'">
        <input type="number" id="Weight'.$rows->id.'"   class="form-control" value="0"> 
        </td> 
        
                 <td style="display:'.$Show_Length.'">
        <input type="number" id="Length'.$rows->id.'"   class="form-control" value="0"> 
        </td>   
        
        
                 <td style="display:'.$Show_Width.'">
        <input type="number" id="Width'.$rows->id.'"   class="form-control" value="0"> 
        </td>   
        
                 <td style="display:'.$Show_Height.'">
        <input type="number" id="Height'.$rows->id.'"   class="form-control" value="0"> 
        </td>   
       
  
        <td>
        <input type="number" id="Qty'.$rows->id.'"   class="form-control" onkeyup="PurchTotal('.$rows->id.')" onclick="PurchTotal('.$rows->id.')" value="1" > 
        </td>
        
                      <td>

 <input type="number" id="Total'.$rows->id.'" readonly step="any"  class="form-control"  value="'.$pr.'"  >

        </td>


        <td>
 <button type="button" class="btn btn-default waves-effect waves-themed" style="display:block" id="AddBtnPur'.$rows->id.'" onclick="Fun('.$rows->id.')">
          <i class="fal fa-plus"></i>
          </button> 

          </td>
        </tr>
        
       
            ';
        }
        
        

        }      

      }else
      {
       $output = '
        <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
       ';
      }
      $data = array(
       'table_data'  => $output,
      );
      echo json_encode($data);
     }
    }
    
        public function UnitShippingProFilter($countryId,$Pro){
            
     
        $rr=ProductUnits::where('Product',$Pro)->where('Unit',$countryId)->first();
            $x=$rr->Price;
            
               if(app()->getLocale() == 'ar' ){ 
            $y=$rr->Unit()->first()->Name;
               }else{
                   
             $y=$rr->Unit()->first()->NameEn;        
               }
  

            $states=['price'=>$x,'name'=>$y];
           return response()->json($states);
        
    }

            public function AddressPhoneClient($countryId){
            
     
        $rr=Customers::where('Account',$countryId)->first();
                
                
            if(!empty($rr->Address)){
                $address=$rr->Address;
            }else{
                
             $address='';   
            }  
                
                
                      if(!empty($rr->Phone)){
                $phone=$rr->Phone;
            }else{
                
             $phone='';   
            }   
            
 


            $states=['address'=>$address,'phone'=>$phone];
           return response()->json($states);
        
    }

          public function AddTicket(){
         
            $data= $this->validate(request(),[
             'Code'=>'required',
             'Date'=>'required',
             'Sender_Name'=>'required',
             'Addressees_Name'=>'required',
             'Total'=>'required',
             'Store'=>'required',
             'Safe'=>'required',
             'Coin'=>'required',
             'Access_Area'=>'required',

               ],[
            

         ]);
         

           $ID = DB::table('tickets')->insertGetId(
        array(
            
            'Code' => request('Code'),
            'Date' => request('Date'),
            'Payment_Method' => request('Payment_Method'),
            'Sender_Name' => request('Sender_Name'),
            'Sender_Address' => request('Sender_Address'),
            'Sender_Phone' => request('Sender_Phone'),
            'Addressees_Name' => request('Addressees_Name'),
            'Addressees_Address' => request('Addressees_Address'),
            'Addressees_Phone' => request('Addressees_Phone'),
            'Notes' => request('Note'),
            'Sub_Total' => request('Sub_Total'),
            'Discount' => request('Discount'),
            'Total' => request('Total_Price'),
            'Store' => request('Store'),
            'Safe' => request('Safe'),
            'Recived' =>0,
            'Selected' =>0,
            'Coin' => request('Coin'),
            'Draw' => request('Draw'),
            'Access_Area' => request('Access_Area'),
            'Product_Numbers' => request('Product_Numbers'),
            'Total_Qty' => request('Total_Qty'),
        )
    );  
    
              
              
                    $c= DB::select("SELECT last_value FROM tickets_arr_seq");
      $f=array_shift($c);
      $z=end($f);    
  $CodeT=$z;   
         
        if(!empty(request('Unit'))){
            
                   StoreCountSales::truncate();   
              $Price=request('Price');
              $P_Ar_Name=request('P_Ar_Name');
              $P_En_Name=request('P_En_Name');
              $Unit=request('Unit');
              $P_Code=request('P_Code');
              $Weight=request('Weight');
              $Length=request('Length');
              $Width=request('Width');
              $Height=request('Height');
              $Qty=request('Qty');
              $Total=request('Total');
              $Product=request('Product');
       

            for($i=0 ; $i < count($Unit) ; $i++){

            $pp=ProductUnits::where('Product',$Product[$i])->where('Unit',$Unit[$i])->first();    
            $plow=ProductUnits::where('Product',$Product[$i])->where('Rate',1)->first();   
                
                $uu['Product_Code']=$P_Code[$i];
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['Price']=$Price[$i];
                $uu['Weight']=$Weight[$i];
                $uu['Length']=$Length[$i];
                $uu['Width']=$Width[$i];
                $uu['Height']=$Height[$i];
                $uu['Qty']=$Qty[$i];
                $uu['Unit']=$Unit[$i];
                $uu['Total']=$Total[$i];
                $uu['Store']=request('Store');
                $uu['Product']=$Product[$i];
                $uu['Ticket']=$ID;
                
               TicketProducts::create($uu); 
                
    $prooooo=Products::find($Product[$i]); 

                 $Quantity =ProductsQty::
                where('Store',request('Store'))    
                ->where('Product',$Product[$i])    
                ->where('P_Code',$P_Code[$i])    
                ->first(); 

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('Store'))    
                ->where('Product',$Product[$i])    
                ->where('PP_Code',$P_Code[$i])    
                ->first(); 

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('Store'))    
                ->where('Product',$Product[$i])    
                ->where('PPP_Code',$P_Code[$i])    
                ->first(); 


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('Store'))    
                ->where('Product',$Product[$i])    
                ->where('PPPP_Code',$P_Code[$i])    
                ->first(); 

}



}






}

                
            if(!empty($Quantity)){    
           $unit=ProductUnits::where('Unit',$Unit[$i])->where('Product',$Product[$i])->first();  
                
           $qq= $unit->Rate * $Qty[$i] ;
                
           $newqty=$Quantity->Qty +  $qq ; 
                
       
                  $prooooo=Products::find($Product[$i]); 

   $plow=ProductUnits::where('Product',$Product[$i])->where('Rate',1)->first();  
    $pp=ProductUnits::where('Product',$Product[$i])->where('Unit',$Unit[$i])->first();  

        $purchs=ProductsPurchases::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('Store',request('Store'))->get()->sum('Total_Bf_Tax');     
        $countPurchs=ProductsPurchases::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('Store',request('Store'))->get()->sum('SmallQty');
                
    $purchsStart=ProductsStartPeriods::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('Store',request('Store'))->get()->sum('Total');     
                
    $countStart=ProductsStartPeriods::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('Store',request('Store'))->get()->sum('SmallQty');
        $storesTransfer=ProductsStoresTransfers::where('Product',$Product[$i])->where('SmallCode',$P_Code[$i])->where('To_Store',request('Store'))->get()->sum('Total');
                
         $storesTransferCount=ProductsStoresTransfers::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('To_Store',request('Store'))->get()->sum('SmallTrans_Qty');          
              
                
           $OUTCOME=OutcomManufacturingModel::where('Product',$Product[$i])->where('Store',request('Store'))->where('SmallCode',$plow->Barcode)->get()->sum('Cost');     
           
$countOUTCOME=OutcomManufacturingModel::where('Product',$Product[$i])->where('Store',request('Store'))->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');      


     $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME; 
            $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

       if($CollectCount != 0){
    $ty= $Collect /  $CollectCount ; 
                }else{
                    
                   $ty= $Collect;   
                }
   
   if($ty != 0){
                   $in=0;
         $out=$qq * $ty ;     
         $current=$newqty * $ty ;  
                }else{
                  
             $in=0;
         $out=$qq * 1;     
         $current=$newqty * 1;        
                    
                }
                
                                               $cur=$newqty * $ty ;
               ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$newqty,'Price'=>$ty , 'TotalCost'=>$cur]);   
                
            }else{
                
                    $sNam=null;
                    $ssNam=null;
                      $sId=null;
                     $ssId=null; 
                
                   $id_store = DB::table('products_stores')->insertGetId(
            
        array(
            
            'P_Ar_Name' => $P_Ar_Name[$i],
            'P_En_Name' => $P_En_Name[$i],
            'P_Code' =>   $P_Code[$i],
            'Exp_Date' => null,
            'Product' => $Product[$i],
            'Store' =>request('Store'),
            'V1' => $sId,
            'V2' => $ssId,        
            'V_Name' => $sNam,        
            'VV_Name' => $ssNam,        
     
        )
    );          
                

                    $pqty['P_Ar_Name']=$P_Ar_Name[$i];
                 $pqty['Exp_Date']=null;
                    $pqty['P_En_Name']=$P_En_Name[$i];
                    $pqty['Qty']=$Qty[$i] * $pp->Rate;
                    $pqty['Price']=$Price[$i];
                    $pqty['TotalCost']=$Price[$i] * $Qty[$i]; 
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=request('Store');
                    $pqty['Unit']=$Unit[$i];
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$Product[$i];
                  $pqty['Price_Sale']=$Price[$i];
                  $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;    
                    $pqty['P_Code']=$P_Code[$i];  
           $prooooo=Products::find($Product[$i]); 
                        $pqty['SearchCode1']=$prooooo->SearchCode1;
                    $pqty['SearchCode2']=$prooooo->SearchCode2;
  $proooooStore=Stores::find(request('Store'));
   $pqty['Group']=$prooooo->Group;
                    $pqty['Brand']=$prooooo->Brand;
                    $pqty['Branch']=$proooooStore->Branch;
              ProductsQty::create($pqty);  
                
                
            }
           

   
         
            }
          }


                   if(request('Payment_Method') == 'Cash'){
                       
               $res=Journalizing::orderBy('id','desc')->first();
         
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
           }else{
              $Code=1; 
               
           }               
                       
                       
                       
          $JunID = DB::table('journalizings')->insertGetId(
            
        array(
            
            'Code' => $Code,
            'Type' => 'البوليصه',
            'TypeEn' =>'Tickets',
            'Code_Type' => $CodeT,
            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Coin' => request('Coin'),
            'Cost_Center' => null,
            'Total_Debaitor' => request('Total_Price'),
            'Total_Creditor' => request('Total_Price'),
            'Note' => request('Note'),
  
        )
    );

    if(request('Discount') != 0){
        
        
          $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price') + request('Discount');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=48;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
        
        $Gen['Type']= 'البوليصه';
        $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price') + request('Discount');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price') + request('Discount');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=48;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
        
    
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=request('Sender_Name');
        $PRODUCTSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=request('Sender_Name');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);     
        

        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']= request('Discount');
        $PRODUCTSS['Account']=50;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Discount');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Discount');
        $Gen['Account']=50;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);       
        
        
        
        
        
        
          $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=request('Safe');
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=request('Safe');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);      
        
        
           $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=request('Sender_Name');
        $PRODUCTSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=request('Sender_Name');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);     
        
    }else{
        
        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=request('Safe');
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=request('Safe');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
        
        
        
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=request('Sender_Name');
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=request('Sender_Name');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
        
        
        
    }                   
                       
       
              
                       
                   }
               
                  if(request('Payment_Method') == 'Later'){
                       
               $res=Journalizing::orderBy('id','desc')->first();
         
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
           }else{
              $Code=1; 
               
           }               
                       
                       
                       
          $JunID = DB::table('journalizings')->insertGetId(
            
        array(
            
            'Code' => $Code,
                     'Type' => 'البوليصه',             'TypeEn' =>'Tickets',
            'Code_Type' => $CodeT,
            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Coin' => request('Coin'),
            'Cost_Center' => null,
            'Total_Debaitor' => request('Total_Price'),
            'Total_Creditor' => request('Total_Price'),
            'Note' => request('Note'),
  
        )
    );

    if(request('Discount') != 0){
        
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=48;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=48;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price') - request('Discount');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=request('Addressees_Name');
        $PRODUCTSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price') - request('Discount');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price') - request('Discount');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=request('Addressees_Name');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);     
        

        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Discount');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=50;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Discount');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Discount');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=50;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);        
        
    }else{
        
        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=48;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=48;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
        
        
        
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=request('Addressees_Name');
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=request('Addressees_Name');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
        
        
        
    }                   
                       
       
              
                       
                   }
              
        
 
           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
           $dataUser['Screen']='البوليصه';
           $dataUser['ScreenEn']='Tickets';
           $dataUser['Type']='اضافه جديده';
           $dataUser['TypeEn']='New Add';
           $dataUser['Explain']=$CodeT;
           $dataUser['ExplainEn']=$CodeT;
           UsersMoves::create($dataUser);
         
           session()->flash('success',trans('admin.Added_Successfully'));
         if(request('SP') == 0){  return back(); }elseif(request('SP') == 1){  return redirect('TicketPrint/'.$ID); }elseif(request('SP') == 2){return redirect('TicketPrint8/'.$ID);} 
                 
         
     }

      public function TicketsSechdule(){
      $items=Ticket::orderBy('id','desc')->paginate(20);
               if(auth()->guard('admin')->user()->emp == 0){
         
         $Stores=Stores::all();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->store)){
                
                   if(auth()->guard('admin')->user()->pos_stores == 0){
                       
                          $Stores=Stores::where('id',auth()->guard('admin')->user()->store)->get();
                   }else{
                       
                     $Stores=Stores::all();    
                   }    
                
                
            }else{
                
                 $Stores=Stores::all();
            }
         
     }   
     
       if(auth()->guard('admin')->user()->emp == 0){
         
          $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->safe)){
         $Safes=AcccountingManual::where('id',auth()->guard('admin')->user()->safe)->get();
            }else{
                
                  $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
            }
         
     }
          
          
          $Clients = AcccountingManual::
             where('Type',1)
              ->where('Parent',24)
              ->get();
          
         return view('admin.Shipping.TicketsSechdule',[
             'items'=>$items,
             'Stores'=>$Stores,
             'Safes'=>$Safes,
             'Clients'=>$Clients,
         ]);
    }
    
    
          public function FilterTicketsSechdule(){
              
              
      $items=Ticket::orderBy('id','desc')->paginate(20);
              
$from=request('From');
$to=request('To');
$sender=request('Sender_Name');
$addresses=request('Addressees_Name');
$store=request('Store');
$safe=request('Safe');
$pay=request('Payment_Method');
$code=request('Code');
              
              $items =Ticket::whereBetween('Date', [$from, $to])  
                        
          ->when(!empty($code), function ($query) use ($code) {
        return $query->where('Code',$code);  
               
                })  
            
                     ->when(!empty($pay), function ($query) use ($pay) {
        return $query->where('Payment_Method',$pay);  
               
                })  
                  
                 ->when(!empty($sender), function ($query) use ($sender) {
        return $query->where('Sender_Name',$sender);  
               
                })  
                  
                     ->when(!empty($addresses), function ($query) use ($addresses) {
        return $query->where('Addressees_Name',$addresses);  
               
                })  
                  
                 ->when(!empty($store), function ($query) use ($store) {
        return $query->where('Store',$store);  
               
                })        
               
                     ->when(!empty($safe), function ($query) use ($safe) {
        return $query->where('Safe',$safe);  
               
                })    
        

          ->paginate(100);  
              
              
              
              
              
               if(auth()->guard('admin')->user()->emp == 0){
         
         $Stores=Stores::all();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->store)){
                
                   if(auth()->guard('admin')->user()->pos_stores == 0){
                       
                          $Stores=Stores::where('id',auth()->guard('admin')->user()->store)->get();
                   }else{
                       
                     $Stores=Stores::all();    
                   }    
                
                
            }else{
                
                 $Stores=Stores::all();
            }
         
     }   
     
       if(auth()->guard('admin')->user()->emp == 0){
         
          $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->safe)){
         $Safes=AcccountingManual::where('id',auth()->guard('admin')->user()->safe)->get();
            }else{
                
                  $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
            }
         
     }
          
          
          $Clients = AcccountingManual::
             where('Type',1)
              ->where('Parent',24)
              ->get();
          
         return view('admin.Shipping.TicketsSechdule',[
             'items'=>$items,
             'Stores'=>$Stores,
             'Safes'=>$Safes,
             'Clients'=>$Clients,
         ]);
    }
    
    

    //TicketPrint
         public function TicketPrint($id){
      $item=Ticket::find($id);
        $Prods=TicketProducts::where('Ticket',$item->id)->get();
         return view('admin.Shipping.TicketPrint',[
             'item'=>$item,
             'Prods'=>$Prods,
         ]);
    }
    
          public function TicketPrint5($id){
      $item=Ticket::find($id);
        $Prods=TicketProducts::where('Ticket',$item->id)->get();
         return view('admin.Shipping.TicketPrint5',[
             'item'=>$item,
             'Prods'=>$Prods,
         ]);
    }
    
          public function TicketPrint8($id){
      $item=Ticket::find($id);
        $Prods=TicketProducts::where('Ticket',$item->id)->get();
         return view('admin.Shipping.TicketPrint8',[
             'item'=>$item,
             'Prods'=>$Prods,
         ]);
    }
    
    
    

    
    //TicketEdit
             public function TicketEdit($id){
         if(auth()->guard('admin')->user()->emp == 0){
         
         $Stores=Stores::all();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->store)){
                
                   if(auth()->guard('admin')->user()->pos_stores == 0){
                       
                          $Stores=Stores::where('id',auth()->guard('admin')->user()->store)->get();
                   }else{
                       
                     $Stores=Stores::all();    
                   }    
                
                
            }else{
                
                 $Stores=Stores::all();
            }
         
     }   
     
       if(auth()->guard('admin')->user()->emp == 0){
         
          $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->safe)){
         $Safes=AcccountingManual::where('id',auth()->guard('admin')->user()->safe)->get();
            }else{
                
                  $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
            }
         
     }
          
          
          $Clients = AcccountingManual::
             where('Type',1)
              ->where('Parent',24)
              ->get();
          
         
                $Coins=Coins::all();
                      $item=Ticket::find($id);
        $Prods=TicketProducts::where('Ticket',$item->id)->get();
                $Governrate=Governrate::all();
                 
                 
                          if($item->Selected != 0){  
   session()->flash('error',trans('admin.Already_Done'));
               return redirect('TicketsSechdule');
        
                    }
                 
         return view('admin.Shipping.TicketEdit',[
             'Stores'=>$Stores,
             'Safes'=>$Safes,
             'Clients'=>$Clients,
             'Coins'=>$Coins,
             'item'=>$item,
             'Prods'=>$Prods,
             'Governrate'=>$Governrate,
  
         ]);
    }
    
         public function PostEditTicket(){
         
            $data= $this->validate(request(),[
             'Code'=>'required',
             'Date'=>'required',
             'Sender_Name'=>'required',
             'Addressees_Name'=>'required',
             'Total'=>'required',
             'Store'=>'required',
             'Safe'=>'required',
             'Coin'=>'required',
             'Access_Area'=>'required',

               ],[
            

         ]);
         

           $ID = request('ID');
    
            
            $data['Code'] = request('Code');
            $data['Date'] = request('Date');
            $data['Payment_Method'] = request('Payment_Method');
            $data['Sender_Name'] = request('Sender_Name');
            $data['Sender_Address'] = request('Sender_Address');
            $data['Sender_Phone'] = request('Sender_Phone');
            $data['Addressees_Name'] = request('Addressees_Name');
            $data['Addressees_Address'] = request('Addressees_Address');
            $data['Addressees_Phone'] = request('Addressees_Phone');
            $data['Notes'] = request('Note');
            $data['Sub_Total'] = request('Sub_Total');
            $data['Discount'] = request('Discount');
            $data['Total'] = request('Total_Price');
            $data['Store'] = request('Store');
            $data['Safe'] = request('Safe');
            $data['Recived'] =0;
            $data['Selected'] =0;
            $data['Coin'] = request('Coin');
            $data['Draw'] = request('Draw');
            $data['Access_Area'] = request('Access_Area');
            $data['Product_Numbers'] = request('Product_Numbers');
            $data['Total_Qty'] = request('Total_Qty');
             Ticket::where('id',$ID)->update($data);
         
        if(!empty(request('Unit'))){
            
             $del=Ticket::find($ID);
        
       GeneralDaily::where('Code_Type',$del->Code)->where('Type','البوليصه')->delete();
       Journalizing::where('Code_Type',$del->Code)->where('Type','البوليصه')->delete();
     
        
    $Products=TicketProducts::where('Ticket',$del->id)->get();        
      foreach($Products as $prod){
          
        $unit=ProductUnits::where('Unit',$prod->Unit)->where('Product',$prod->Product)->first();  
               
              $qq= $unit->Rate * $prod->Qty ;  
          
        $PR=ProductsQty::where('Product',$prod->Product)
             ->where('P_Code',$prod->Product_Code) 
             ->where('Store',$prod->Store) 
             ->first(); 
          
          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PP_Code',$prod->Product_Code) 
             ->where('Store',$prod->Store) 
             ->first(); 
              
                    if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPP_Code',$prod->Product_Code) 
             ->where('Store',$prod->Store) 
             ->first(); 
                        
                          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPPP_Code',$prod->Product_Code) 
             ->where('Store',$prod->Store) 
             ->first(); 
              
              
          }    
                        
              
              
          }
              
              
          }
          
          
          
             
        $newqty=$PR->Qty - $qq ; 
        
          ProductsQty::where('id',$PR->id)->update(['Qty'=>$newqty]);
          
      }

            TicketProducts::where('Ticket',$ID)->delete();
                   StoreCountSales::truncate();   
              $Price=request('Price');
              $P_Ar_Name=request('P_Ar_Name');
              $P_En_Name=request('P_En_Name');
              $Unit=request('Unit');
              $P_Code=request('P_Code');
              $Weight=request('Weight');
              $Length=request('Length');
              $Width=request('Width');
              $Height=request('Height');
              $Qty=request('Qty');
              $Total=request('Total');
              $Product=request('Product');
       

            for($i=0 ; $i < count($Unit) ; $i++){

            $pp=ProductUnits::where('Product',$Product[$i])->where('Unit',$Unit[$i])->first();    
            $plow=ProductUnits::where('Product',$Product[$i])->where('Rate',1)->first();   
                
                $uu['Product_Code']=$P_Code[$i];
                $uu['P_Ar_Name']=$P_Ar_Name[$i];
                $uu['P_En_Name']=$P_En_Name[$i];
                $uu['Price']=$Price[$i];
                $uu['Weight']=$Weight[$i];
                $uu['Length']=$Length[$i];
                $uu['Width']=$Width[$i];
                $uu['Height']=$Height[$i];
                $uu['Qty']=$Qty[$i];
                $uu['Unit']=$Unit[$i];
                $uu['Total']=$Total[$i];
                $uu['Store']=request('Store');
                $uu['Product']=$Product[$i];
                $uu['Ticket']=$ID;
                
               TicketProducts::create($uu); 
                
    $prooooo=Products::find($Product[$i]); 

                 $Quantity =ProductsQty::
                where('Store',request('Store'))    
                ->where('Product',$Product[$i])    
                ->where('P_Code',$P_Code[$i])    
                ->first(); 

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('Store'))    
                ->where('Product',$Product[$i])    
                ->where('PP_Code',$P_Code[$i])    
                ->first(); 

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('Store'))    
                ->where('Product',$Product[$i])    
                ->where('PPP_Code',$P_Code[$i])    
                ->first(); 


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',request('Store'))    
                ->where('Product',$Product[$i])    
                ->where('PPPP_Code',$P_Code[$i])    
                ->first(); 

}



}






}

                
            if(!empty($Quantity)){    
           $unit=ProductUnits::where('Unit',$Unit[$i])->where('Product',$Product[$i])->first();  
                
           $qq= $unit->Rate * $Qty[$i] ;
                
           $newqty=$Quantity->Qty +  $qq ; 
                
       
                  $prooooo=Products::find($Product[$i]); 

   $plow=ProductUnits::where('Product',$Product[$i])->where('Rate',1)->first();  
    $pp=ProductUnits::where('Product',$Product[$i])->where('Unit',$Unit[$i])->first();  

        $purchs=ProductsPurchases::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('Store',request('Store'))->get()->sum('Total_Bf_Tax');     
        $countPurchs=ProductsPurchases::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('Store',request('Store'))->get()->sum('SmallQty');
                
    $purchsStart=ProductsStartPeriods::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('Store',request('Store'))->get()->sum('Total');     
                
    $countStart=ProductsStartPeriods::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('Store',request('Store'))->get()->sum('SmallQty');
        $storesTransfer=ProductsStoresTransfers::where('Product',$Product[$i])->where('SmallCode',$P_Code[$i])->where('To_Store',request('Store'))->get()->sum('Total');
                
         $storesTransferCount=ProductsStoresTransfers::where('Product',$Product[$i])->where('SmallCode',$plow->Barcode)->where('To_Store',request('Store'))->get()->sum('SmallTrans_Qty');          
              
                
           $OUTCOME=OutcomManufacturingModel::where('Product',$Product[$i])->where('Store',request('Store'))->where('SmallCode',$plow->Barcode)->get()->sum('Cost');     
           
$countOUTCOME=OutcomManufacturingModel::where('Product',$Product[$i])->where('Store',request('Store'))->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');      


     $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME; 
            $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

       if($CollectCount != 0){
    $ty= $Collect /  $CollectCount ; 
                }else{
                    
                   $ty= $Collect;   
                }
   
   if($ty != 0){
                   $in=0;
         $out=$qq * $ty ;     
         $current=$newqty * $ty ;  
                }else{
                  
             $in=0;
         $out=$qq * 1;     
         $current=$newqty * 1;        
                    
                }
                
                                               $cur=$newqty * $ty ;
               ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$newqty,'Price'=>$ty , 'TotalCost'=>$cur]);   
                
            }else{
                
                    $sNam=null;
                    $ssNam=null;
                      $sId=null;
                     $ssId=null; 
                
                   $id_store = DB::table('products_stores')->insertGetId(
            
        array(
            
            'P_Ar_Name' => $P_Ar_Name[$i],
            'P_En_Name' => $P_En_Name[$i],
            'P_Code' =>   $P_Code[$i],
            'Exp_Date' => null,
            'Product' => $Product[$i],
            'Store' =>request('Store'),
            'V1' => $sId,
            'V2' => $ssId,        
            'V_Name' => $sNam,        
            'VV_Name' => $ssNam,        
     
        )
    );          
                

                    $pqty['P_Ar_Name']=$P_Ar_Name[$i];
                 $pqty['Exp_Date']=null;
                    $pqty['P_En_Name']=$P_En_Name[$i];
                    $pqty['Qty']=$Qty[$i] * $pp->Rate;
                    $pqty['Price']=$Price[$i];
                    $pqty['TotalCost']=$Price[$i] * $Qty[$i]; 
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=request('Store');
                    $pqty['Unit']=$Unit[$i];
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$Product[$i];
                  $pqty['Price_Sale']=$Price[$i];
                  $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;    
                    $pqty['P_Code']=$P_Code[$i];  
           $prooooo=Products::find($Product[$i]); 
                        $pqty['SearchCode1']=$prooooo->SearchCode1;
                    $pqty['SearchCode2']=$prooooo->SearchCode2;
  $proooooStore=Stores::find(request('Store'));
   $pqty['Group']=$prooooo->Group;
                    $pqty['Brand']=$prooooo->Brand;
                    $pqty['Branch']=$proooooStore->Branch;
              ProductsQty::create($pqty);  
                
                
            }
           

   
         
            }
          }


                   if(request('Payment_Method') == 'Cash'){
                       
               $res=Journalizing::orderBy('id','desc')->first();
         
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
           }else{
              $Code=1; 
               
           }               
                       
                       
                       
          $JunID = DB::table('journalizings')->insertGetId(
            
        array(
            
            'Code' => $Code,
                     'Type' => 'البوليصه',             'TypeEn' =>'Tickets',
            'Code_Type' => request('Code'),
            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Coin' => request('Coin'),
            'Cost_Center' => null,
            'Total_Debaitor' => request('Total_Price'),
            'Total_Creditor' => request('Total_Price'),
            'Note' => request('Note'),
  
        )
    );

    if(request('Discount') != 0){
        
        
          $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price') + request('Discount');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=48;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price') + request('Discount');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price') + request('Discount');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=48;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
        
    
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=request('Sender_Name');
        $PRODUCTSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=request('Sender_Name');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);     
        

        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']= request('Discount');
        $PRODUCTSS['Account']=50;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Discount');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Discount');
        $Gen['Account']=50;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);       
        
        
        
        
        
        
          $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=request('Safe');
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=request('Safe');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);      
        
        
           $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=request('Sender_Name');
        $PRODUCTSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=request('Sender_Name');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);     
        
    }else{
        
        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=request('Safe');
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=request('Safe');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
        
        
        
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=request('Sender_Name');
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=request('Sender_Name');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
        
        
        
    }                   
                       
       
              
                       
                   }
               
                  if(request('Payment_Method') == 'Later'){
                       
               $res=Journalizing::orderBy('id','desc')->first();
         
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
           }else{
              $Code=1; 
               
           }               
                       
                       
                       
          $JunID = DB::table('journalizings')->insertGetId(
            
        array(
            
            'Code' => $Code,
                     'Type' => 'البوليصه',             'TypeEn' =>'Tickets',
            'Code_Type' => request('Code'),
            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Coin' => request('Coin'),
            'Cost_Center' => null,
            'Total_Debaitor' => request('Total_Price'),
            'Total_Creditor' => request('Total_Price'),
            'Note' => request('Note'),
  
        )
    );

    if(request('Discount') != 0){
        
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=48;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=48;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price') - request('Discount');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=request('Addressees_Name');
        $PRODUCTSS['Statement']=null;
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price') - request('Discount');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price') - request('Discount');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=request('Addressees_Name');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);     
        

        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Discount');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=50;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Discount');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Discount');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=50;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);        
        
    }else{
        
        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=48;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=48;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
        
        
        
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=request('Addressees_Name');
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=request('Code');
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=request('Addressees_Name');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
        
        
        
    }                   
                       
       
              
                       
                   }
              
        
 
           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
             $dataUser['Screen']='البوليصه';
           $dataUser['ScreenEn']='Tickets';
           $dataUser['Type']='تعديل';
           $dataUser['TypeEn']='Edit';
           $dataUser['Explain']=request('Code');
           $dataUser['ExplainEn']=request('Code');
           UsersMoves::create($dataUser);
         
           session()->flash('success',trans('admin.Updated'));
        return redirect('TicketsSechdule');    
         
     }
    
    
    
    //DeleteTicket
        public function DeleteTicket($id){
                      
        $del=Ticket::find($id);
        
       GeneralDaily::where('Code_Type',$del->Code)->where('Type','البوليصه')->delete();
       Journalizing::where('Code_Type',$del->Code)->where('Type','البوليصه')->delete();
     
        
    $Products=TicketProducts::where('Ticket',$del->id)->get();        
      foreach($Products as $prod){
          
        $unit=ProductUnits::where('Unit',$prod->Unit)->where('Product',$prod->Product)->first();  
               
              $qq= $unit->Rate * $prod->Qty ;  
          
        $PR=ProductsQty::where('Product',$prod->Product)
             ->where('P_Code',$prod->Product_Code) 
             ->where('Store',$prod->Store) 
             ->first(); 
          
          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PP_Code',$prod->Product_Code) 
             ->where('Store',$prod->Store) 
             ->first(); 
              
                    if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPP_Code',$prod->Product_Code) 
             ->where('Store',$prod->Store) 
             ->first(); 
                        
                          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPPP_Code',$prod->Product_Code) 
             ->where('Store',$prod->Store) 
             ->first(); 
              
              
          }    
                        
              
              
          }
              
              
          }
          
          
          
             
        $newqty=$PR->Qty - $qq ; 
        
          ProductsQty::where('id',$PR->id)->update(['Qty'=>$newqty]);
          
      }

           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
           $dataUser['Screen']='البوليصه';
           $dataUser['ScreenEn']='Tickets';
           $dataUser['Type']='حذف';
           $dataUser['TypeEn']='Delete';
           $dataUser['Explain']=$del->Code;
           $dataUser['ExplainEn']=$del->Code;
           UsersMoves::create($dataUser);
          TicketProducts::where('Ticket',$id)->delete();
        $del->delete();
        session()->flash('error',trans('admin.Deleted'));
        return back();

           }   
        
    //=============================================================
    
    //  =============== ShippingList  ====================
    
          public function ShippingList(){
         if(auth()->guard('admin')->user()->emp == 0){
         
         $Stores=Stores::all();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->store)){
                
                   if(auth()->guard('admin')->user()->pos_stores == 0){
                       
                          $Stores=Stores::where('id',auth()->guard('admin')->user()->store)->get();
                   }else{
                       
                     $Stores=Stores::all();    
                   }    
                
                
            }else{
                
                 $Stores=Stores::all();
            }
         
     }   
   
                
      $res=ShippingList::orderBy('id','desc')->first();
           
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
               
           }else{
               
              $Code=1; 
               
           }
                      
                $Governrate=Governrate::all();
               
                    $Employess = Employess::
             where('Emp_Type','Driver')
                 ->where("EmpSort",1)->where('Active',1)
              ->get();
       $CarStores=Stores::all();
         return view('admin.Shipping.ShippingList',[
             'Stores'=>$Stores,
             'Code'=>$Code,
             'Governrate'=>$Governrate,
             'Employess'=>$Employess,
             'CarStores'=>$CarStores,
           
         ]);
    }
    
          function ShippingListFilter(Request $request)
             {  
     if($request->ajax())
     { 
      $output = '';
      $store = $request->get('store');             
      $area = $request->get('Access_Area');             
      
    if($store != '' and $area != '')
    {

     $data =Ticket::    
              where('Store',$store)                  
              ->where('Access_Area',$area)                  
              ->where('Selected',0)                  
          ->get();         
                           
     }

         $total_row = $data->count();
      if($total_row > 0) 
      { 

         foreach($data as $rows){  
    $Prods=TicketProducts::where('Ticket',$rows->id)->get();
             if($rows->Payment_Method == 'Cash' or $rows->Payment_Method == 'كاش'){
                 $Pay=trans('admin.Cash');
                 $PayOption='<input type="hidden"  id="PayOption'.$rows->id.'" value="'.$rows->Total.'">';  
                 
             }else{
                    $Pay=trans('admin.Later');  
                 $PayOption='<input type="hidden"  id="PayOption'.$rows->id.'" value="'.$rows->Total.'">';  
             }
                 
           
                    if(app()->getLocale() == 'ar' ){ 
                       $SenderNamme=$rows->Sender_Name()->first()->Name;
                       $AddrssesNamme=$rows->Addressees_Name()->first()->Name;
                   }else{
                        $SenderNamme=$rows->Sender_Name()->first()->NameEn;
                       $AddrssesNamme=$rows->Addressees_Name()->first()->NameEn;  
              
                   }
             
             
        $output .= '
        
       <tr id="Row'.$rows->id.'">
        <td>'.$rows->Code.'
    <input type="hidden" id="Code'.$rows->id.'" value="'.$rows->Code.'">    
    <input type="hidden" id="Ticket'.$rows->id.'" value="'.$rows->id.'">    
        </td>
        <td>'.$SenderNamme.'
         <input type="hidden" id="Sender_Name'.$rows->id.'" value="'.$SenderNamme.'">   
        </td>
        <td>'.$AddrssesNamme.'
         <input type="hidden" id="Addressees_Name'.$rows->id.'" value="'.$AddrssesNamme.'">   
        </td>
        <td>'.$rows->Total_Qty.'
         <input type="hidden"  id="Total_Qty'.$rows->id.'" value="'.$rows->Total_Qty.'">   
        </td>
        <td>'.$rows->Total.'
     <input type="hidden"  id="Total'.$rows->id.'" value="'.$rows->Total.'">       
        </td>
        <td>'.$Pay.' '.$PayOption.'
     <input type="hidden" id="Pay'.$rows->id.'" value="'.$Pay.'">       
        </td>
        
        
         <td>
           <button type="button" class="btn btn-default" data-toggle="modal" data-target="#Details'.$rows->id.'">'.trans('admin.Details').'</button>   
            
        </td>
        
        
        <td>'.$rows->Notes.'
     <input type="hidden" id="Notes'.$rows->id.'" value="'.$rows->Notes.'">       
        </td>
        <td>
 <button type="button" class="btn btn-default waves-effect waves-themed" id="AddBtnPur'.$rows->id.'" onclick="Fun('.$rows->id.')">
          <i class="fal fa-plus"></i>
          </button>
        </td>
        
        <td>
    <div class="modal fade" id="Details'.$rows->id.'" tabindex="-1" role="dialog" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h4 class="modal-title">
                                          '.trans('admin.Details').' 
                                    </h4>
                                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        <span aria-hidden="true"><i class="fal fa-times"></i></span>
                                    </button>
                                </div>
                                
                                <div class="modal-body"> 
                       
                                     <div id="mobile-overflow">
                                        <table 
                                            class="table">
                                        
                                                <tr>
                                                    <th>'.trans('admin.Code').'</th>
                                                    <th>'.trans('admin.Name').'</th>
                                                    <th>'.trans('admin.Price').'</th>
                                                    <th>'.trans('admin.Weight').'</th>
                                                    <th>'.trans('admin.Length').'</th>
                                                    <th>'.trans('admin.Width').'</th>
                                                    <th>'.trans('admin.Height').'</th>
                                                    <th>'.trans('admin.Qty').'</th>
                                                    <th>'.trans('admin.Unit').'</th>
                                                    <th>'.trans('admin.Total').'</th>
                  
                                                </tr>
                                        
                                      
                                                ';
             
                              foreach($Prods as $pro){
                                         if(app()->getLocale() == 'ar' ){ 
                       $Namme=$pro->P_Ar_Name;
                       $UnitNamme=$pro->Unit()->first()->Name;
                   }else{
                       
                       $Namme=$pro->P_En_Name; 
                       $UnitNamme=$pro->Unit()->first()->NameEn; 
                   }
                                            $output .= '      <tr>
                                                    <td>'.$pro->Product_Code.'</td>
                                                    <td>'.$Namme.'</td>
                                                    <td>'.$pro->Price.'</td>
                                                    <td>'.$pro->Weight.'</td>
                                                    <td>'.$pro->Length.'</td>
                                                    <td>'.$pro->Width.'</td>
                                                    <td>'.$pro->Height.'</td>
                                                    <td>'.$pro->Qty.'</td>
                                                    <td>'.$UnitNamme.'</td>
                                                    <td>'.$pro->Total.'</td>
                                                  
                                                </tr>
                                                ';
                              }           
                                   
               $output .= '
                                    
                                          
                                        </table>
                                        </div>
                                    
                                     <div id="mobile-overflow">
                                        <table 
                                            class="table table-bordered ">
                                           
                                                <tr>
                                                     <th>'.trans('admin.Sub_Total').'</th>
                                                    <th>'.trans('admin.Discount').'</th>
                                                    <th>'.trans('admin.Total').'</th>
                                                    <th>'.trans('admin.Product_Numbers').'</th>
                                                    <th>'.trans('admin.Total_Qty').'</th>
                                                </tr>
                                         
                                      
                                                
                              
                                                <tr>
                                                    <td>'.$rows->Sub_Total.'</td>
                                                    <td>'.$rows->Discount.'</td>
                                                    <td>'.$rows->Total.'</td>
                                                    <td>'.$rows->Product_Numbers.'</td>
                                                    <td>'.$rows->Total_Qty.'</td>
                                                   
                                                </tr>
                                   
                                   
                                          
                                        </table>
                                        </div>
   
                                
                                </div>
                                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-dismiss="modal"> '.trans('admin.Close').'</button>
                                </div>
                            </div>
                        </div>
                    </div>
      </td>  
        </tr>
        
        

            
            ';
   
        
        
             
             

        }      

      }else
      {
       $output = '
        <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
       ';
      }
      $data = array(
       'table_data'  => $output,
      );
      echo json_encode($data);
     }
    }
    
           public function AddShippingList(){
         
            $data= $this->validate(request(),[
             'Code'=>'required',
             'Date'=>'required',
             'Ticket_Store'=>'required',
             'Car_Store'=>'required',
             'Driver'=>'required',
             'Travel_Area'=>'required',
             'Access_Area'=>'required',
               ],[
            

         ]);
         

           $ID = DB::table('shipping_lists')->insertGetId(
        array(
            
            'Ticket_Store' => request('Ticket_Store'),
            'Driver' => request('Driver'),
            'Car_Store' => request('Car_Store'),
            'Travel_Area' => request('Travel_Area'),
            'Access_Area' => request('Access_Area'),
            'Date_Travel' => request('Date_Travel'),
            'Date_Arrival' => request('Date_Arrival'),
            'Car_Number' => request('Car_Number'),
            'Code' => request('Code'),
            'Date' => request('Date'),
            'Status' => 0,
            'Total_Cash' => request('Total_Cash'),
            'Total_Later' => request('Total_Later'),
            'Total_Price' => request('Total_Price'),
            'Tickets_Numbers' => request('Tickets_Numbers'),
        )
    );  

         
        if(!empty(request('Codee'))){
            
                  
              $Code=request('Codee');
              $Sender_Name=request('Sender_Name');
              $Addressees_Name=request('Addressees_Name');
              $Total_Qty=request('Total_Qty');
              $Total=request('Total');
              $Pay=request('Pay');
              $Notes=request('Notes');
              $Ticket=request('Ticket');
  
          
            for($i=0 ; $i < count($Code) ; $i++){
                
                $uu['Shipping_List']=$ID;
                $uu['Code']=$Code[$i];
                $uu['Sender_Name']=$Sender_Name[$i];
                $uu['Addressees_Name']=$Addressees_Name[$i];
                $uu['Total_Qty']=$Total_Qty[$i];
                $uu['Total_Price']=$Total[$i];
                $uu['Payment_Method']=$Pay[$i];
                $uu['Notes']=$Notes[$i];
                $uu['Ticket']=$Ticket[$i];

               ShippingListTickets::create($uu); 
       
                
       Ticket::where('id',$Ticket[$i])->update(['Selected'=>1]);  
                
            $prods=TicketProducts::where('Ticket',$Ticket[$i])->get();    
              
                
            foreach($prods as $pro){
               $pp=ProductUnits::where('Product',$pro->Product)->where('Unit',$pro->Unit)->first();    
            $plow=ProductUnits::where('Product',$pro->Product)->where('Rate',1)->first();       
                  $prooooo=Products::find($pro->Product);
                
                
    //From            
                      $Quantity =ProductsQty::
                where('Store',$pro->Store)    
                ->where('Product',$pro->Product)    
                ->where('P_Code',$pro->Product_Code)    
                ->first(); 
    


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$pro->Store)    
                ->where('Product',$pro->Product)    
                ->where('PP_Code',$pro->Product_Code)    
                ->first(); 

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$pro->Store)    
                ->where('Product',$pro->Product)    
                ->where('PPP_Code',$pro->Product_Code)    
                ->first(); 


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$pro->Store)    
                ->where('Product',$pro->Product)    
                ->where('PPPP_Code',$pro->Product_Code)    
                ->first(); 

}



}



}

               
            if(!empty($Quantity)){    
           $unit=ProductUnits::where('Unit',$pro->Unit)->where('Product',$pro->Product)->first();  
                
           $qq= $unit->Rate * $pro->Qty ;
                
           $newqty=$Quantity->Qty -  $qq ; 
                
         
               ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$newqty]);   
                
            }
                  
     //To           
         
                            $QuantityTo =ProductsQty::
                where('Store',request('Car_Store'))    
                ->where('Product',$pro->Product)    
                ->where('P_Code',$pro->Product_Code)    
                ->first(); 
    
if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Car_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PP_Code',$pro->Product_Code)    
                ->first(); 

if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Car_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PPP_Code',$pro->Product_Code)    
                ->first(); 


if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Car_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PPPP_Code',$pro->Product_Code)    
                ->first(); 

}



}






}
        
                
           
                    
            if(!empty($QuantityTo)){    
           $unit=ProductUnits::where('Unit',$pro->Unit)->where('Product',$pro->Product)->first();  
                
           $qq= $unit->Rate * $pro->Qty ;
                
           $newqty=$QuantityTo->Qty +  $qq ; 
                
       
                  $prooooo=Products::find($pro->Product); 

   $plow=ProductUnits::where('Product',$pro->Product)->where('Rate',1)->first();  
    $pp=ProductUnits::where('Product',$pro->Product)->where('Unit',$pro->Unit)->first();  

        $purchs=ProductsPurchases::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',request('Car_Store'))->get()->sum('Total_Bf_Tax');     
        $countPurchs=ProductsPurchases::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',request('Car_Store'))->get()->sum('SmallQty');
                
    $purchsStart=ProductsStartPeriods::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',request('Car_Store'))->get()->sum('Total');     
                
    $countStart=ProductsStartPeriods::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',request('Car_Store'))->get()->sum('SmallQty');
        $storesTransfer=ProductsStoresTransfers::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('To_Store',request('Car_Store'))->get()->sum('Total');
                
         $storesTransferCount=ProductsStoresTransfers::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('To_Store',request('Car_Store'))->get()->sum('SmallTrans_Qty');          
              
                
           $OUTCOME=OutcomManufacturingModel::where('Product',$pro->Product)->where('Store',request('Car_Store'))->where('SmallCode',$plow->Barcode)->get()->sum('Cost');     
           
$countOUTCOME=OutcomManufacturingModel::where('Product',$pro->Product)->where('Store',request('Car_Store'))->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');      


     $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME; 
            $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

       if($CollectCount != 0){
    $ty= $Collect /  $CollectCount ; 
                }else{
                    
                   $ty= $Collect;   
                }
   
   if($ty != 0){
                   $in=0;
         $out=$qq * $ty ;     
         $current=$newqty * $ty ;  
                }else{
                  
             $in=0;
         $out=$qq * 1;     
         $current=$newqty * 1;        
                    
                }
                
                                               $cur=$newqty * $ty ;
               ProductsQty::where('id',$QuantityTo->id)->update(['Qty'=>$newqty,'Price'=>$ty , 'TotalCost'=>$cur]);   
                
            }else{
                
                    $sNam=null;
                    $ssNam=null;
                      $sId=null;
                     $ssId=null; 
                
                   $id_store = DB::table('products_stores')->insertGetId(
            
        array(
            
            'P_Ar_Name' =>$pro->P_Ar_Name,
            'P_En_Name' => $pro->P_En_Name,
            'P_Code' =>   $pro->Product_Code,
            'Exp_Date' => null,
            'Product' => $pro->Product,
            'Store' =>request('Car_Store'),
            'V1' => $sId,
            'V2' => $ssId,        
            'V_Name' => $sNam,        
            'VV_Name' => $ssNam,        
     
        )
    );          
                

                    $pqty['P_Ar_Name']=$pro->P_Ar_Name;
                 $pqty['Exp_Date']=null;
                    $pqty['P_En_Name']=$pro->P_En_Name;
                    $pqty['Qty']=$pro->Qty * $pp->Rate;
                    $pqty['Price']=$pro->Price;
                    $pqty['TotalCost']=$pro->Price * $pro->Qty; 
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=request('Car_Store');
                    $pqty['Unit']=$pro->Unit;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$pro->Product;
                  $pqty['Price_Sale']=$pro->Price;
                  $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;    
                    $pqty['P_Code']=$pro->Product_Code;  
           $prooooo=Products::find($pro->Product); 
                        $pqty['SearchCode1']=$prooooo->SearchCode1;
                    $pqty['SearchCode2']=$prooooo->SearchCode2;
  $proooooStore=Stores::find(request('Car_Store'));
   $pqty['Group']=$prooooo->Group;
                    $pqty['Brand']=$prooooo->Brand;
                    $pqty['Branch']=$proooooStore->Branch;
              ProductsQty::create($pqty);  
                
                
            }
             
                
                
                
                
                
           
 } 
   
         
            }
          }


           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
           $dataUser['Screen']='قائمه الشحن';
           $dataUser['ScreenEn']='Shipping List';
           $dataUser['Type']='اضافه جديده';
           $dataUser['TypeEn']='New Add';
           $dataUser['Explain']=request('Code');
           $dataUser['ExplainEn']=request('Code');
           UsersMoves::create($dataUser);
         
           session()->flash('success',trans('admin.Added_Successfully'));
         if(request('SP') == 0){  return back(); }elseif(request('SP') == 1){  return redirect('ShippingListPrint/'.$ID); } 
                 
         
     }
    
     public function ShippingListSechdule(){
      $items=ShippingList::orderBy('id','desc')->paginate(20);
        
         return view('admin.Shipping.ShippingListSechdule',[
             'items'=>$items,
         ]);
    }
    
    //ShippingListPrint
         public function ShippingListPrint($id){
      $item=ShippingList::find($id);
        $Prods=ShippingListTickets::where('Shipping_List',$item->id)->get(); 
         return view('admin.Shipping.ShippingListPrint',[
             'item'=>$item,
             'Prods'=>$Prods,
         ]);
    }
    
    
    //ShippingListEdit
     public function ShippingListEdit($id){
      $item=ShippingList::find($id);
        $Prods=ShippingListTickets::where('Shipping_List',$item->id)->get(); 
                 if(auth()->guard('admin')->user()->emp == 0){
         
         $Stores=Stores::all();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->store)){
                
                   if(auth()->guard('admin')->user()->pos_stores == 0){
                       
                          $Stores=Stores::where('id',auth()->guard('admin')->user()->store)->get();
                   }else{
                       
                     $Stores=Stores::all();    
                   }    
                
                
            }else{
                
                 $Stores=Stores::all();
            }
         
     }   
   
     $Governrate=Governrate::all();
               
                    $Employess = Employess::
             where('Emp_Type','Driver')
                 ->where("EmpSort",1)->where('Active',1)
              ->get();
           $CarStores=Stores::all();

         
                                   if($item->Status != 0){  
   session()->flash('error',trans('admin.Already_Done'));
               return redirect('ShippingListSechdule');
        
                    }
         return view('admin.Shipping.ShippingListEdit',[
             'item'=>$item,
             'Prods'=>$Prods,
             'Stores'=>$Stores,
             'Governrate'=>$Governrate,
             'Employess'=>$Employess,
             'CarStores'=>$CarStores,
         ]);
    }
    //PostEditShippingList
               public function PostEditShippingList(){
         
            $data= $this->validate(request(),[
             'Code'=>'required',
             'Date'=>'required',
             'Ticket_Store'=>'required',
             'Car_Store'=>'required',
             'Driver'=>'required',
             'Travel_Area'=>'required',
             'Access_Area'=>'required',
               ],[
            

         ]);
         
$ID=request('ID');
  
                   
    $data['Ticket_Store'] = request('Ticket_Store');
    $data['Driver'] = request('Driver');
    $data['Car_Store'] = request('Car_Store');
    $data['Travel_Area'] = request('Travel_Area');
    $data['Access_Area'] = request('Access_Area');
    $data['Date_Travel'] = request('Date_Travel');
    $data['Date_Arrival'] = request('Date_Arrival');
    $data['Car_Number'] = request('Car_Number');
    $data['Code'] = request('Code');
    $data['Date'] = request('Date');
    $data['Status'] = 0;
    $data['Total_Cash'] = request('Total_Cash');
    $data['Total_Later'] = request('Total_Later');
    $data['Total_Price'] = request('Total_Price');
    $data['Tickets_Numbers'] = request('Tickets_Numbers');
                   
    ShippingList::where('id',$ID)->update($data);
         
        if(!empty(request('Codee'))){
            
            $id=$ID;
                $del=ShippingList::find($id);
  
   
    $Pros=ShippingListTickets::where('Shipping_List',$del->id)->get();  
             if(!empty($Pros)){
        foreach($Pros as $pro){     
            
            Ticket::where('id',$pro->Ticket)->update(['Selected'=>0]);  
                
            $Products=TicketProducts::where('Ticket',$pro->Ticket)->get();    
               
 
      foreach($Products as $prod){
          
        $unit=ProductUnits::where('Unit',$prod->Unit)->where('Product',$prod->Product)->first();  
               
              $qq= $unit->Rate * $prod->Qty ;  
          
        $PR=ProductsQty::where('Product',$prod->Product)
             ->where('P_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Ticket_Store) 
             ->first(); 
          
          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Ticket_Store) 
             ->first(); 
              
                    if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Ticket_Store) 
             ->first(); 
                        
                          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPPP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Ticket_Store) 
             ->first(); 
              
              
          }    
                        
              
              
          }
              
              
          }
          
       
          
          if(!empty($PR)){   
        $newqty=$PR->Qty + $qq ; 
        
          ProductsQty::where('id',$PR->id)->update(['Qty'=>$newqty]);
          }
      }
            
            
            
            
        }
             
             
         foreach($Pros as $pro){     
            $Products=TicketProducts::where('Ticket',$pro->Ticket)->get();    
               
 
      foreach($Products as $prod){
          
        $unit=ProductUnits::where('Unit',$prod->Unit)->where('Product',$prod->Product)->first();  
               
              $qq= $unit->Rate * $prod->Qty ;  
          
        $PR=ProductsQty::where('Product',$prod->Product)
             ->where('P_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
          
          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
              
                    if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
                        
                          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPPP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
              
              
          }    
                        
              
              
          }
              
              
          }
          
          
          
             if(!empty($PR)){
        $newqty=$PR->Qty - $qq ; 
        
          ProductsQty::where('id',$PR->id)->update(['Qty'=>$newqty]);
             }
      }
            
            
            
            
        }
           
             }
   ShippingListTickets::where('Shipping_List',$id)->delete();
            
            
                  
              $Code=request('Codee');
              $Sender_Name=request('Sender_Name');
              $Addressees_Name=request('Addressees_Name');
              $Total_Qty=request('Total_Qty');
              $Total=request('Total');
              $Pay=request('Pay');
              $Notes=request('Notes');
              $Ticket=request('Ticket');
  
          
            for($i=0 ; $i < count($Code) ; $i++){
                
                $uu['Shipping_List']=$ID;
                $uu['Code']=$Code[$i];
                $uu['Sender_Name']=$Sender_Name[$i];
                $uu['Addressees_Name']=$Addressees_Name[$i];
                $uu['Total_Qty']=$Total_Qty[$i];
                $uu['Total_Price']=$Total[$i];
                $uu['Payment_Method']=$Pay[$i];
                $uu['Notes']=$Notes[$i];
                $uu['Ticket']=$Ticket[$i];

               ShippingListTickets::create($uu); 
       
                
       Ticket::where('id',$Ticket[$i])->update(['Selected'=>1]);  
                
            $prods=TicketProducts::where('Ticket',$Ticket[$i])->get();    
              
                
            foreach($prods as $pro){
               $pp=ProductUnits::where('Product',$pro->Product)->where('Unit',$pro->Unit)->first();    
            $plow=ProductUnits::where('Product',$pro->Product)->where('Rate',1)->first();       
                  $prooooo=Products::find($pro->Product);
                
                
    //From            
                      $Quantity =ProductsQty::
                where('Store',$pro->Store)    
                ->where('Product',$pro->Product)    
                ->where('P_Code',$pro->Product_Code)    
                ->first(); 
    


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$pro->Store)    
                ->where('Product',$pro->Product)    
                ->where('PP_Code',$pro->Product_Code)    
                ->first(); 

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$pro->Store)    
                ->where('Product',$pro->Product)    
                ->where('PPP_Code',$pro->Product_Code)    
                ->first(); 


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$pro->Store)    
                ->where('Product',$pro->Product)    
                ->where('PPPP_Code',$pro->Product_Code)    
                ->first(); 

}



}



}

               
            if(!empty($Quantity)){    
           $unit=ProductUnits::where('Unit',$pro->Unit)->where('Product',$pro->Product)->first();  
                
           $qq= $unit->Rate * $pro->Qty ;
                
           $newqty=$Quantity->Qty -  $qq ; 
                
         
               ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$newqty]);   
                
            }
                  
     //To           
         
                            $QuantityTo =ProductsQty::
                where('Store',request('Car_Store'))    
                ->where('Product',$pro->Product)    
                ->where('P_Code',$pro->Product_Code)    
                ->first(); 
    
if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Car_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PP_Code',$pro->Product_Code)    
                ->first(); 

if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Car_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PPP_Code',$pro->Product_Code)    
                ->first(); 


if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Car_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PPPP_Code',$pro->Product_Code)    
                ->first(); 

}



}






}
        
                
           
                    
            if(!empty($QuantityTo)){    
           $unit=ProductUnits::where('Unit',$pro->Unit)->where('Product',$pro->Product)->first();  
                
           $qq= $unit->Rate * $pro->Qty ;
                
           $newqty=$QuantityTo->Qty +  $qq ; 
                
       
                  $prooooo=Products::find($pro->Product); 

   $plow=ProductUnits::where('Product',$pro->Product)->where('Rate',1)->first();  
    $pp=ProductUnits::where('Product',$pro->Product)->where('Unit',$pro->Unit)->first();  

        $purchs=ProductsPurchases::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',request('Car_Store'))->get()->sum('Total_Bf_Tax');     
        $countPurchs=ProductsPurchases::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',request('Car_Store'))->get()->sum('SmallQty');
                
    $purchsStart=ProductsStartPeriods::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',request('Car_Store'))->get()->sum('Total');     
                
    $countStart=ProductsStartPeriods::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',request('Car_Store'))->get()->sum('SmallQty');
        $storesTransfer=ProductsStoresTransfers::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('To_Store',request('Car_Store'))->get()->sum('Total');
                
         $storesTransferCount=ProductsStoresTransfers::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('To_Store',request('Car_Store'))->get()->sum('SmallTrans_Qty');          
              
                
           $OUTCOME=OutcomManufacturingModel::where('Product',$pro->Product)->where('Store',request('Car_Store'))->where('SmallCode',$plow->Barcode)->get()->sum('Cost');     
           
$countOUTCOME=OutcomManufacturingModel::where('Product',$pro->Product)->where('Store',request('Car_Store'))->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');      


     $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME; 
            $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

       if($CollectCount != 0){
    $ty= $Collect /  $CollectCount ; 
                }else{
                    
                   $ty= $Collect;   
                }
   
   if($ty != 0){
                   $in=0;
         $out=$qq * $ty ;     
         $current=$newqty * $ty ;  
                }else{
                  
             $in=0;
         $out=$qq * 1;     
         $current=$newqty * 1;        
                    
                }
                
                                               $cur=$newqty * $ty ;
               ProductsQty::where('id',$QuantityTo->id)->update(['Qty'=>$newqty,'Price'=>$ty , 'TotalCost'=>$cur]);   
                
            }else{
                
                    $sNam=null;
                    $ssNam=null;
                      $sId=null;
                     $ssId=null; 
                
                   $id_store = DB::table('products_stores')->insertGetId(
            
        array(
            
            'P_Ar_Name' =>$pro->P_Ar_Name,
            'P_En_Name' => $pro->P_En_Name,
            'P_Code' =>   $pro->Product_Code,
            'Exp_Date' => null,
            'Product' => $pro->Product,
            'Store' =>request('Car_Store'),
            'V1' => $sId,
            'V2' => $ssId,        
            'V_Name' => $sNam,        
            'VV_Name' => $ssNam,        
     
        )
    );          
                

                    $pqty['P_Ar_Name']=$pro->P_Ar_Name;
                 $pqty['Exp_Date']=null;
                    $pqty['P_En_Name']=$pro->P_En_Name;
                    $pqty['Qty']=$pro->Qty * $pp->Rate;
                    $pqty['Price']=$pro->Price;
                    $pqty['TotalCost']=$pro->Price * $pro->Qty; 
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=request('Car_Store');
                    $pqty['Unit']=$pro->Unit;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$pro->Product;
                  $pqty['Price_Sale']=$pro->Price;
                  $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;    
                    $pqty['P_Code']=$pro->Product_Code;  
           $prooooo=Products::find($pro->Product); 
                        $pqty['SearchCode1']=$prooooo->SearchCode1;
                    $pqty['SearchCode2']=$prooooo->SearchCode2;
  $proooooStore=Stores::find(request('Car_Store'));
   $pqty['Group']=$prooooo->Group;
                    $pqty['Brand']=$prooooo->Brand;
                    $pqty['Branch']=$proooooStore->Branch;
              ProductsQty::create($pqty);  
                
                
            }
             
                
                
                
                
                
           
 } 
   
         
            }
          }


           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
           $dataUser['Screen']='قائمه الشحن';
           $dataUser['ScreenEn']='Shipping List';
           $dataUser['Type']='تعديل';
           $dataUser['TypeEn']='Edit';
           $dataUser['Explain']=request('Code');
           $dataUser['ExplainEn']=request('Code');
           UsersMoves::create($dataUser);
         
           session()->flash('success',trans('admin.Updated'));
           return redirect('ShippingListSechdule'); 
                 
         
     }
    
    //DeleteShippingList
         public function DeleteShippingList($id){
                      
        $del=ShippingList::find($id);
  
   
    $Pros=ShippingListTickets::where('Shipping_List',$del->id)->get();  
             if(!empty($Pros)){
        foreach($Pros as $pro){     
            
            Ticket::where('id',$pro->Ticket)->update(['Selected'=>0]);  
                
            $Products=TicketProducts::where('Ticket',$pro->Ticket)->get();    
               
 
      foreach($Products as $prod){
          
        $unit=ProductUnits::where('Unit',$prod->Unit)->where('Product',$prod->Product)->first();  
               
              $qq= $unit->Rate * $prod->Qty ;  
          
        $PR=ProductsQty::where('Product',$prod->Product)
             ->where('P_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Ticket_Store) 
             ->first(); 
          
          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Ticket_Store) 
             ->first(); 
              
                    if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Ticket_Store) 
             ->first(); 
                        
                          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPPP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Ticket_Store) 
             ->first(); 
              
              
          }    
                        
              
              
          }
              
              
          }
          
       
          
             
        $newqty=$PR->Qty + $qq ; 
        
          ProductsQty::where('id',$PR->id)->update(['Qty'=>$newqty]);
          
      }
            
            
            
            
        }
             
             
                  foreach($Pros as $pro){     
            $Products=TicketProducts::where('Ticket',$pro->Ticket)->get();    
               
 
      foreach($Products as $prod){
          
        $unit=ProductUnits::where('Unit',$prod->Unit)->where('Product',$prod->Product)->first();  
               
              $qq= $unit->Rate * $prod->Qty ;  
          
        $PR=ProductsQty::where('Product',$prod->Product)
             ->where('P_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
          
          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
              
                    if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
                        
                          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPPP_Code',$prod->Product_Code) 
             ->where('Store',$pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
              
              
          }    
                        
              
              
          }
              
              
          }
          
          
          
             
        $newqty=$PR->Qty - $qq ; 
        
          ProductsQty::where('id',$PR->id)->update(['Qty'=>$newqty]);
          
      }
            
            
            
            
        }
           
             }
           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
             $dataUser['Screen']='قائمه الشحن';
           $dataUser['ScreenEn']='Shipping List';
           $dataUser['Type']='حذف';
           $dataUser['TypeEn']='Delete';
           $dataUser['Explain']=$del->Code;
           $dataUser['ExplainEn']=$del->Code;
           UsersMoves::create($dataUser);
          ShippingListTickets::where('Shipping_List',$id)->delete();
        $del->delete();
        session()->flash('error',trans('admin.Deleted'));
        return back();

           }   
        
    
    //ShippingListStatus
         public function ShippingListStatus($id){
                      
        ShippingList::where('id',$id)->update(['Status'=>1]);
  
        session()->flash('success',trans('admin.Updated'));
        return back();

           }   
        
    
        //=============================================================
    
    
    //ShipmentReceipts
              public function ShipmentReceipts(){
         if(auth()->guard('admin')->user()->emp == 0){
         
         $Stores=Stores::all();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->store)){
                
                   if(auth()->guard('admin')->user()->pos_stores == 0){
                       
                          $Stores=Stores::where('id',auth()->guard('admin')->user()->store)->get();
                   }else{
                       
                     $Stores=Stores::all();    
                   }    
                
                
            }else{
                
                 $Stores=Stores::all();
            }
         
     }   
   
                
      $res=ShipmentReceipts::orderBy('id','desc')->first();
           
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
               
           }else{
               
              $Code=1; 
               
           }
                      
        $Shippings=ShippingList::where('Status',1)->get();       
      
         return view('admin.Shipping.ShipmentReceipts',[
             'Stores'=>$Stores,
             'Code'=>$Code,
             'Shippings'=>$Shippings,           
         ]);
    }

             function ShippingIDFilter(Request $request)
             {  
     if($request->ajax())
     { 
      $output = '';
       $shipping = $request->get('shipping');          
      
    if($shipping != '')
    {

$ship=ShippingList::find($shipping);     
        
    
       if(app()->getLocale() == 'ar' ){ 
        
    $Ticket_Store=$ship->Ticket_Store()->first()->Name;
$Car_Store=$ship->Car_Store()->first()->Name;
$Driver=$ship->Driver()->first()->Name;
$Travel_Area=$ship->Travel_Area()->first()->Arabic_Name;
$Access_Area  =  $ship->Access_Area()->first()->Arabic_Name;
       }else{
    
               $Ticket_Store=$ship->Ticket_Store()->first()->NameEn;
$Car_Store=$ship->Car_Store()->first()->NameEn;
$Driver=$ship->Driver()->first()->NameEn;
$Travel_Area=$ship->Travel_Area()->first()->English_Name;
$Access_Area  =  $ship->Access_Area()->first()->English_Name;
           
       }
    
     $data =ShippingListTickets::    
              where('Shipping_List',$shipping)                                
          ->get();         
                           
     }

         $total_row = $data->count();
      if($total_row > 0) 
      { 

         foreach($data as $rows){  
   

             if($rows->Payment_Method == 'Cash' or $rows->Payment_Method == 'كاش'){
                 $Pay=trans('admin.Cash');
                 $PayOption='<input type="hidden"  id="PayOption'.$rows->id.'" value="'.$rows->Total_Price.'">';  
                 
             }else{
                    $Pay=trans('admin.Later');  
                 $PayOption='<input type="hidden"  id="PayOption'.$rows->id.'" value="'.$rows->Total_Price.'">';  
             }
                 
             
             
                   if(app()->getLocale() == 'ar' ){ 
                      $SendName=$rows->Ticket()->first()->Sender_Name()->first()->Name; 
                      $AddName=$rows->Ticket()->first()->Addressees_Name()->first()->Name; 
                   
                   }else{
                               $SendName=$rows->Ticket()->first()->Sender_Name()->first()->NameEn; 
                      $AddName=$rows->Ticket()->first()->Addressees_Name()->first()->NameEn; 
                   
                       
                   }  
 
             
        $output .= '
        
       <tr id="Row'.$rows->id.'">
        <td>'.$rows->Code.'
    <input type="hidden" id="Code'.$rows->id.'" value="'.$rows->Code.'">    
    <input type="hidden" id="Ticket'.$rows->id.'" value="'.$rows->Ticket.'">    
        </td>
        <td>'.$SendName.'
         <input type="hidden" id="Sender_Name'.$rows->id.'" value="'.$SendName.'">   
        </td>
        <td>'.$AddName.'
         <input type="hidden" id="Addressees_Name'.$rows->id.'" value="'.$AddName.'">   
        </td>
        <td>'.$rows->Total_Qty.'
         <input type="hidden"  id="Total_Qty'.$rows->id.'" value="'.$rows->Total_Qty.'">   
        </td>
        <td>'.$rows->Total_Price.'
     <input type="hidden"  id="Total'.$rows->id.'" value="'.$rows->Total_Price.'">       
        </td>
        <td>'.$Pay.' '.$PayOption.'
     <input type="hidden" id="Pay'.$rows->id.'" value="'.$Pay.'">       
        </td>
        <td>'.$rows->Notes.'
     <input type="hidden" id="Notes'.$rows->id.'" value="'.$rows->Notes.'">       
        </td>
        </tr>
            ';
   

        }      

      }else
      {
       $output = '
        <div class="col-md-3">'.trans('admin.No_Data_Find').' </div>
       ';
      }
      $data = array(
       'table_data'  => $output,
          
        'Ticket_Store'=>$Ticket_Store,
    'Car_Store'=>$Car_Store,
    'Driver'=>$Driver,
    'Travel_Area'=>$Travel_Area,
    'Access_Area'=>$Access_Area,
    'Date_Travel'=>$ship->Date_Travel,
    'Date_Arrival'=>$ship->Date_Arrival,
    'Car_Number'=>$ship->Car_Number,
    'Tickets_Numbers'=>$ship->Tickets_Numbers,
    'Total_Cash'=>$ship->Total_Cash,
    'Total_Later'=>$ship->Total_Later,
    'Total_Price'=>$ship->Total_Price  
          
          
      );
      echo json_encode($data);
     }
    }
    
               public function AddShipmentReceipts(){
         
            $data= $this->validate(request(),[
             'Code'=>'required',
             'Date'=>'required',
             'ShippingList'=>'required',
             'Recived_Store'=>'required',
               ],[
            

         ]);
         

           $ID = DB::table('shipment_receipts')->insertGetId(
        array(
            
            'Recived_Store' => request('Recived_Store'),
            'Code' => request('Code'),
            'Date' => request('Date'),
            'Total_Cash' => request('Total_Cash'),
            'Total_Later' => request('Total_Later'),
            'Total_Price' => request('Total_Price'),
            'Tickets_Numbers' => request('Tickets_Numbers'),
            'Status' =>0,
            'ShippingList' => request('ShippingList'),
          
        )
    );  

                   $data=ShippingListTickets::where('Shipping_List',request('ShippingList'))->get();
                   $ship=ShippingList::find(request('ShippingList'));
            foreach($data as $row){
            
            
                $uu['Shipping_List']=request('ShippingList');
                $uu['Code']=$row->Code;
                $uu['Sender_Name']=$row->Sender_Name;
                $uu['Addressees_Name']=$row->Addressees_Name;
                $uu['Total_Qty']=$row->Total_Qty;
                $uu['Total_Price']=$row->Total_Price;
                $uu['Payment_Method']=$row->Payment_Method;
                $uu['Notes']=$row->Notes;
                $uu['Ticket']=$row->Ticket;
                $uu['ShipmentReceipts']=$ID;
                $uu['Status']=0;

               ShipmentReceiptsList::create($uu); 
       
                
       ShippingList::where('id',request('ShippingList'))->update(['Status'=>1]);  
              
                
                
            $prods=TicketProducts::where('Ticket',$row->Ticket)->get();    
              
                
            foreach($prods as $pro){
               $pp=ProductUnits::where('Product',$pro->Product)->where('Unit',$pro->Unit)->first();    
            $plow=ProductUnits::where('Product',$pro->Product)->where('Rate',1)->first();       
                  $prooooo=Products::find($pro->Product);
                
                
    //From            
                      $Quantity =ProductsQty::
                where('Store',$ship->Car_Store)    
                ->where('Product',$pro->Product)    
                ->where('P_Code',$pro->Product_Code)    
                ->first(); 
    


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$ship->Car_Store)    
                ->where('Product',$pro->Product)    
                ->where('PP_Code',$pro->Product_Code)    
                ->first(); 

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$ship->Car_Store)    
                ->where('Product',$pro->Product)    
                ->where('PPP_Code',$pro->Product_Code)    
                ->first(); 


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$ship->Car_Store)    
                ->where('Product',$pro->Product)    
                ->where('PPPP_Code',$pro->Product_Code)    
                ->first(); 

}



}



}

               
            if(!empty($Quantity)){    
           $unit=ProductUnits::where('Unit',$pro->Unit)->where('Product',$pro->Product)->first();  
                
           $qq= $unit->Rate * $pro->Qty ;
                
           $newqty=$Quantity->Qty -  $qq ; 
                
         
               ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$newqty]);   
                
            }
                  
     //To           
         
                            $QuantityTo =ProductsQty::
                where('Store',request('Recived_Store'))    
                ->where('Product',$pro->Product)    
                ->where('P_Code',$pro->Product_Code)    
                ->first(); 
    
if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Recived_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PP_Code',$pro->Product_Code)    
                ->first(); 

if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Recived_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PPP_Code',$pro->Product_Code)    
                ->first(); 


if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Recived_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PPPP_Code',$pro->Product_Code)    
                ->first(); 

}



}






}
        
                
           
                    
            if(!empty($QuantityTo)){    
           $unit=ProductUnits::where('Unit',$pro->Unit)->where('Product',$pro->Product)->first();  
                
           $qq= $unit->Rate * $pro->Qty ;
                
           $newqty=$QuantityTo->Qty +  $qq ; 
                
       
                  $prooooo=Products::find($pro->Product); 

   $plow=ProductUnits::where('Product',$pro->Product)->where('Rate',1)->first();  
    $pp=ProductUnits::where('Product',$pro->Product)->where('Unit',$pro->Unit)->first();  

        $purchs=ProductsPurchases::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',$ship->Car_Store)->get()->sum('Total_Bf_Tax');     
        $countPurchs=ProductsPurchases::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',$ship->Car_Store)->get()->sum('SmallQty');
                
    $purchsStart=ProductsStartPeriods::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',$ship->Car_Store)->get()->sum('Total');     
                
    $countStart=ProductsStartPeriods::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',$ship->Car_Store)->get()->sum('SmallQty');
        $storesTransfer=ProductsStoresTransfers::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('To_Store',$ship->Car_Store)->get()->sum('Total');
                
         $storesTransferCount=ProductsStoresTransfers::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('To_Store',$ship->Car_Store)->get()->sum('SmallTrans_Qty');          
              
                
           $OUTCOME=OutcomManufacturingModel::where('Product',$pro->Product)->where('Store',$ship->Car_Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');     
           
$countOUTCOME=OutcomManufacturingModel::where('Product',$pro->Product)->where('Store',$ship->Car_Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');      


     $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME; 
            $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

       if($CollectCount != 0){
    $ty= $Collect /  $CollectCount ; 
                }else{
                    
                   $ty= $Collect;   
                }
   
   if($ty != 0){
                   $in=0;
         $out=$qq * $ty ;     
         $current=$newqty * $ty ;  
                }else{
                  
             $in=0;
         $out=$qq * 1;     
         $current=$newqty * 1;        
                    
                }
                
                                               $cur=$newqty * $ty ;
               ProductsQty::where('id',$QuantityTo->id)->update(['Qty'=>$newqty,'Price'=>$ty , 'TotalCost'=>$cur]);   
                
            }else{
                
                    $sNam=null;
                    $ssNam=null;
                      $sId=null;
                     $ssId=null; 
                
                   $id_store = DB::table('products_stores')->insertGetId(
            
        array(
            
            'P_Ar_Name' =>$pro->P_Ar_Name,
            'P_En_Name' => $pro->P_En_Name,
            'P_Code' =>   $pro->Product_Code,
            'Exp_Date' => null,
            'Product' => $pro->Product,
            'Store' =>$ship->Car_Store,
            'V1' => $sId,
            'V2' => $ssId,        
            'V_Name' => $sNam,        
            'VV_Name' => $ssNam,        
     
        )
    );          
                

                    $pqty['P_Ar_Name']=$pro->P_Ar_Name;
                 $pqty['Exp_Date']=null;
                    $pqty['P_En_Name']=$pro->P_En_Name;
                    $pqty['Qty']=$pro->Qty * $pp->Rate;
                    $pqty['Price']=$pro->Price;
                    $pqty['TotalCost']=$pro->Price * $pro->Qty; 
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$ship->Car_Store;
                    $pqty['Unit']=$pro->Unit;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$pro->Product;
                  $pqty['Price_Sale']=$pro->Price;
                  $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;    
                    $pqty['P_Code']=$pro->Product_Code;  
           $prooooo=Products::find($pro->Product); 
                        $pqty['SearchCode1']=$prooooo->SearchCode1;
                    $pqty['SearchCode2']=$prooooo->SearchCode2;
  $proooooStore=Stores::find($ship->Car_Store);
   $pqty['Group']=$prooooo->Group;
                    $pqty['Brand']=$prooooo->Brand;
                    $pqty['Branch']=$proooooStore->Branch;
              ProductsQty::create($pqty);  
                
                
            }
             
                
                
                
                
                
           
 } 
   
  
          }

                   
                ShippingList::where('id',request('ShippingList'))->update(['Status'=>2]);   
                   
           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());

            $dataUser['Screen']='استلام شحنات';
           $dataUser['ScreenEn']='Shipment Receipts';
           $dataUser['Type']='اضافه جديده';
           $dataUser['TypeEn']='New Add';
           $dataUser['Explain']=request('Code');
           $dataUser['ExplainEn']=request('Code');
           UsersMoves::create($dataUser);
         
           session()->flash('success',trans('admin.Added_Successfully'));
         if(request('SP') == 0){  return back(); }elseif(request('SP') == 1){  return redirect('ShipmentReceiptsPrint/'.$ID); } 
                 
         
     }
    
    
         public function ShipmentReceiptsSechdule(){
      $items=ShipmentReceipts::orderBy('id','desc')->paginate(20);
            
             $ships=ShipmentReceipts::where('Status',0)->get();
             
             foreach($ships as $ship){
                 
                 
                    $Prods=ShipmentReceiptsList::where('ShipmentReceipts',$ship->id)->where('Status',0)->count(); 
                 
                 
                 if($Prods == 0){
                     
                   ShipmentReceipts::where('id',$ship->id)->update(['Status'=>1]);  
                 }
                 
                 
             }
             
         return view('admin.Shipping.ShipmentReceiptsSechdule',[
             'items'=>$items,
         ]);
    }
    
    
       //ShipmentReceiptsPrint
         public function ShipmentReceiptsPrint($id){
      $item=ShipmentReceipts::find($id);
       $Prods=ShipmentReceiptsList::where('ShipmentReceipts',$item->id)->get(); 
         return view('admin.Shipping.ShipmentReceiptsPrint',[
             'item'=>$item,
             'Prods'=>$Prods,
         ]);
    }
    
    //ShipmentReceiptsEdit
          public function ShipmentReceiptsEdit($id){
         if(auth()->guard('admin')->user()->emp == 0){
         
         $Stores=Stores::all();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->store)){
                
                   if(auth()->guard('admin')->user()->pos_stores == 0){
                       
                          $Stores=Stores::where('id',auth()->guard('admin')->user()->store)->get();
                   }else{
                       
                     $Stores=Stores::all();    
                   }    
                
                
            }else{
                
                 $Stores=Stores::all();
            }
         
     }   
   
                $item=ShipmentReceipts::find($id);
       $Prods=ShipmentReceiptsList::where('ShipmentReceipts',$item->id)->get();       
        
            
                                     if($item->Status != 0){  
   session()->flash('error',trans('admin.Already_Done'));
               return redirect('ShipmentReceiptsSechdule');
        
                    }
         return view('admin.Shipping.ShipmentReceiptsEdit',[
             'Stores'=>$Stores,
             'item'=>$item,
             'Prods'=>$Prods,
                  
         ]);
    }

          public function PostEditShipmentReceipts(){
         
            $data= $this->validate(request(),[
             'Code'=>'required',
             'Date'=>'required',
             'ShippingList'=>'required',
             'Recived_Store'=>'required',
               ],[
            

         ]);
         

           $ID = request('ID');
            
            $data['Recived_Store'] = request('Recived_Store');
            $data['Code'] = request('Code');
            $data['Date'] = request('Date');
            $data['Total_Cash'] = request('Total_Cash');
            $data['Total_Later'] = request('Total_Later');
            $data['Total_Price'] = request('Total_Price');
            $data['Tickets_Numbers'] = request('Tickets_Numbers');
            $data['Status'] =0;
            $data['ShippingList'] = request('ShippingList');
          ShipmentReceipts::where('id',$ID)->update($data);
  

                   $data=ShippingListTickets::where('Shipping_List',request('ShippingList'))->get();
                   $ship=ShippingList::find(request('ShippingList'));
              
              
              $id=$ID;
                  $del=ShipmentReceipts::find($id);
    $Pros=ShipmentReceiptsList::where('ShipmentReceipts',$del->id)->get();  
               $ship=ShippingList::find($del->ShippingList); 
                ShippingList::where('id',$del->ShippingList)->update(['Status'=>1]);  
             if(!empty($Pros)){
        foreach($Pros as $pro){     
            
          
                
            $Products=TicketProducts::where('Ticket',$pro->Ticket)->get();    
             
 
      foreach($Products as $prod){
          
        $unit=ProductUnits::where('Unit',$prod->Unit)->where('Product',$prod->Product)->first();  
               
              $qq= $unit->Rate * $prod->Qty ;  
          
        $PR=ProductsQty::where('Product',$prod->Product)
             ->where('P_Code',$prod->Product_Code) 
             ->where('Store',  $pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
          
          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PP_Code',$prod->Product_Code) 
             ->where('Store',  $pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
              
                    if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPP_Code',$prod->Product_Code) 
             ->where('Store',  $pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
                        
                          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPPP_Code',$prod->Product_Code) 
             ->where('Store',  $pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
              
              
          }    
                        
              
              
          }
              
              
          }
          
       
          
             
        $newqty=$PR->Qty + $qq ; 
        
          ProductsQty::where('id',$PR->id)->update(['Qty'=>$newqty]);
          
      }
            
            
            
            
        }
             
             
                  foreach($Pros as $pro){     
            $Products=TicketProducts::where('Ticket',$pro->Ticket)->get();    
               
 
      foreach($Products as $prod){
          
        $unit=ProductUnits::where('Unit',$prod->Unit)->where('Product',$prod->Product)->first();  
               
              $qq= $unit->Rate * $prod->Qty ;  
          
        $PR=ProductsQty::where('Product',$prod->Product)
             ->where('P_Code',$prod->Product_Code) 
             ->where('Store',$ship->Recived_Store) 
             ->first(); 
          
          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PP_Code',$prod->Product_Code) 
             ->where('Store',$ship->Recived_Store) 
             ->first(); 
              
                    if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPP_Code',$prod->Product_Code) 
             ->where('Store',$ship->Recived_Store) 
             ->first(); 
                        
                          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPPP_Code',$prod->Product_Code) 
             ->where('Store',$ship->Recived_Store) 
             ->first(); 
              
              
          }    
                        
              
              
          }
              
              
          }
          
          
          
             
        $newqty=$PR->Qty - $qq ; 
        
          ProductsQty::where('id',$PR->id)->update(['Qty'=>$newqty]);
          
      }
            
            
            
            
        }
           
             }
ShipmentReceiptsList::where('ShipmentReceipts',$id)->delete();
              
              
            foreach($data as $row){
            
            
                $uu['Shipping_List']=request('ShippingList');
                $uu['Code']=$row->Code;
                $uu['Sender_Name']=$row->Sender_Name;
                $uu['Addressees_Name']=$row->Addressees_Name;
                $uu['Total_Qty']=$row->Total_Qty;
                $uu['Total_Price']=$row->Total_Price;
                $uu['Payment_Method']=$row->Payment_Method;
                $uu['Notes']=$row->Notes;
                $uu['Ticket']=$row->Ticket;
                $uu['ShipmentReceipts']=$ID;
                $uu['Status']=0;

               ShipmentReceiptsList::create($uu); 
       
                
       ShippingList::where('id',request('ShippingList'))->update(['Status'=>1]);  
              
                
                
            $prods=TicketProducts::where('Ticket',$row->Ticket)->get();    
              
                
            foreach($prods as $pro){
               $pp=ProductUnits::where('Product',$pro->Product)->where('Unit',$pro->Unit)->first();    
            $plow=ProductUnits::where('Product',$pro->Product)->where('Rate',1)->first();       
                  $prooooo=Products::find($pro->Product);
                
                
    //From            
                      $Quantity =ProductsQty::
                where('Store',$ship->Car_Store)    
                ->where('Product',$pro->Product)    
                ->where('P_Code',$pro->Product_Code)    
                ->first(); 
    


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$ship->Car_Store)    
                ->where('Product',$pro->Product)    
                ->where('PP_Code',$pro->Product_Code)    
                ->first(); 

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$ship->Car_Store)    
                ->where('Product',$pro->Product)    
                ->where('PPP_Code',$pro->Product_Code)    
                ->first(); 


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$ship->Car_Store)    
                ->where('Product',$pro->Product)    
                ->where('PPPP_Code',$pro->Product_Code)    
                ->first(); 

}



}



}

               
            if(!empty($Quantity)){    
           $unit=ProductUnits::where('Unit',$pro->Unit)->where('Product',$pro->Product)->first();  
                
           $qq= $unit->Rate * $pro->Qty ;
                
           $newqty=$Quantity->Qty -  $qq ; 
                
         
               ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$newqty]);   
                
            }
                  
     //To           
         
                            $QuantityTo =ProductsQty::
                where('Store',request('Recived_Store'))    
                ->where('Product',$pro->Product)    
                ->where('P_Code',$pro->Product_Code)    
                ->first(); 
    
if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Recived_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PP_Code',$pro->Product_Code)    
                ->first(); 

if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Recived_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PPP_Code',$pro->Product_Code)    
                ->first(); 


if(empty($QuantityTo)){

  $QuantityTo =ProductsQty::
                where('Store',request('Recived_Store'))    
                ->where('Product',$pro->Product)    
                ->where('PPPP_Code',$pro->Product_Code)    
                ->first(); 

}



}






}
        
                
           
                    
            if(!empty($QuantityTo)){    
           $unit=ProductUnits::where('Unit',$pro->Unit)->where('Product',$pro->Product)->first();  
                
           $qq= $unit->Rate * $pro->Qty ;
                
           $newqty=$QuantityTo->Qty +  $qq ; 
                
       
                  $prooooo=Products::find($pro->Product); 

   $plow=ProductUnits::where('Product',$pro->Product)->where('Rate',1)->first();  
    $pp=ProductUnits::where('Product',$pro->Product)->where('Unit',$pro->Unit)->first();  

        $purchs=ProductsPurchases::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',$ship->Car_Store)->get()->sum('Total_Bf_Tax');     
        $countPurchs=ProductsPurchases::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',$ship->Car_Store)->get()->sum('SmallQty');
                
    $purchsStart=ProductsStartPeriods::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',$ship->Car_Store)->get()->sum('Total');     
                
    $countStart=ProductsStartPeriods::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('Store',$ship->Car_Store)->get()->sum('SmallQty');
        $storesTransfer=ProductsStoresTransfers::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('To_Store',$ship->Car_Store)->get()->sum('Total');
                
         $storesTransferCount=ProductsStoresTransfers::where('Product',$pro->Product)->where('SmallCode',$plow->Barcode)->where('To_Store',$ship->Car_Store)->get()->sum('SmallTrans_Qty');          
              
                
           $OUTCOME=OutcomManufacturingModel::where('Product',$pro->Product)->where('Store',$ship->Car_Store)->where('SmallCode',$plow->Barcode)->get()->sum('Cost');     
           
$countOUTCOME=OutcomManufacturingModel::where('Product',$pro->Product)->where('Store',$ship->Car_Store)->where('SmallCode',$plow->Barcode)->get()->sum('SmallQty');      


     $Collect=$purchs + $purchsStart + $storesTransfer + $OUTCOME; 
            $CollectCount=$countPurchs + $countStart + $storesTransferCount + $countOUTCOME ;

       if($CollectCount != 0){
    $ty= $Collect /  $CollectCount ; 
                }else{
                    
                   $ty= $Collect;   
                }
   
   if($ty != 0){
                   $in=0;
         $out=$qq * $ty ;     
         $current=$newqty * $ty ;  
                }else{
                  
             $in=0;
         $out=$qq * 1;     
         $current=$newqty * 1;        
                    
                }
                
                                               $cur=$newqty * $ty ;
               ProductsQty::where('id',$QuantityTo->id)->update(['Qty'=>$newqty,'Price'=>$ty , 'TotalCost'=>$cur]);   
                
            }else{
                
                    $sNam=null;
                    $ssNam=null;
                      $sId=null;
                     $ssId=null; 
                
                   $id_store = DB::table('products_stores')->insertGetId(
            
        array(
            
            'P_Ar_Name' =>$pro->P_Ar_Name,
            'P_En_Name' => $pro->P_En_Name,
            'P_Code' =>   $pro->Product_Code,
            'Exp_Date' => null,
            'Product' => $pro->Product,
            'Store' =>$ship->Car_Store,
            'V1' => $sId,
            'V2' => $ssId,        
            'V_Name' => $sNam,        
            'VV_Name' => $ssNam,        
     
        )
    );          
                

                    $pqty['P_Ar_Name']=$pro->P_Ar_Name;
                 $pqty['Exp_Date']=null;
                    $pqty['P_En_Name']=$pro->P_En_Name;
                    $pqty['Qty']=$pro->Qty * $pp->Rate;
                    $pqty['Price']=$pro->Price;
                    $pqty['TotalCost']=$pro->Price * $pro->Qty; 
                    $pqty['Pro_Stores']=$id_store;
                    $pqty['Store']=$ship->Car_Store;
                    $pqty['Unit']=$pro->Unit;
                    $pqty['Low_Unit']=$plow->Unit;
                    $pqty['Product']=$pro->Product;
                  $pqty['Price_Sale']=$pro->Price;
                  $pqty['V1']=null;
                    $pqty['V2']=null;
                    $pqty['V_Name']=null;
                    $pqty['VV_Name']=null;    
                    $pqty['P_Code']=$pro->Product_Code;  
           $prooooo=Products::find($pro->Product); 
                        $pqty['SearchCode1']=$prooooo->SearchCode1;
                    $pqty['SearchCode2']=$prooooo->SearchCode2;
  $proooooStore=Stores::find($ship->Car_Store);
   $pqty['Group']=$prooooo->Group;
                    $pqty['Brand']=$prooooo->Brand;
                    $pqty['Branch']=$proooooStore->Branch;
              ProductsQty::create($pqty);  
                
                
            }
             
                
                
                
                
                
           
 } 
   
  
          }

           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
                $dataUser['Screen']='استلام شحنات';
           $dataUser['ScreenEn']='Shipment Receipts';
           $dataUser['Type']='تعديل';
           $dataUser['TypeEn']='Edit';
           $dataUser['Explain']=request('Code');
           $dataUser['ExplainEn']=request('Code');
           UsersMoves::create($dataUser);
         
           session()->flash('success',trans('admin.Updated'));
          return redirect('ShipmentReceiptsSechdule'); 
                 
         
     }
    
   
//DeleteShipmentReceipts
         public function DeleteShipmentReceipts($id){
                      
        $del=ShipmentReceipts::find($id);
  
   
    $Pros=ShipmentReceiptsList::where('ShipmentReceipts',$del->id)->get();  
               $ship=ShippingList::find($del->ShippingList); 
                ShippingList::where('id',$del->ShippingList)->update(['Status'=>0]);  
             if(!empty($Pros)){
        foreach($Pros as $pro){     
            
          
                
            $Products=TicketProducts::where('Ticket',$pro->Ticket)->get();    
             
 
      foreach($Products as $prod){
          
        $unit=ProductUnits::where('Unit',$prod->Unit)->where('Product',$prod->Product)->first();  
               
              $qq= $unit->Rate * $prod->Qty ;  
          
        $PR=ProductsQty::where('Product',$prod->Product)
             ->where('P_Code',$prod->Product_Code) 
             ->where('Store',  $pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
          
          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PP_Code',$prod->Product_Code) 
             ->where('Store',  $pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
              
                    if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPP_Code',$prod->Product_Code) 
             ->where('Store',  $pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
                        
                          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPPP_Code',$prod->Product_Code) 
             ->where('Store',  $pro->Shipping_List()->first()->Car_Store) 
             ->first(); 
              
              
          }    
                        
              
              
          }
              
              
          }
          
       
          
             
        $newqty=$PR->Qty + $qq ; 
        
          ProductsQty::where('id',$PR->id)->update(['Qty'=>$newqty]);
          
      }
            
            
            
            
        }
             
             
                  foreach($Pros as $pro){     
            $Products=TicketProducts::where('Ticket',$pro->Ticket)->get();    
               
 
      foreach($Products as $prod){
          
        $unit=ProductUnits::where('Unit',$prod->Unit)->where('Product',$prod->Product)->first();  
               
              $qq= $unit->Rate * $prod->Qty ;  
          
        $PR=ProductsQty::where('Product',$prod->Product)
             ->where('P_Code',$prod->Product_Code) 
             ->where('Store',$ship->Recived_Store) 
             ->first(); 
          
          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PP_Code',$prod->Product_Code) 
             ->where('Store',$ship->Recived_Store) 
             ->first(); 
              
                    if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPP_Code',$prod->Product_Code) 
             ->where('Store',$ship->Recived_Store) 
             ->first(); 
                        
                          if(empty($PR)){
             
              $PR=ProductsQty::where('Product',$prod->Product)
             ->where('PPPP_Code',$prod->Product_Code) 
             ->where('Store',$ship->Recived_Store) 
             ->first(); 
              
              
          }    
                        
              
              
          }
              
              
          }
          
          
          
             
        $newqty=$PR->Qty - $qq ; 
        
          ProductsQty::where('id',$PR->id)->update(['Qty'=>$newqty]);
          
      }
            
            
            
            
        }
           
             }
           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
           $dataUser['Screen']='استلام شحنات';
           $dataUser['ScreenEn']='Shipment Receipts';
           $dataUser['Type']='حذف';
           $dataUser['TypeEn']='Delete';
           $dataUser['Explain']=$del->Code;
           $dataUser['ExplainEn']=$del->Code;
           UsersMoves::create($dataUser);
          ShipmentReceiptsList::where('ShipmentReceipts',$id)->delete();
        $del->delete();
        session()->flash('error',trans('admin.Deleted'));
        return back();

           }   
    
       //=============================================================
    
    
    //ShipmentReceiptsClients
    
         public function ShipmentReceiptsClients(){
         if(auth()->guard('admin')->user()->emp == 0){
         
         $Stores=Stores::all();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->store)){
                
                   if(auth()->guard('admin')->user()->pos_stores == 0){
                       
                          $Stores=Stores::where('id',auth()->guard('admin')->user()->store)->get();
                   }else{
                       
                     $Stores=Stores::all();    
                   }    
                
                
            }else{
                
                 $Stores=Stores::all();
            }
         
     }   
   
                
      $res=ShipmentReceiptsClients::orderBy('id','desc')->first();
           
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
               
           }else{
               
              $Code=1; 
               
           }

  if(auth()->guard('admin')->user()->emp == 0){
         
          $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
     }else{
        
            if(!empty(auth()->guard('admin')->user()->safe)){
         $Safes=AcccountingManual::where('id',auth()->guard('admin')->user()->safe)->get();
            }else{
                
                  $Safes = AcccountingManual::
             where('Type',1)
              ->where('Parent',28)
              ->orWhere('Parent',29)
              ->get();
            }
         
     }
          
          
          $Clients = AcccountingManual::
             where('Type',1)
              ->where('Parent',24)
              ->get();
          
          $Coins=Coins::all();
                
      $ShipmentReceipts=ShipmentReceipts::where('Status',0)->get();
         return view('admin.Shipping.ShipmentReceiptsClients',[
             'Stores'=>$Stores,
             'Code'=>$Code,
             'Safes'=>$Safes,
             'Clients'=>$Clients,
             'Coins'=>$Coins,
             'ShipmentReceipts'=>$ShipmentReceipts,
           
         ]);
    }
    
             function ShippingReciptFilter(Request $request)
             {  
     if($request->ajax())
     { 
      $output = '';
       $shipping = $request->get('shipping');          
      
    if($shipping != '')
    {

     $data =ShipmentReceiptsList::    
              where('ShipmentReceipts',$shipping)                                
              ->where('Status',0)                                
          ->get();         
                           
     }

         $total_row = $data->count();
      if($total_row > 0) 
      { 

         foreach($data as $rows){  
   
             if($rows->Payment_Method == 'Cash' or $rows->Payment_Method == 'كاش'){
                 $Pay=trans('admin.Cash');
                 $PayOption='<input type="hidden"  id="PayOption'.$rows->id.'" value="'.$rows->Total.'">';  
                 
             }else{
                    $Pay=trans('admin.Later');  
                 $PayOption='<input type="hidden"  id="PayOption'.$rows->id.'" value="'.$rows->Total.'">';  
             }
          
             
                       if(app()->getLocale() == 'ar' ){ 
                      $SendName=$rows->Ticket()->first()->Sender_Name()->first()->Name; 
                      $AddName=$rows->Ticket()->first()->Addressees_Name()->first()->Name; 
                   
                   }else{
                               $SendName=$rows->Ticket()->first()->Sender_Name()->first()->NameEn; 
                      $AddName=$rows->Ticket()->first()->Addressees_Name()->first()->NameEn; 
                   
                       
                   }  
 
             
        $output .= '
        
       <tr id="Row'.$rows->id.'">
        <td>'.$rows->Code.'
    <input type="hidden" id="Code'.$rows->id.'" value="'.$rows->Code.'">    
    <input type="hidden" id="Ticket'.$rows->id.'" value="'.$rows->id.'">    
        </td>
        <td>'.$SendName.'
         <input type="hidden" id="Sender_Name'.$rows->id.'" value="'.$SendName.'">   
        </td>
        <td>'.$AddName.'
         <input type="hidden" id="Addressees_Name'.$rows->id.'" value="'.$AddName.'">   
        </td>
        <td>'.$rows->Total_Qty.'
         <input type="hidden"  id="Total_Qty'.$rows->id.'" value="'.$rows->Total_Qty.'">   
        </td>
        <td>'.$rows->Total.'
     <input type="hidden"  id="Total'.$rows->id.'" value="'.$rows->Total.'">       
        </td>
        <td>'.$Pay.' '.$PayOption.'
     <input type="hidden" id="Pay'.$rows->id.'" value="'.$Pay.'">       
        </td>
        <td>'.$rows->Notes.'
     <input type="hidden" id="Notes'.$rows->id.'" value="'.$rows->Notes.'">       
        </td>
     <td>

    <input type="radio" name="choice" class="form-control" onclick="ChoiceTicket('.$rows->Ticket.')" >      
        </td>        
        </tr>
            ';
   

        }      

      }else
      {
       $output = '
        <div class="col-md-3">'.trans('admin.No_Data_Find').'</div>
       ';
      }
      $data = array(
       'table_data'  => $output,
 
          
      );
      echo json_encode($data);
     }
    }
    
               function ShippingReciptTicketFilter(Request $request)
             {  
     if($request->ajax())
     { 
      $output = '';
       $ticket = $request->get('ticket');          
      
    if($ticket != '')
    {
        $newticket=Ticket::find($ticket);
     $data =TicketProducts::    
              where('Ticket',$ticket)                                                            
          ->get();       
        
        
           if(app()->getLocale() == 'ar' ){ 
        $Store=$newticket->Store()->first()->Name;

$Safe=$newticket->Safe()->first()->Name;

$Coin=$newticket->Coin()->first()->Arabic_Name;

$Sender_Name=$newticket->Sender_Name()->first()->Name;

$Addressees_Name=$newticket->Addressees_Name()->first()->Name;
           }else{
               
             $Store=$newticket->Store()->first()->NameEn;

$Safe=$newticket->Safe()->first()->NameEn;

$Coin=$newticket->Coin()->first()->English_Name;

$Sender_Name=$newticket->Sender_Name()->first()->NameEn;

$Addressees_Name=$newticket->Addressees_Name()->first()->NameEn;          
           }
        
                           
     }

         $total_row = $data->count();
      if($total_row > 0) 
      { 

         foreach($data as $rows){  

                 if(app()->getLocale() == 'ar' ){ 
                      $PrrroName=$rows->P_Ar_Name; 
                      $UniiName=$rows->Unit()->first()->Name; 

                   
                   }else{
                         $PrrroName=$rows->P_En_Name;  

                       $UniiName=$rows->Unit()->first()->NameEn;    

                       
                   }    
             
             
        $output .= '
        
       <tr id="Row'.$rows->id.'">
        <td>'.$PrrroName.' 
        </td>
        <td>'.$UniiName.'
        </td>
        <td>'.$rows->Product_Code.'
        </td>
        <td>'.$rows->Price.'

        </td>
        <td>'.$rows->Weight.'
  
        </td>
        <td>
           '.$rows->Length.'
        </td>
        <td>'.$rows->Width.'
    
        </td>     
        <td>'.$rows->Height.'
    
        </td>     
        <td>'.$rows->Qty.'
    
        </td>       
        <td>'.$rows->Total.'
    
        </td>

        </tr>
            ';
   

        }      

      }else
      {
       $output = '
        <div class="col-md-3">ل'.trans('admin.No_Data_Find').'</div>
       ';
      }
      $data = array(
       'table_data'  => $output,
       'Codee'  => $newticket->Code,
       'Date'  => $newticket->Date,
       'Store'  => $Store,
       'Safe'  => $Safe,
       'Coin'  => $Coin,
       'Draw'  => $newticket->Draw,
       'Payment_Method'  => $newticket->Payment_Method,
       'Sender_Name'  =>$Sender_Name,
       'Sender_Address'  => $newticket->Sender_Address,
       'Sender_Phone'  => $newticket->Sender_Phone,
       'Addressees_Name'  => $Addressees_Name,
       'Addressees_Address'  => $newticket->Addressees_Address,
       'Addressees_Phone'  => $newticket->Addressees_Phone,
       'Notes'  => $newticket->Notes,
       'Total_Price'  => $newticket->Total,
       'Total_Qty'  => $newticket->Total_Qty,
 
          
      );
      echo json_encode($data);
     }
    }
    
    
            public function AddShipmentReceiptsClients(){
         
            $data= $this->validate(request(),[
             'Code'=>'required',
             'Date'=>'required',
             'Safe'=>'required',
             'Coin'=>'required',

               ],[
            

         ]);
         

           $ID = DB::table('shipment_receipts_clients')->insertGetId(
        array(
            
            'Code' => request('Code'),
            'Date' => request('Date'),
            'ShipmentReceipts' => request('ShipmentReceipts'),
            'ShipmentReceiptsList' => request('ShipmentReceiptsList'),
            'Total_Price' => request('Total_Price'),
            'Total_Qty' => request('Total_Qty'),
            'Safe' => request('Safe'),
            'Coin' => request('Coin'),
            'Draw' => request('Draw'),
            'Pay' => request('Pay'),
            'Payment_Method' => request('Payment_Method'),
        
        )
    );  
    
              
                
                    $c= DB::select("SELECT last_value FROM shipment_receipts_clients_arr_seq");
      $f=array_shift($c);
      $z=end($f);    
  $CodeT=$z;   
                
             
            ShipmentReceiptsList::where('ShipmentReceipts',request('ShipmentReceipts'))->where('Ticket',request('ShipmentReceiptsList'))->orderBy('id','desc')->update(['Status'=>1]);
         
                $Prods=TicketProducts::where('Ticket',request('ShipmentReceiptsList'))->get();
                $ship=ShipmentReceipts::find(request('ShipmentReceipts'));
                $Ticket=Ticket::find(request('ShipmentReceiptsList'));
        foreach($Prods as $pro){        
             $Quantity =ProductsQty::
                where('Store',$ship->Recived_Store)    
                ->where('Product',$pro->Product)    
                ->where('P_Code',$pro->Product_Code)    
                ->first(); 

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$ship->Recived_Store)    
                ->where('Product',$pro->Product)    
                ->where('PP_Code',$pro->Product_Code)    
                ->first(); 

if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$ship->Recived_Store)    
                ->where('Product',$pro->Product)    
                ->where('PPP_Code',$pro->Product_Code)    
                ->first(); 


if(empty($Quantity)){

  $Quantity =ProductsQty::
                where('Store',$ship->Recived_Store)    
                ->where('Product',$pro->Product)    
                ->where('PPPP_Code',$pro->Product_Code)    
                ->first(); 

}



}






}

                
            if(!empty($Quantity)){    
           $unit=ProductUnits::where('Unit',$pro->Unit)->where('Product',$pro->Product)->first();  
                
           $qq= $unit->Rate * $pro->Qty ;
                
           $newqty=$Quantity->Qty -  $qq ; 
            
               ProductsQty::where('id',$Quantity->id)->update(['Qty'=>$newqty]);   
                
            }
           
        }
     
                  if(request('Payment_Method') == 'Later'){
                       
               $res=Journalizing::orderBy('id','desc')->first();
         
           if(!empty($res->Code)){
               
              $Code=$res->Code + 1 ; 
           }else{
              $Code=1; 
               
           }               
                                 
          $JunID = DB::table('journalizings')->insertGetId(
            
        array(
            
            'Code' => $Code,
                     'Type' => 'البوليصه',             'TypeEn' =>'Tickets',
            'Code_Type' => $CodeT,
            'Date' => request('Date'),
            'Draw' => request('Draw'),
            'Coin' => request('Coin'),
            'Cost_Center' => null,
            'Total_Debaitor' => request('Total_Price'),
            'Total_Creditor' => request('Total_Price'),
            'Note' => request('Note'),
  
        )
    );


        $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=0;
        $PRODUCTSS['Creditor']=request('Total_Price');
        $PRODUCTSS['Account']=$Ticket->Addressees_Name;
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=0;
        $Gen['Creditor']=request('Total_Price');
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * 0;
        $Gen['Creditor_Coin']=request('Draw') * request('Total_Price');
        $Gen['Account']=$Ticket->Addressees_Name;
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
        
        
        
         $PRODUCTSS['Joun_ID']=$JunID;
        $PRODUCTSS['Debitor']=request('Total_Price');
        $PRODUCTSS['Creditor']=0;
        $PRODUCTSS['Account']=request('Safe');
        $PRODUCTSS['Statement']=null;
      
    
         JournalizingDetails::create($PRODUCTSS);      
   
        $Gen['Code']=$Code;
        $Gen['Code_Type']=$CodeT;
        $Gen['Date']=request('Date');
          $Gen['Type']= 'البوليصه';         $Gen['TypeEn']='Tickets';
        $Gen['Debitor']=request('Total_Price');
        $Gen['Creditor']=0;
        $Gen['Statement']=null;
        $Gen['Draw']=request('Draw');
        $Gen['Debitor_Coin']= request('Draw') * request('Total_Price');
        $Gen['Creditor_Coin']=request('Draw') * 0;
        $Gen['Account']=request('Safe');
        $Gen['Coin']= request('Coin');
        $Gen['Cost_Center']=null;
        $Gen['userr']= auth()->guard('admin')->user()->id;

         GeneralDaily::create($Gen);          
                
       
                       
                   }
              
        
 
           $dataUser['User']=auth()->guard('admin')->user()->id;
           $dataUser['Date']=date('Y-m-d');
           $dataUser['Time']=date("h:i:s a", time());
     
                $dataUser['Screen']='استلام شحنات عملاء';
           $dataUser['ScreenEn']='Shipment Receipts Clients';
           $dataUser['Type']='اضافه جديده';
           $dataUser['TypeEn']='New Add';
           $dataUser['Explain']=$CodeT;
           $dataUser['ExplainEn']=$CodeT;
           UsersMoves::create($dataUser);
         
           session()->flash('success',trans('admin.Added_Successfully'));
         if(request('SP') == 0){  return back(); }elseif(request('SP') == 1){  return redirect('ShipmentReceiptsClientsPrint/'.$ID); } 
                 
         
     }

    
    
    //ShipmentReceiptsClientsSechdule
          public function ShipmentReceiptsClientsSechdule(){
      $items=ShipmentReceiptsClients::orderBy('id','desc')->paginate(20);
            
           
             
         return view('admin.Shipping.ShipmentReceiptsClientsSechdule',[
             'items'=>$items,
         ]);
    }
    
//ShipmentReceiptsClientsPrint
         public function ShipmentReceiptsClientsPrint($id){
      $item=ShipmentReceiptsClients::find($id);
                 
                  $Ticket=Ticket::find($item->ShipmentReceiptsList);
                                    
            $Prods=TicketProducts::where('Ticket',$item->ShipmentReceiptsList)->get(); 

         return view('admin.Shipping.ShipmentReceiptsClientsPrint',[
             'item'=>$item,
             'Ticket'=>$Ticket,
             'Prods'=>$Prods,
         ]);
    }
    
    
        
    
}
