<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use  App\Class_;
use  App\Classification;
use  App\Group;
use  App\Transporter;
use  App\Customer;
use  App\RecycleMethod;
use  App\Waste;
use App\Supplier;
use App\Main;
use Carbon\Carbon;
use Session;
use Auth; 
use App\Actions;
use App\Branch;

class ReportController extends Controller
{
    
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function report_create()
    {
        $transporters = Transporter::get();
        //$customers = Customer::get();
        $suppliers = Supplier::get();
        return view('report.create' , ['suppliers' => $suppliers , 'transporters'=>$transporters]);
        
    }


//ajax get suppliers
    public function get_suppliers( $from , $to){
        
        $mains = Main::with("supplier")
                        ->where('customer_id','!=',NULL)
                        ->whereDate('created_at','>=',$from)
                        ->whereDate('created_at','<=',$to)
                        ->groupBy('supplier_id')->get();
        return \Response::json(['suppliers_' => $mains, ]);

    }
    

  // ajax 
     public function get_class($supplier_id, $from , $to){
        
        Session::put('supplier_id', $supplier_id );
        Session::put('tracking_from', $from );
        Session::put('tracking_to', $to );

        $mains = Main::where('supplier_id',$supplier_id)
                        ->where('customer_id','!=',NULL)
                        //->whereBetween( 'created_at', [$from, $to] )
                        ->where('date','>=',$from)
                        ->where('date','<=',$to)
                        ->get();
     
        
        $class_ids = []; // collect the class_ids from the wastes of supliers
        foreach ( $mains as $main ) {
            $class_ids[] = $main->waste->class_id; // from the relationship 
        }
        
        $classes_ = Class_::whereIn('id', $class_ids)->groupBy('name')->get(); // get all classes where belongs to the wastes of suppliers but no dublicates 

        return \Response::json(['classes_' => $classes_, ]);

    }

     // ajax 
     public function get_group($class_id ){
        
        Session::put('class_id', $class_id );

        $supplier_id = Session::get('supplier_id');
        $from = Session::get('tracking_from');
        $to = Session::get('tracking_to');

        $mains = Main::where('supplier_id',$supplier_id)
                     ->where('customer_id','!=',NULL)
                     //->whereBetween( 'created_at', [$from, $to] )
                     ->where('date','>=',$from)
                     ->where('date','<=',$to)
                     ->get();

        $group_ids = [];
        foreach ( $mains as $main ) {
            if ( $main->waste->class_id == $class_id) { 
            $group_ids[] = $main->waste->groups_id;  // // get all groups where belongs to the wastes of suppliers and with class_id that selected but no dublicates
            }
        }

        $groups = Group::whereIn('id', $group_ids)->groupBy('name')->get();

        return \Response::json(['groups' => $groups ]);	

    }

 // ajax 
    public function get_classification($group_id){
        
        Session::put('group_id', $group_id );
        $supplier_id = Session::get('supplier_id');
        $class_id = Session::get('class_id');
        $from = Session::get('tracking_from');
        $to = Session::get('tracking_to');

        $mains = Main::where('supplier_id',$supplier_id)
                        ->where('customer_id','!=',NULL)
                        //->whereBetween( 'created_at', [$from, $to] )
                        ->where('date','>=',$from)
                        ->where('date','<=',$to)
                        ->get();

        $classifications_id = [];
        foreach ( $mains as $main ) {
            if ( $main->waste->class_id == $class_id && $main->waste->groups_id == $group_id  ) { 
            $classifications_id[] = $main->waste->classifications_id;  // // get all groups where belongs to the wastes of suppliers and with class_id that selected but no dublicates
            }
        }

        $classifications = Classification::whereIn('id', $classifications_id)->groupBy('name')->get();

      // sleep(3);

        return \Response::json(['classifications' => $classifications  ]);	

    }




     // ajax 
     public function get_customers($classification_id){
        

        $supplier_id = Session::get('supplier_id');
        $class_id = Session::get('class_id');
        $group_id = Session::get('group_id');

        $from = Session::get('tracking_from');
        $to = Session::get('tracking_to');

        $mains = Main::where('supplier_id',$supplier_id)
                        ->where('customer_id','!=',NULL)
                        //->whereBetween( 'created_at', [$from, $to] )
                        ->where('date','>=',$from)
                        ->where('date','<=',$to)
                        ->get();

        $customers_id = [];
        foreach ( $mains as $main ) {
            if ( $main->waste->class_id == $class_id && $main->waste->groups_id == $group_id &&  $main->waste->classifications_id == $classification_id  ) { 
                $customers_id[] = $main->customer_id;
            }
        }
       
        $customers = Customer::whereIn('id', $customers_id)->groupBy('name')->get();


        return \Response::json(['customers'=>$customers ]);	

    }


