Current File : /home/tradevaly/www/app/Http/Controllers/UserController.php
<?php

namespace App\Http\Controllers;
use Session;
use Auth;
use Hash;
use App\Models\Banner;
use App\Models\BuyOffer;
use App\Models\Message;
use App\Models\FeaturedRequest;
use App\Models\Package;
use App\Models\FeaturedProduct;
use App\Models\FeaturedCategory;
use App\Models\Product;
use App\Models\PackageFeature;
use App\Models\User;
use Illuminate\Support\Facades\Storage;
use App\Models\Tag;
use Intervention\Image\Facades\Image;
use App\Models\Category;
use App\Models\Company;
use App\Models\Country;
use App\Models\Thread;
use App\Models\Testimonial;
use App\Models\Tradeshows;
use App\Models\Certificate;
use App\Models\Pdf;
use App\Models\Award;
use Illuminate\Http\Request;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use DataTables;
use Mail;

class UserController extends Controller
{
    public function feature_product_create(Request $request){
        dd($request);
    }
     
     public function index(Request $request)
    {
            $query =  User::latest();
            if(!empty($request->user_type)){
                $query->where('type',$request->user_type);
            }
            if(!empty($request->free_pack)){
                $query->where('package_id',1);
            }
            if(!empty($request->premium_pack)){
                $query->where('package_id','!=',1);
            }
            if(!empty($request->country_id)){
                $query->where('country_id',$request->country_id);
            }
            
            if(!empty($request->category_id)){
                $query->where('category_id',$request->category_id);
            }
            
            $countries = Country::all();
            $categories = Category::latest()->where('parent_id', 0)->get();
            
            $data =  $query->get();
            
        
       if ($request->ajax()) {
            return Datatables::of($data)
             
                ->addIndexColumn()
                ->addColumn('pack', function($row){
                    $actionBtn = ' <img src="'.asset('storage/images/admin/package/'.$row->package->image).'"  width="138" height="44" class="lazy" style="">';
                    return $actionBtn;
                })
                ->addColumn('company', function($row){
                    if(isset($row->company))
                    return $row->company->name;
                })
                ->addColumn('phone', function($row){
                    if(isset($row->company))
                    return $row->company->phone;
                })
                ->addColumn('pack_start', function($row){
                    $pack_start = '<span class="badge alert-info">'. $row->created_at->format('d M Y H:i').' </span';
                    if($row->package_id != 1){
                   $pack_start =  $row->pack_start;
                    }
                    return $pack_start;
                })
                ->addColumn('pack_end', function($row){
                    $pack_end = '<span class="badge alert-info">Unlimited </span';
                    if($row->package_id != 1){
                   $pack_end =  $row->pack_end;
                    }
                    return $pack_end;
                })
                ->addColumn('action', function($row){
                    $actionBtn = '<a href="'.route('admin.users.view',$row->id).'"  class="btn btn-success" title="View Profle" style="color: #fff">
                      <i class="fas fa-eye"></i>
                    </a> <a href="'.route('admin.secrretlogin',$row->id).'"  class="btn btn-warning" title="Enter Login" style="color: #fff">
                      <i class="fas fa-key"></i>
                    </a>
                    <a href="'.route('admin.users.user_delete',$row->id).'"  class="btn btn-danger" title="Delete User" style="color: #fff">
                      <i class="fas fa-trash"></i>
                    </a>';
                    return $actionBtn;
                })
                ->rawColumns(['pack','pack_end','pack_start', 'action'])
                ->make(true);
        } 
        
       return view('backend.pages.users.index',compact('countries','categories'));
    }
     public function index_trash(Request $request)
    {
       if ($request->ajax()) {
            $data =  User::onlyTrashed()->latest()->get();
            return Datatables::of($data)
                ->addIndexColumn()
                ->addColumn('pack', function($row){
                    $actionBtn = ' <img src="'.asset('storage/images/admin/package/'.$row->package->image).'"  width="138" height="44" class="lazy" style="">';
                    return $actionBtn;
                })
                ->addColumn('company', function($row){
                    if(isset($row->company))
                    return $row->company->name;
                })
                ->addColumn('phone', function($row){
                    if(isset($row->company))
                    return $row->company->phone;
                })
                ->addColumn('action', function($row){
                    $actionBtn = '<a href="'.route('admin.trash.users.restore_trash',$row->id).'"  class="btn btn-success" title="View Profle" style="color: #fff">
                         <i class="fas fa-undo-alt"></i>
                    </a>
                    <a href=""  class="btn btn-success" title="Delete User" style="color: #fff">
                      <i class="fas fa-checked"></i>
                    </a>
                    <a href="'.route('admin.trash.users.delete_trash',$row->id).'"  class="btn btn-danger" title="Delete User" style="color: #fff">
                      <i class="fas fa-trash"></i>
                    </a>';
                    return $actionBtn;
                })
                ->rawColumns(['pack', 'action'])
                ->make(true);
        } 
        
       return view('backend.pages.users.trash_index');
    }
    public function user_delete($id){
            $user = User::find($id);
              $this->feature_delete_by_user($user->id);
              
              $this->buy_offer_delete_by_user($user->id);
              
              $this->messages_delete_by_user($user->id);
              $this->product_delete_by_user($user->id);
            $company = Company::where('user_id',$id)->first();
            if($company){
                $this->award_delete_by_company($company->id);
                $this->certificate_delete_by_company($company->id);
                $this->brochure_delete_by_company($company->id);
                $company->delete();
            }
          
            $user->delete();
            Toastr::error('User Deleted Successfully!', '', ['progressBar' => true, 'closeButton' => true, 'positionClass' => 'toast-top-right']);
            return back(); 
        }
    public function delete_trash($id){
            $user = User::onlyTrashed()->find($id);
              $this->trash_product_delete_by_user($user->id);

            if($user->image != 'image.jpg'){
                if (!Storage::disk('public')->exists('images/user/avatar/' . $user->image)) {
                        Storage::disk('public')->makeDirectory('images/user/avatar/' . $user->image);
                    }
            }
            $company = Company::onlyTrashed()->find($id);
            if($company){
                if($company->image != 'image.jpg'){
                    if(Storage::disk('public')->exists('images/user/avatar/'.$company->image))
                    {
                        Storage::disk('public')->delete('images/user/avatar/'.$company->image);
                    }
                }
                $company->forceDelete();
            }
          
            $user->forceDelete();
            Toastr::error('User Deleted Successfully!', '', ['progressBar' => true, 'closeButton' => true, 'positionClass' => 'toast-top-right']);
            return back(); 
        }
       public function restore_trash($id){
           $user_ctroller = new  \App\Http\Controllers\User\UserController();
           
            $user = User::onlyTrashed()->findOrFail($id)->restore();
              $this->trashed_product_restore_by_user($id);
            $company = Company::onlyTrashed()->find($id);
            if($company){
                $company->restore();
            }
            Toastr::success('User Restore Successfully!', '', ['progressBar' => true, 'closeButton' => true, 'positionClass' => 'toast-top-right']);
            return back(); 
        }
     public function country()
    {
       
    }
    // public function delete($id){
    //     $user = User::findorFail($id);
    //     $user->delete();
    //     Toastr::success('Success!','User Deleted!');
    //         return redirect()->route('admin.users,index');
    // }
    
    
    public function verified($id){
        $user = User::findorFail($id);
        $user->email_verified_at = Carbon::now();
        $user->save();
        Toastr::success('Success!','User Verified!');
            return redirect()->route('admin.users.index');
    }
    public function approved($id){
        $user = User::findorFail($id);
        $user->verified = 1;
        $user->save();
        Toastr::success('Success!','User Verified!');
            return redirect()->route('admin.users.index');
    }
    public function inbox(Request $request, $id)
    {
      $threads = \App\Models\Message::where('thread_id', $id)->orderBy('id', 'desc')->paginate(12); 
      return view('backend.pages.users.inbox', compact('threads'));
    }
     public function view(Request $request, $id)
    {
        if ($request->ajax()) {
      $threads = Thread::where('sender_id', $id)->orWhere('receiver_id', $id)->get();
       return Datatables::of($threads)
                ->addIndexColumn()
                ->addColumn('title', function($row){
                   return '<a href="'.route('admin.users.inbox', $row->id).'">'.$row->subject.'</a>';
                })
                ->addColumn('lastreply', function($row){
                    $msg = \App\Models\Message::where('thread_id', $row->id)->orderBy('created_at', 'desc')->first();
                    return $msg->sender->name;
                })
                ->addColumn('receiver', function($row){
                    return $row->receiver->name;
                })->addColumn('sender', function($row){
                    return $row->sender->name;
                })
                ->addColumn('time', function($row){
                    $msg = \App\Models\Message::where('thread_id', $row->id)->orderBy('created_at', 'desc')->first();
                    return $msg->sender->name;
                    return date('d F, Y h:i', strtotime($msg->created_at));
                })
                ->addColumn('view', function($row){
                   return '<a class="badge bg-info" href="'.route('admin.users.inbox', $row->id).'">View</a>';
                })
                ->rawColumns(['title', 'view'])
                ->make(true);
        }
      $user = User::findorFail($id);
      $company = Company::where('user_id', $id)->firstorFail();
      $products = Product::where('supplier_id', $id)->where('status',1)->take(8)->get();
      $offers = BuyOffer::where('buyer_id', $id)->take(8)->get();
      
        return view('backend.pages.users.view', compact('user', 'company', 'products', 'offers'));
      
    }
    
