<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use  App\Activity;
use  App\Classification;
use  App\City;
use  App\RecycleMethod;
use  App\Supplier;
use  App\Waste;
use  App\User;
use Carbon\Carbon;
use Auth; 
use App\Actions;

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

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Supplier Controller 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public function supplier_show()
{
    $suppliers = Supplier::with('city')->get();
    return view('supplier.show' , ['suppliers' => $suppliers]);
}
public function supplier_create_get()
{
    $citys = City::get();
  return view('supplier.create', ['citys' => $citys]);
}

public function waste_supplier_create_get()
{
    $suppliers = Supplier::get();
    $wastes =  Waste::get();
  return view('supplier.wastesuppliercreate', ['suppliers' => $suppliers , 'wastes' =>$wastes]);
}

public function waste_supplier_create(Request $request) {
    
    $activity = DB::table('supplier_waste')->insert ( [ 		
            'waste_id' => $request ['waste_id'],
            'supplier_id' => $request ['supplier_id'],
    ] );    

    session()->flash('message', 'New Waste Supplier Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/waste_supplier/create" );
}


public function supplier_create(Request $request) {
    
    $supplier = Supplier::create ( [ 
            'name' => $request ['name'],
            'address' => $request ['address'],
            'phone' => $request ['phone'],
            'fax' => $request ['fax'],
            'email' => $request ['email'],
            'environmental_response' => $request ['environmental_response'],
            'resp_position' => $request ['resp_position'],
            'resp_phone' => $request ['resp_phone'],
            'resp_email' => $request ['resp_email'],
            'commertial_registration_no' => $request ['commertial_registration_no'],
            'tax_card_no' => $request ['tax_card_no'],
            'operating_licence_no' => $request ['operating_licence_no'],
            'industrial_registration_no' => $request ['industrial_registration_no'],
            'industrial_city_id' => $request ['industrial_city_id']
    ] );    
     
    
    if($request->hasFile('image')){
        $image_name = $supplier->id . '.' . $request->file ( 'image' )->getClientOriginalExtension ();
        $request->file ( 'image' )->move ( public_path () . '/uploads/suppliers/', $image_name );
        //Save logo
        $supplier->logo =  '/uploads/suppliers/'. $image_name;
    }
    $supplier->update();



    session()->flash('message', 'New Supplier Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/supplier/index" );
}

public function supplier_edit_get($supplier_id){
     
    $supplier = DB::table('suppliers')->where('id', '=',$supplier_id)->first();
    $citys = City::get();

    return view('supplier.edit',[
            'supplier' => $supplier, 'citys' => $citys
    ]);
}
public function supplier_edit_post(Request $request){
    $supplier_id = $request ['supplier_id'];
    $supplier_row = DB::table('suppliers')->where('id', '=',$supplier_id)->first();

    $name = $request ['name'];
    $address = $request ['address'];
    $phone = $request ['phone'];
    $fax = $request ['fax'];
    $email = $request ['email'];
    $environmental_response = $request ['environmental_response'];
    $resp_position = $request ['resp_position'];
    $resp_phone = $request ['resp_phone'];
    $resp_email = $request ['resp_email'];
    $commertial_registration_no = $request ['commertial_registration_no'];
    $tax_card_no = $request ['tax_card_no'];
    $operating_licence_no = $request ['operating_licence_no'];
    $industrial_registration_no = $request ['industrial_registration_no'];
    $industrial_city_id = $request ['industrial_city_id'];

    
    $logo = $supplier_row->logo;     
    if($request->hasFile('image')){
        $image_name = $supplier_id . '.' . $request->file ( 'image' )->getClientOriginalExtension ();
        $request->file ( 'image' )->move ( public_path () . '/uploads/suppliers/', $image_name );
        $logo =  '/uploads/suppliers/'. $image_name;
    }
    
    
    DB::table('suppliers')
        ->where('id', $supplier_id)
        ->update([
            'name' => $name,
            'address' => $address,
            'phone' => $phone,
            'fax' => $fax,
            'email' => $email,
            'environmental_response' => $environmental_response,
            'resp_position' => $resp_position,
            'resp_phone' => $resp_phone,
            'resp_email' => $resp_email,
            'commertial_registration_no' => $commertial_registration_no,
            'tax_card_no' => $tax_card_no,
            'operating_licence_no' => $operating_licence_no,
            'industrial_registration_no' => $industrial_registration_no,
            'industrial_city_id' => $industrial_city_id,
            'logo'=>$logo,
         'updated_at' => Carbon::now()]);


    session()->flash('message', 'Supplier Updated successfully');
    session()->flash('type', 'success');

    return redirect ( "/supplier/edit/$supplier_id" );
}
public function supplier_delete($supplier_id){
        
        $supplier = Supplier::find($supplier_id);
        $supplier->delete();
        return redirect ( "/supplier/index");
    }
   
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Industrial City
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function city_show()
{
    $citys = City::get();
    return view('city.show' , ['citys' => $citys]);
}
public function city_create_get()
{
    return view('city.create');
}
public function city_create(Request $request) {
    
    $city = City::create ( [ 		
            'name' => $request ['name'],
            'addres'=>$request ['addres']
    ] );    
    session()->flash('message', 'New City Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/city/index" );
}

public function city_edit_get($city_id){
    $city = DB::table('industrial_city')->where('id', '=',$city_id)->first();
    return view('city.edit',[
                            'city' => $city
                            ]);
}
public function city_edit_post(Request $request){
    $city_id = $request ['city_id'];
    $city_name = $request ['name'];
    $city_addres = $request ['addres'];

    DB::table('industrial_city')
        ->where('id', $city_id)
        ->update(['name' => $city_name,'addres' => $city_addres, 'updated_at' => Carbon::now()]);
            
    session()->flash('message', 'Industerial City Updated successfully');
    session()->flash('type', 'success');

    return redirect ( "/city/edit/$city_id" );
}
public function city_delete($city_id){
        
        $city = City::find($city_id);
        $city->delete();
        return redirect ( "/city/index");
    }    


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// User
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function user_show()
{
    $users = User::with('supplier')
    ->where('email','!=','a.helmygreenova@egaccounting.org')->get();
    
       ///////////////// action /////////////////

        $subject = "Show All Users  ";
        $action = "User Show"  ;
        Actions::create ( [ 		
        'user' => Auth::user()->name ,
        'action' => $action,
        'comment' => $subject
        ] );
        ///////////////////


    return view('user.show' , ['users' => $users]);
}
public function user_create_get()
{
    return view('user.create');
}
public function user_create(Request $request) {
    
    $is_admin = NULL;
    $is_supervisor = NULL;
    $show = 0;
    $create = 0;
    $edit = 0;
    $delete = 0;
    $approve = 0;

    $check_admin_supervisor = $request ['check_admin_supervisor'];
    
    if ($request ['password'] != $request ['confirmpassword']){
        session()->flash('message', 'Password and Confirm password no matched');
        session()->flash('type', 'error');
        return back()->withInput();
    }
    if (  $request ['show'] ){
        $show = 1;
    } 
    if (  $request ['create'] ){
        $create = 1;
    } 
    if (  $request ['edit'] ){
        $edit = 1;
    } 
    if (  $request ['delete'] ){
        $delete = 1;
    } 
    if (  $request ['approve'] ){
        $approve = 1;
    } 

    if ( $check_admin_supervisor == "admin"){
        $is_admin = 1;
        $is_supervisor = NULL;
    }
    else {
        $is_admin = NULL;
        $is_supervisor = 1;
    }


    $user = User::create ( [ 		
        'name' => $request ['name'],
        'email' => $request ['email'],
        'password' => bcrypt($request ['password']),
        'is_admin'=> $is_admin ,
        'is_supervisor' => $is_supervisor,
        'show_'=>$show,
        'create_'=>$create,
        'edit_'=>$edit,
        'delete_'=>$delete,
        'approve_'=>$approve,
        'is_superadmin' =>NULL,
        'is_supplier'=> NULL
    ] );    
    session()->flash('message', 'New User/Supplier Added Successfully');
    session()->flash('type', 'success');
    
    
      ///////////////// action /////////////////
        
       $action = "New User Created " ;
       Actions::create ( [ 		
        'user' => Auth::user()->name ,
        'action' => $action,
        'comment' => " $user "
            ] );
        /////////////////////////////////
        
        
    return redirect ( "/user/index" );
    
}

public function user_edit_get($user_id){
    $user = DB::table('users')->where('id', '=',$user_id)->first();
    return view('user.edit',[
                            'user' => $user
                            ]);
}
public function user_edit_post(Request $request){

    $is_admin = NULL;
    $is_supervisor = NULL;
    $show = 0;
    $create = 0;
    $edit = 0;
    $delete = 0;
    $approve = 0;
    $with_password = false;
    $check_admin_supervisor = $request ['check_admin_supervisor'];
    
    if ($request ['password'] && $request ['confirmpassword']){
        $with_password = true;
    if ($request ['password'] != $request ['confirmpassword']){
        session()->flash('message', 'Password and Confirm password no matched');
        session()->flash('type', 'error');
        return back()->withInput();
    }

    }
    if (  $request ['show'] ){
        $show = 1;
    } 
    if (  $request ['create'] ){
        $create = 1;
    } 
    if (  $request ['edit'] ){
        $edit = 1;
    } 
    if (  $request ['delete'] ){
        $delete = 1;
    } 
    if (  $request ['approve'] ){
        $approve = 1;
    } 

    if ( $check_admin_supervisor == "admin"){
        $is_admin = 1;
        $is_supervisor = NULL;
    }
    else {
        $is_admin = NULL;
        $is_supervisor = 1;
    }



    $user_id = $request ['user_id'];
    $user_name = $request ['name'];
    $user_email = $request ['email'];

    $old_user= User::where('id',$user_id)->first();


    if ($with_password ) {
        DB::table('users')
        ->where('id', $user_id)
        ->update([
            'name' => $user_name,
            'email' => $user_email, 
            'is_admin'=> $is_admin ,
            'is_supervisor' => $is_supervisor,
            'show_'=>$show,
            'create_'=>$create,
            'edit_'=>$edit,
            'delete_'=>$delete,
            'approve_'=>$approve,
            'is_superadmin' =>NULL,
            'is_supplier'=> NULL,
            'password' => bcrypt($request ['password']) ,
            'updated_at' => Carbon::now()
        ]);
    } else {
    DB::table('users')
        ->where('id', $user_id)
        ->update([
            'name' => $user_name,
            'email' => $user_email, 
            'is_admin'=> $is_admin ,
            'is_supervisor' => $is_supervisor,
            'show_'=>$show,
            'create_'=>$create,
            'edit_'=>$edit,
            'delete_'=>$delete,
            'approve_'=>$approve,
            'is_superadmin' =>NULL,
            'is_supplier'=> NULL,
            //'password' => bcrypt($request ['password']) ,
            'updated_at' => Carbon::now()
        ]);
    }
    session()->flash('message', 'User Updated successfully');
    session()->flash('type', 'success');



  ///////////////// action /////////////////
        $new_user= User::where('id',$user_id)->first();
       $action = "Edit User $user_id " ;
       Actions::create ( [ 		
        'user' => Auth::user()->name ,
        'action' => $action,
        'comment' => " new ==> $new_user ==old===>  $old_user "
            ] );
        /////////////////////////////////
        

    return redirect ( "/user/edit/$user_id" );
}
public function user_delete($user_id){
        
        $user = User::find($user_id);
        $user->delete();
        
         ///////////////// action /////////////////
        
       $action = "Delete User $user_id " ;
       Actions::create ( [ 		
        'user' => Auth::user()->name ,
        'action' => $action,
        'comment' => " Delete user $user_id "
            ] );
        /////////////////////////////////
        
        
        return redirect ( "/user/index");
    }    

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Supplier Credentials
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public function credential_create_get()
{   
    $users_ids = User::select('is_supplier')->where( 'is_supplier' , '!=' , NULL)->get();
    $data = []; 
    foreach ($users_ids as $user_id) {
                $data[] = $user_id->is_supplier;
            }
    $suppliers = DB::table('suppliers')->select('id','name')->whereNotIn('id', $data)->get();
    return view('user.createsuppliercredential', ['suppliers'=>$suppliers]);
}
public function credential_create(Request $request) {
    
    if ($request ['password'] != $request ['confirmpassword']){
        session()->flash('message', 'Password and Confirm password no matched');
        session()->flash('type', 'error');
        return back()->withInput();
    }

    $user = User::create ( [ 		
        'name' => $request ['name'],
        'email' => $request ['email'],
        'password' => bcrypt($request ['password']),
        'is_supplier'=> $request ['supplier_id']
    ] );    
    session()->flash('message', 'New Supplier Credentials Added Successfully');
    session()->flash('type', 'success');
    
    ///////////////// action /////////////////
        $sname = $request ['name'];
        $subject = "Create New Supplier  ".$sname;
        $action = "Supplier Create "  ;
        Actions::create ( [ 		
        'user' => Auth::user()->name ,
        'action' => $action,
        'comment' => $subject
        ] );
        ///////////////////
        
        
    return redirect ( "/user/index" );
}

public function credential_edit_get($user_id){
    $suppliers = Supplier::get();
   // $user = DB::table('users')->where('id', '=',$user_id)->first();
    $user = User::with('supplier')->where('id',$user_id)->first();

    return view('user.editsuppliercredential',[
                            'user' => $user,
                            'suppliers'=>$suppliers
                            ]);
}

public function credential_edit_post(Request $request){
    $user_id = $request ['user_id'];
    $user_name = $request ['name'];
    $user_email = $request ['email'];
    $is_supplier= $request ['supplier_id'];
    $with_password = false;

    if ($request ['password'] && $request ['confirmpassword']){
        $with_password = true;
    if ($request ['password'] != $request ['confirmpassword']){
        session()->flash('message', 'Password and Confirm password no matched');
        session()->flash('type', 'error');
        return back()->withInput();
    }
    }
    if ( $with_password  ) {
    DB::table('users')
        ->where('id', $user_id)
        ->update([
            'name' => $user_name,
            'email' => $user_email, 
            'password' => bcrypt($request ['password']) ,
            'is_supplier'=> $is_supplier,
            'updated_at' => Carbon::now()
        ]);
    }else {
        DB::table('users')
        ->where('id', $user_id)
        ->update([
            'name' => $user_name,
            'email' => $user_email, 
            //'password' => bcrypt($request ['password']) ,
            'is_supplier'=> $is_supplier,
            'updated_at' => Carbon::now()
        ]);
    }

    session()->flash('message', 'Supplier Credentials Updated successfully');
    session()->flash('type', 'success');

    return redirect ( "/credential/edit/$user_id" );
}
    
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Activities
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public function activity_show()
{
    $activitys = Activity::get();
    return view('activity.show' , ['activitys' => $activitys]);
}
public function activity_create_get()
{
    return view('activity.create');
}

public function activity_supplier_create_get()
{
    $suppliers = Supplier::get();
    $activitys = Activity::get();
    return view('activity.addactivitysupplier' , ['activitys' => $activitys , 'suppliers' => $suppliers ] );
}

public function activity_create(Request $request) {
    
    $activity = Activity::create ( [ 		
            'name' => $request ['name'],
    ] );    
    session()->flash('message', 'New Activity Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/activity/index" );
}

public function activity_supplier_create(Request $request) {
    
    $activity = DB::table('activity_supplier')->insert ( [ 		
            'activity_id' => $request ['activity_id'],
            'supplier_id' => $request ['supplier_id'],
    ] );    

    session()->flash('message', 'New Activity Supplier Added Successfully');
    session()->flash('type', 'success');
    return redirect ( "/activity_supplier/create" );
}


public function activity_edit_get($activity_id){
    $activity = DB::table('activites')->where('id', '=',$activity_id)->first();
    return view('activity.edit',[
                            'activity' => $activity
                            ]);
}
public function activity_edit_post(Request $request){
    $activity_id = $request ['activity_id'];
    $activity_name = $request ['name'];
    DB::table('activites')
        ->where('id', $activity_id)
        ->update(['name' => $activity_name, 'updated_at' => Carbon::now()]);
            
    session()->flash('message', 'Activity Updated successfully');
    session()->flash('type', 'success');

    return redirect ( "/activity/edit/$activity_id" );
}
public function activity_delete($activity_id){
        
        $activity = Activity::find($activity_id);
        $activity->delete();
        return redirect ( "/activity/index");
    }
    
    
    public function suppervisor_supplier_list_get ($user_id) {
    $suppervisor = DB::table('users')->where('id', '=',$user_id)->first();
    $suppliers = Supplier::select(['id' , 'name'])->get();
    $suppervisor_suplier_list =  DB::table('supervisor_supplier') ->where('user_id', $user_id)->get();
    
    foreach ( $suppliers as $supplier ) {
        for ( $i = 0 ;$i < sizeof ($suppervisor_suplier_list); $i++){
            if ( $supplier->id ==  $suppervisor_suplier_list[$i]->supplier_id ){
              $supplier["check"] = "yes";
            }
        }
    }
    
    
    return view('user.suppervisor_suplier',[
        'suppliers' => $suppliers,
        'suppervisor'=>$suppervisor
        ]);
        
}



public function suppervisor_supplier_list_edit (Request $request) {
        $user_id = $request["user_id"];
        $json = json_encode($request->except('_token' , 'user_id'), JSON_NUMERIC_CHECK );
        $array = json_decode($json, TRUE);
        $suppervisor_suplier_list =  DB::table('supervisor_supplier') ->where('user_id', $user_id)->get();
        $suplier_list = [];
        for ( $i=0 ; $i< sizeof ($suppervisor_suplier_list); $i++){
            $suplier_list[]= $suppervisor_suplier_list[$i]->supplier_id;
        }

         
        // add supplier to table
        foreach ( $array as $supplier_id  ) {
            if (!in_array($supplier_id, $suplier_list)){
                DB::table('supervisor_supplier')->insert(['user_id' => $user_id, 'supplier_id' =>$supplier_id ]);
            }
        }


        // remove supplier from table
        foreach ( $suplier_list as $supplier_id  ) {
            if (!in_array($supplier_id, $array)){
                DB::table('supervisor_supplier')->where('supplier_id', $supplier_id)->delete();
            } 
        }
    
        session()->flash('message', 'List Of Suppliers Updated successfully');
        session()->flash('type', 'success');
        return redirect ( "/suppervisor_supplier_list/edit/$user_id" );
    
        
}



}