    public function report_create_post(Request $request) {
    
        $transporter_id = $request ['transporter_id'];
        $supplier_id = $request ['supplier_id'];
        $customer_id = $request ['customer_id'];
        $dateFrom = $request ['from'];
        $dateTo = $request ['to'];
        $logo = $request ['logo'];

        $class_id = $request ['class_id'];
        $group_id = $request ['group_id'];
        $classification_id = $request ['classification_id'];

        $class = DB::table('class')->where('id', '=',$class_id)->first();
        $group = DB::table('groups')->where('id', '=',$group_id)->first();
        $classification = DB::table('classifications')->where('id', '=',$classification_id)->first();


        $transporter = DB::table('transporters')->where('id', '=',$transporter_id)->first();

        $supplier = DB::table('suppliers')->where('id', '=',$supplier_id)->first();

        $customer = DB::table('customers')->where('id', '=',$customer_id)->first();

        $wastes = DB::table('waste')->where( [ 
            ['class_id', '=',$class_id] , 
            ['groups_id', '=',$group_id] , 
            ['classifications_id', '=',$classification_id] , 
            ])->get();

        // get all wastes ids in one D array 
        $wastes_ids = [];
        foreach ( $wastes as $waste ) {
            $wastes_ids[] = $waste->id; 
        }


        /*$mains = Main::with('waste','vehicle', 'driver', 'physicalcondition','packingmethod')->whereIn('waste_id', $wastes_ids)->
        where( [ 
            ['supplier_id', '=',$supplier_id] , 
            ['customer_id', '=',$customer_id] ,
            ])->get();
            */

            $mains = Main::with('waste','vehicle', 'driver', 'physicalcondition','packingmethod')
               ->whereIn('waste_id', $wastes_ids)->
                where( [  ['supplier_id', '=',$supplier_id] , ['customer_id', '=',$customer_id] ])
                    ->where( 'date',">=", $dateFrom)
                    ->where('date',"<=", $dateTo )
                    ->orderBy('date','asc')
                    ->get();
        
        
        
        
        
        
        
         
         
         ///////////////// action /////////////////
        
        
        $subject = "Egwaste Tracking From ".$supplier->name. "To ".$customer->name. "date ==> ".$dateFrom ."  ".$dateTo;
          
        $action = "Tracking"  ;
        Actions::create ( [ 		
        'user' => Auth::user()->name ,
        'action' => $action,
        'comment' => $subject
        ] );
        ///////////////////
        
        
         return view('report.show', [
            'supplier'=>$supplier , 
            'transporter'=>$transporter ,
            'customer'=>$customer,
            'mains'=>$mains,
            'class'=>$class,
            'group'=>$group,
            'classification'=>$classification,
            'dateFrom'=>$dateFrom,
            'dateTo'=>$dateTo,
            'logo'=>$logo
        ]);
        
    }

    

public function createCreport(){
    $branches = Branch::get();
    return view('wastereport.create', ['branches'=>$branches]);
}
public function getWastes(Request $request)
    {
    $from = $request->input('from');
    $to = $request->input('to');
    $branch_id = $request->input('branch_id');
        try {
              

           $wastes = Main::with('waste')
            ->select('waste_id', DB::raw('SUM(quantity) as total_quantity'))
            ->where('branch_id',$branch_id)
            ->where('date','>=',$from)
            ->where('date','<=',$to)
            ->groupBy('waste_id')
            ->get();

//echo $wastes;

//return ;
                
            return response()->json([
                'success' => true,
                'wastes' => $wastes,
                
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'حدث خطأ: ' . $e->getMessage()
            ], 500);
        }
    }

public function CwasteReport(Request $request)
{

        $branch_id = $request->input('branch_id');
        $itemIds = $request->input('wastes', []);
        $from = $request->input('from');
        $to = $request->input('to');
        $branch = Branch::where('id', $branch_id)->first();
         $wastes = Main::with('waste')->select('waste_id', DB::raw('SUM(quantity) as total_quantity'))
            ->where('branch_id',$branch_id)
            ->whereIn('waste_id', $itemIds)
            ->where('date','>=',$from)
            ->where('date','<=',$to)
            ->groupBy('waste_id')
            ->get();

//return;
       return view('wastereport.show', [
        'wastes'=>$wastes,
        'dateFrom'=>$from,
        'dateTo'=>$to,
        'branch_name'=>$branch->name
    
    ]);



}


}