    public function updateProfile(Request $request, $id)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'string', 'email'],
            'password' => ['nullable', 'string', 'min:6'],
        ]);
        $user = User::find($id);
      

        
        $user->name = $request->get('name');
        $user->email = $request->get('email');
        if($request->filled('password')){
        $user->password = bcrypt($request->get('password'));
        }
       
        $user->update();
        if ($user) {
           Toastr::success('Success!','User Updated!');
            return redirect()->back();
        } else {
            Toastr::error('Failed!','User Update Failed!');
            return redirect()->back();
        }
    }
     public function about_us ()
    {
       
    }
    public function supplier(Request $request, $slug)
    {
        $data['user'] = User::where('username', $slug)->firstorFail();
        $product_limit = PackageFeature::where('package_id',$data['user']->package_id)->where('feature_id',7)->first()->value;
        $data['company'] = Company::where('user_id', $data['user']->id)->first();
        $data['products_3'] = Product::where('supplier_id', $data['user']->id)->where('status',1)->get()->take(3);
        $data['products'] = Product::where('supplier_id', $data['user']->id)->where('status',1)->latest()->take($product_limit)->paginate(9);
        $data['pdfs'] = Pdf::where('company_id', $data['company']->id)->get();
        $data['awards'] = Award::where('company_id', $data['company']->id)->get();
        $data['certificates'] = Certificate::where('company_id', $data['company']->id)->get();
        return view('frontend.pages.company_overview')->with($data);
    }
    
   
    
    public function profile(Request $request){
       if($request->isMethod('post')){
            $request->validate([
                'name' => 'required',
            ]);
            $id= Auth::id();
            $user= User::find($id);
            
            if($request->email != $user->email){
                 $request->validate([
                'email' => 'required|unique:users,email',
            ]);
            $user->email = $request->email;
            Mail::to($request->email)->send(new \App\Mail\MailChange($user));
            }
            if ($request->hasFile('image')) {

                $image = $request->file('image');
                $currentDate = Carbon::now()->toDateString();
                $imageName = $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension();
                if (!Storage::disk('public')->exists('images/user/avatar/' . $user->image)) {
                    Storage::disk('public')->makeDirectory('images/user/avatar/' . $user->image);
                }
                $userImage = Image::make($image)->resize(100, 100)->stream();
                Storage::disk('public')->put('images/user/avatar/' . $imageName, $userImage);
                $user->image = $imageName;
            }
                $user->name = $request->name;
                
                $user->save();
            Toastr::success('Info updated!');
             return redirect()->back();die;
        }
        return view('user.pages.profile');
    }
    public function password(Request $request){
        $id= Auth::user()->id;
        $user= User::find($id);
        if($request->isMethod('post')){
            $data=$request->all();
           if($data['old']==""){
            Toastr::error('Please enter current password!');
            return redirect()->back();die;
           }
          elseif(!Hash::check($data['old'],$user['password'])){
             Toastr::error('Current password is incorrect!');
             return redirect()->back();die;
           } elseif(!Hash::check($data['new'],$user['confirm'])){
             Toastr::error('Password do not matcht!');
             return redirect()->back();die;
           }
           else{
             $user->update(['password'=>Hash::make($data['confirm'])]);
             Toastr::success('Password updated!');
             return redirect()->back();;
           }
        }
        return view('user.pages.reset')->with(compact('user'));
    }
    public function password_admin(Request $request){
        $id= Auth::user()->id;
        $user= User::find($id);
        if($request->isMethod('post')){
            $data=$request->all();
           if($data['old']==""){
            Toastr::error('Please enter current password!');
            return redirect()->back();die;
           }
          elseif(!Hash::check($data['old'],$user['password'])){
             Toastr::error('Current password is incorrect!');
             return redirect()->back();die;
           } elseif(!Hash::check($data['new'],$user['confirm'])){
             Toastr::error('Password do not matcht!');
             return redirect()->back();die;
           }
           else{
             $user->update(['password'=>Hash::make($data['confirm'])]);
             Toastr::success('Password updated!');
             return redirect()->back();;
           }
        }
        return view('user.pages.reset')->with(compact('user'));
    }
    public function product_delete_by_user($id){
       $products =  Product::where('supplier_id',$id)->get();
       if($products){
            foreach($products as $product){
              $product->delete();
          }
       }
    }
    
    public function trash_product_delete_by_user($id){
        $user_ctroller = new  \App\Http\Controllers\User\UserController();
       $products =  Product::where('supplier_id',$id)->get();
       if($products){
            foreach($products as $product){
                  $user_ctroller->delete_trash_product($product);
          }
       }
       return true;
    }
    
    public function trashed_product_restore_by_user($id){
        $user_ctroller = new  \App\Http\Controllers\User\UserController();
       $products =  Product::onlyTrashed()->where('supplier_id',$id)->get();
       if($products){
            foreach($products as $product){
                $category = Category::find($product->child_id);
                $user = User::find($product->supplier_id);
                if(!empty($category) && !empty($user)){
                  $user_ctroller->restore_trash_product($product);
                }
          }
       }
       return true;
    }
    
    
    
    public function feature_delete_by_user($id){
      
       $feature_requests =  FeaturedRequest::where('user_id',$id)->get();
       if($feature_requests){
         foreach($feature_requests as $feature_request){
           $feature_request->delete();
       }  
       }
        $feature_products = FeaturedProduct::where('user_id', $id)->latest()->get();
        foreach($feature_products as $feature_product){
            $feature_product->delete();
        }
    }
    public function messages_delete_by_user($id){
       $messages =  Message::where('sender_id',$id)->orWhere('receiver_id',$id)->get();
       if(!empty($messages)){
           foreach($messages as $message){
               $message->delete();
           }
       }
    }
    public function buy_offer_delete_by_user($id){
       $buy_offers =  BuyOffer::where('buyer_id',$id)->orWhere('seller_id',$id)->get();
       if($buy_offers){
           foreach($buy_offers as $buy_offer){
               $buy_offer->delete();
           }
       }
    }
    public function award_delete_by_company($id){
       $awards =  Award::where('company_id',$id)->get();
       if($awards){
           foreach($awards as $award){
                    if(Storage::disk('public')->exists('images/user/pdf/'.$award->image))
                     {
                       Storage::disk('public')->delete('images/user/pdf/'.$award->image);
                     }
            
               $award->delete();
           }
       }
    }
    public function brochure_delete_by_company($id){
       $brochures =  Pdf::where('company_id',$id)->get();
       if($brochures){
           foreach($brochures as $brochure){
                    if(Storage::disk('public')->exists('images/user/pdf/'.$brochure->image))
                     {
                       Storage::disk('public')->delete('images/user/pdf/'.$brochure->image);
                     }
            
               $brochure->delete();
           }
       }
    }
    public function certificate_delete_by_company($id){
       $certificates =  Certificate::where('company_id',$id)->get();
       if($certificates){
           foreach($certificates as $certificate){
                    if(Storage::disk('public')->exists('images/user/certificate/'.$certificate->image))
                     {
                       Storage::disk('public')->delete('images/user/certificate/'.$certificate->image);
                     }
            
               $certificate->delete();
           }
       }
    }
}