<?php namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Session;
use Auth;
use Illuminate\Support\Facades\Redirect;
use App\User;
use Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Roles;
use App\Industry;
use App\Categories;
use App\Currency;
use App\CurrencyUnits;
use App\GrowthPerYear;
use Hash;
use App\Page;
use App\Content;
use App\Profile;
use App\Contact;
use App\Legal;
use Mail;
use App\BusinessYears;
use App\Funding;
use App\Import_contacts;
use App\Subscribe;
use App\Subscribe_mails;

class AdminController extends Controller {

//    private $current_profile_id;
  /*
  |--------------------------------------------------------------------------
  | User Controller
  |--------------------------------------------------------------------------
  |
  | This controller renders your application's users functionality
  | like signup, login, forgot password.
  |
  */
        public function __construct()
  {
                //session()->regenerate();
				if(Auth::user()):
                   if(Auth::user()->user_type!='admin'):
                 Redirect::to('home')->send();
                   endif; 
                endif;
                
                
  } 
  /**
   * Create a new controller instance.
   *
   * @return void
   */
    
  /**
     * Show the application login to the user.
     *
     * @return Response
     */
    public function index()
    {
      $pictures='success';
      return View('admin.login')->with('data',$pictures);
    }
    public function dashboard()
    { 
      // Dashboard data
      $total_users = User::getTotalUsers();
      $this_month_users = User::getThisMonthUsers();
      $users_monthwise = User::getMonthwiseTotal();
      $total_talents = Profile::getTotalByType('T');
      $total_orgs = Profile::getTotalByType('O');

      // Monthly Totals
      $monthly_talents = Profile::getMonthwiseTotal('T');
      $monthly_orgs = Profile::getMonthwiseTotal('O');

      // Pie Chart data
     // $total_users = User::all()->count();
      $total_returning = User::getTotalReturning();
      $total_business = Profile::getStatus('Business');
      $total_finance = Profile::getStatus('Finance');
      $total_newuser = User::getTotalNewUsers();
      $percent_returning = ( $total_business / $total_orgs ) * 100;
      $percent_new = ( $total_finance / $total_orgs ) * 100;
      $total=$total_talents+$total_orgs;
      $percent_invalid = ( $total_orgs / $total ) * 100;

      return View('admin.dashboard')->with([
        'total_users'       => $total_users,
        'total_talents'     => $total_talents,
        'users_monthwise'   => $users_monthwise,
        'total_orgs'        => $total_orgs,
        'monthly_talents'   => $monthly_talents,
        'monthly_orgs'      => $monthly_orgs,
        'total_users'       => $total_users,
        'total_returning'   => $total_returning,
        'total_newuser'     => $total_newuser,
        'percent_returning' => round($percent_returning, 2),
        'percent_new'       => round($percent_new, 2),
        'percent_invalid'   => round($percent_invalid, 2),
        'this_month_users'  => $this_month_users
      ]);
    }
                
                  public function users_view()
                { 
                   $allusers=User::where('user_type', '=', 'user')->where('deleted', '=', '0')->distinct('username')->orderBy('id', 'desc')->get();
                  return View('admin.users')->with('data',$allusers);
                }
               
               
               public function user_delete($del_id)
                {
                  if(is_numeric($del_id)):
                   $pic_id=User::find($del_id)->get();
                   
                   if(isset($pic_id[0])):

                                      $delete = User::where('id', '=', $del_id)->update(array('deleted' => 1));
                        
                   if($delete):
                      
                          return Redirect::back()->with('succ_msg',"User Deleted Successfully");   
                      else:
                         return Redirect::back()->with('error_msg',"Invalid Request");    
                      endif;
                      
                   else:
                      return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;

                    
                   else:
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                   endif;
                }
                
                
                public function user_edit($user_id)
                {
                     if(is_numeric($user_id)):
                         $user_data=User::getUserinfo($user_id);
                     
                            if(isset($user_data[0])):
                             $business_years = BusinessYears::getAllYears();  
                             return View('admin.user_edit')->with('user_info',$user_data)->with('business_years',$business_years);
                            else:
                            return Redirect::back()->with('error_msg',"Invalid Request");   
                            endif;
                     else:    
                     return Redirect::back()->with('error_msg',"Invalid Request");       
                     endif;
    
      
                }
                public function user_update(Request $request)
                {
                    if($request->input('Update')=='Store')
                             { 
                         if($request->input('selected_profile')=='T')
                            {
                                 $rule  =  array(
                                 'name' => 'required|max:255',
                                 'city' => 'required',
                                 'dob' => 'required',
                                 'gender' => 'required',
                                  );
                            }
                             if($request->input('selected_profile')=='O')
                            {
                                 $rule  =  array(
                                 'name' => 'required|max:255',
                                 'city' => 'required',
                                 'years_in_business' => 'required',
                                  );
                            }
                                
                                 $user_id=Input::get('user_id');
                                 $profile_id=Input::get('profile_id');
                                 $validator = Validator::make(Input::all(),$rule);
                                 if ($validator->fails())
                                  {
                                     return Redirect::to('admin/user_edit/'.$user_id)
                                         ->withErrors($validator->messages());
                                  }
                                 else
                                  {
                                     if(Input::get('dob')): 
                                          $dob=  date('Y-m-d',  strtotime(Input::get('dob')));
                                     else:
                                          $dob="";
                                     endif;
                                     if(Input::get('gender')):
                                         $gender=Input::get('gender');
                                     else:
                                         $gender="";
                                     endif;
                                     if(Input::get('years_in_business')): 
                                          $business_years=  Input::get('years_in_business');
                                     else:
                                          $business_years="";
                                     endif;
                                     
                                        
                                     User::where('id', '=', $user_id)->update(array('name' => trim(Input::get('name')),'city' => trim(Input::get('city')),'dob' => trim($dob),'gender' => trim($gender),'years_in_business'=> trim($business_years)));
                                     Funding::where('profile_id', '=', $profile_id)->update(array('years_in_business' => trim($business_years)));
                                  }

                                 
                             }  
                              $allusers=User::where('user_type', '=', 'user')->where('deleted', '=', '0')->distinct('username')->orderBy('id', 'desc')->get();
                                   return Redirect::to('admin/users')->with('data',$allusers)->with('succ_msg',"User Updated Successfully");
                }
                
                 public function roles_view()
                {
                 $allroles= Roles::orderBy('id', 'DESC')->get();
                  return View('admin.roles')->with('data',$allroles);
                }
                
                public function roles_delete($del_id)
                {
                 if(is_numeric($del_id)):
                   $pic_id=Roles::find($del_id)->get();
                   
                   if(isset($pic_id[0])):

                                      $delete = Roles::where('id', '=', $del_id)->delete();
                        
                   if($delete):
                      
                          return Redirect::back()->with('succ_msg',"Role Deleted Successfully");   
                      else:
                         return Redirect::back()->with('error_msg',"Invalid Request");    
                      endif;
                      
                   else:
                      return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;

                    
                   else:
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                   endif;
                }
                 public function role_edit($user_id)
                {
                     $allroles= Roles::orderBy('id', 'DESC')->get();
                
                     if(is_numeric($user_id)):
                         $user_data=Roles::where('id','=',$user_id)->get();
                     
                            if(isset($user_data[0])):
                               // print_r($user_data[0]);exit;
                             return View('admin.roles')->with('user_info',$user_data)->with('data',$allroles);
                            else:
                            return Redirect::back()->with('error_msg',"Invalid Request");   
                            endif;
                     else:    
                     return Redirect::back()->with('error_msg',"Invalid Request");    
                     endif;
    
      
                }
                 public function role_update(Request $request)
                {
                    if($request->input('Update')=='Store')
                             {  
                                 $rule  =  array(
                                 'name' => 'required',
                                  );
                                 $role_id=Input::get('role_id');
                                 $validator = Validator::make(Input::all(),$rule);
                                 if ($validator->fails())
                                  {
                                     return Redirect::to('admin/role_edit/'.$role_id)
                                         ->withErrors($validator->messages());
                                  }
                                 else
                                  {
                                      $delete = Roles::where('id', '=', $role_id)->update(array('name' => trim(Input::get('name'))));
                                  }

                                 
                             }  
                              $allroles= Roles::orderBy('id', 'DESC')->get();
                               return Redirect::to('admin/roles')->with('data',$allroles)->with('succ_msg',"Role Updated Successfully");
                        
                }
                public function roles_add(Request $request)
                {
                      if($request->input('Insert')=='Store')
                        {  
                            $rule  =  array(
                            'name' => 'required',
                             );
                            $validator = Validator::make(Input::all(),$rule);
                            if ($validator->fails())
                             {
                                 return Redirect::to('admin/roles')
                                                 ->withErrors($validator->messages());
                             }
                            else
                             {
                                $find_out=Roles::where('name', '=', Input::get('name'))->first();
                                
                                if (is_null($find_out)) 
                                {
                                     $object= Roles::create([
                                            'name' => trim(Input::get('name')),
                                           ]);
                                } 
                               else 
                                {
                                 return Redirect::back()->with('error_msg',"Given Role Have Already Exists");    
                                }
                                
                                
                             }
                        } 
                        $allroles= Roles::orderBy('id', 'DESC')->get();
                               return Redirect::to('admin/roles')->with('data',$allroles)->with('succ_msg',"Role Added Successfully");
                }
                 public function contact_del($del_id)
                {
                  
                 if(is_numeric($del_id)):
                   $pic_id= Contact::find($del_id)->get();
                   
                   if(isset($pic_id[0])):

                                      $delete = Contact::where('id', '=', $del_id)->delete();
                        
                   if($delete):
                      
                          return Redirect::back()->with('succ_msg',"Contact Deleted Successfully");   
                      else:
                         return Redirect::back()->with('error_msg',"Invalid Request");    
                      endif;
                      
                   else:
                      return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;

                    
                   else:
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                   endif;  
                }
                 public function contact()
                {
                 $allroles= Contact::orderBy('id', 'DESC')->get();
                  return View('admin.contact')->with('data',$allroles);
                }
                  public function industry_view()
                {
                 $allroles= Industry::orderBy('id', 'DESC')->get();
                  return View('admin.industrys')->with('data',$allroles);
                }
                  public function industry_delete($del_id)
                {
                 if(is_numeric($del_id)):
                   $pic_id= Industry::find($del_id)->get();
                   
                   if(isset($pic_id[0])):

                                      $delete = Industry::where('id', '=', $del_id)->delete();
                        
                   if($delete):
                      
                          return Redirect::back()->with('succ_msg',"Industry Deleted Successfully");   
                      else:
                         return Redirect::back()->with('error_msg',"Invalid Request");    
                      endif;
                      
                   else:
                      return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;

                    
                   else:
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                   endif;
                }
                 public function industry_edit($user_id)
                {
                     
                       $allroles= Industry::orderBy('id', 'DESC')->get();
               
                     if(is_numeric($user_id)):
                         $user_data=Industry::where('id','=',$user_id)->get();
                     
                            if(isset($user_data[0])):
                               // print_r($user_data[0]);exit;
                             return View('admin.industrys')->with('user_info',$user_data)->with('data',$allroles);
                            else:
                            return Redirect::back()->with('error_msg',"Invalid Request");   
                            endif;
                     else:    
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                     endif;
    
      
                }
                 public function industry_update(Request $request)
                {
                    if($request->input('Update')=='Store')
                             {  
                                 $rule  =  array(
                                 'name' => 'required',
                                  );
                                 $role_id=Input::get('role_id');
                                 $validator = Validator::make(Input::all(),$rule);
                                 if ($validator->fails())
                                  {
                                     return Redirect::to('admin/industry_edit/'.$role_id)
                                         ->withErrors($validator->messages());
                                  }
                                 else
                                  {
                                      $delete = Industry::where('id', '=', $role_id)->update(array('name' => trim(Input::get('name'))));
                                  }

                                 
                             }  
                              $allroles= Industry::orderBy('id', 'DESC')->get();
                               return Redirect::to('admin/industry')->with('data',$allroles)->with('succ_msg',"Industry Updated Successfully");
                        
                }
                
                   public function industry_add(Request $request)
                {
                      if($request->input('Insert')=='Store')
                        {  
                            $rule  =  array(
                            'name' => 'required',
                             );
                            $validator = Validator::make(Input::all(),$rule);
                            if ($validator->fails())
                             {
                                 return Redirect::to('admin/industry')
                                                 ->withErrors($validator->messages());
                             }
                            else
                             {
                               $find_out=Industry::where('name', '=', Input::get('name'))->first();
                                
                                if (is_null($find_out)) 
                                {
                                     $object= Industry::create([
                                            'name' => trim(Input::get('name')),
                                           ]);
                                } 
                               else 
                                {
                                 return Redirect::back()->with('error_msg',"Given Industry Have Already Exists");    
                                }
                                
                                
                             }
                        } 
                        $allroles= Roles::orderBy('id', 'DESC')->get();
                               return Redirect::to('admin/industry')->with('data',$allroles)->with('succ_msg',"Industry Added Successfully");
                }
                 public function skills_view()
                {
                 $allroles= Categories::orderBy('id', 'DESC')->get();
                  return View('admin.skills')->with('data',$allroles);
                }
                public function new_skills()
                {
                    $allroles= Categories::orderBy('id', 'DESC')->get();
                  return View('admin.new_skills')->with('skill_info',$allroles);
                }
                 public function skill_delete($del_id)
                {
                 if(is_numeric($del_id)):
                   $pic_id=  Categories::find($del_id)->get();
                   
                   if(isset($pic_id[0])):

                                      $delete = Categories::where('id', '=', $del_id)->delete();
                        
                   if($delete):
                      
                          return Redirect::back()->with('succ_msg',"Category Deleted Successfully");   
                      else:
                         return Redirect::back()->with('error_msg',"Invalid Request");    
                      endif;
                      
                   else:
                      return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;

                    
                   else:
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                   endif;
                }
                public function skill_add(Request $request)
                {
                       if($request->input('skill1')=='add1')
                        {  
                            $rule  =  array(
                            'name' => 'required',
                             'type'=> 'required',
                             );
                            $validator = Validator::make(Input::all(),$rule);
                            if ($validator->fails())
                             {
                                 return Redirect::to('admin/new_category')
                                                 ->withErrors($validator->messages());
                             }
                            else
                             {
                                $find_out=Categories::where('name', '=', Input::get('name'))->where('type', '=', Input::get('type'))->first();
                                
                                if (is_null($find_out)) 
                                {
                                      $object= Categories::create([
                                             'name'          => $request->input('name'),
                                             'type'      => $request->input('type'),
                                           ]);
                                         $object->save();
                                } 
                               else 
                                {
                                 return Redirect::back()->with('error_msg',"Given Category Have Already Exists With That Type");    
                                }
                                
                               
                             }
                        } 
                         if($request->input('skill2')=='add2')
                        {  
                            $rule  =  array(
                            'name' => 'required',
                             'type'=> 'required',
                             'main_skill'=>'required',
                             );
                            $validator = Validator::make(Input::all(),$rule);
                            if ($validator->fails())
                             {
                                 return Redirect::to('admin/new_category')
                                                 ->withErrors($validator->messages());
                             }
                            else
                             {
                              // return $request->input('main_skill');exit;
                                $find_out=Categories::where('name', '=', Input::get('name'))->where('ref_cat_id', '=', Input::get('main_skill'))->where('type', '=', Input::get('type'))->first();
                                
                                if (is_null($find_out)) 
                                {
                                     
                                        $object= Categories::create([
                                                     'name'          => $request->input('name'),
                                                     'type'      => $request->input('type'),
                                                     'ref_cat_id'    => $request->input('main_skill'),

                                                   ]);
                                       // return $object;exit;
                                       $object->save();
                                } 
                               else 
                                {
                                 return Redirect::back()->with('error_msg',"Given Category Have Already Exists");    
                                }
                                
                             }
                        } 
                        $allroles= Categories::orderBy('id', 'DESC')->get();
                           return Redirect::to('admin/category')->with('data',$allroles)->with('succ_msg',"Category Added Successfully");
                }
                public function skill_edit($user_id)
                {
                     if(is_numeric($user_id)):
                         $user_data=Categories::where('id','=',$user_id)->get();
                         $allroles= Categories::orderBy('id', 'DESC')->get();
                            if(isset($user_data[0])):
                               // print_r($user_data[0]);exit;
                             return View('admin.skill_edit')->with('skill_info',$user_data)->with('cat_info',$allroles);
                            else:
                             return Redirect::back()->with('error_msg',"Invalid Request");   
                            endif;
                     else:  
                      return Redirect::back()->with('error_msg',"Invalid Request");   
                     endif;
    
      
                }
               public function skill_update(Request $request)
                {
                    if($request->input('Update')=='Store')
                             {  
                                 $rule  =  array(
                                 'name' => 'required',
                                  );
                                 $role_id=Input::get('role_id');
                                 $validator = Validator::make(Input::all(),$rule);
                                 if ($validator->fails())
                                  {
                                     return Redirect::to('admin/category_edit/'.$role_id)
                                         ->withErrors($validator->messages());
                                  }
                                 else
                                  {
                                     $find_out=Categories::where('name', '=', Input::get('name'))->where('ref_cat_id', '=', Input::get('main_skill'))->where('type', '=', Input::get('type'))->first();
                                
                                        if (is_null($find_out)) 
                                        {

                                             $update = Categories::where('id', '=', $role_id)->update(array('name' => trim(Input::get('name')),'ref_cat_id' => trim(Input::get('main_skill')),'type' => trim(Input::get('type'))));

                                         } 
                                       else 
                                        {
                                         return Redirect::back()->with('error_msg',"Given Category Have Already Exists");    
                                        }
                                  }

                                 
                             }  
                              $allroles= Industry::orderBy('id', 'DESC')->get();
                               return Redirect::to('admin/category')->with('data',$allroles)->with('succ_msg',"Category Updated Successfully");
                        
                }
                 public function currency_view()
                {
                 $allroles= Currency::orderBy('id', 'DESC')->get();
                  return View('admin.currency')->with('data',$allroles);
                }
                   public function currency_delete($del_id)
                {
                 if(is_numeric($del_id)):
                   $pic_id=Currency::find($del_id)->get();
                   
                   if(isset($pic_id[0])):

                                      $delete = Currency::where('id', '=', $del_id)->delete();
                        
                   if($delete):
                      
                          return Redirect::back()->with('succ_msg',"Currency Deleted Successfully");   
                      else:
                         return Redirect::back()->with('error_msg',"Invalid Request");    
                      endif;
                      
                   else:
                      return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;

                    
                   else:
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                   endif;
                }
                public function currency_add(Request $request)
                {
                      if($request->input('Insert')=='Store')
                        {  
                            $rule  =  array(
                            'name' => 'required',
                             );
                            $validator = Validator::make(Input::all(),$rule);
                            if ($validator->fails())
                             {
                                 return Redirect::to('admin/currency')
                                                 ->withErrors($validator->messages());
                             }
                            else
                             {
                                $find_out=Currency::where('name', '=', Input::get('name'))->first();
                                
                                if (is_null($find_out)) 
                                {
                                     $object= Currency::create([
                                            'name' => trim(Input::get('name')),
                                           ]);
                                } 
                               else 
                                {
                                 return Redirect::back()->with('error_msg',"Given Currency Have Already Exists");    
                                }
                                
                                
                             }
                        } 
                        $allroles= Currency::orderBy('id', 'DESC')->get();
                               return Redirect::to('admin/currency')->with('data',$allroles)->with('succ_msg',"Currency Added Successfully");
                }
                    public function currency_edit($user_id)
                {
                         $allroles= Currency::orderBy('id', 'DESC')->get();
                 
                     if(is_numeric($user_id)):
                         $user_data=Currency::where('id','=',$user_id)->get();
                     
                            if(isset($user_data[0])):
                               // print_r($user_data[0]);exit;
                             return View('admin.currency')->with('user_info',$user_data)->with('data',$allroles);
                            else:
                            return Redirect::back()->with('error_msg',"Invalid Request");   
                            endif;
                    else:
                     return Redirect::back()->with('error_msg',"Invalid Request");        
                     endif;
    
      
                }
                  public function currency_update(Request $request)
                {
                    if($request->input('Update')=='Store')
                             {  
                                 $rule  =  array(
                                 'name' => 'required',
                                  );
                                 $role_id=Input::get('role_id');
                                 $validator = Validator::make(Input::all(),$rule);
                                 if ($validator->fails())
                                  {
                                     return Redirect::to('admin/currency_edit/'.$role_id)
                                         ->withErrors($validator->messages());
                                  }
                                 else
                                  {   
                                      $find_out=Currency::where('name', '=', Input::get('name'))->first();
                                
                                        if (is_null($find_out)) 
                                        {

                                              $update = Currency::where('id', '=', $role_id)->update(array('name' => trim(Input::get('name'))));

                                         } 
                                       else 
                                        {
                                         return Redirect::back()->with('error_msg',"Given Currency Have Already Exists");    
                                        }
                                    
                                  }

                                 
                             }  
                              $allroles= Currency::orderBy('id', 'DESC')->get();
                  return Redirect::to('admin/currency')->with('data',$allroles)->with('succ_msg',"Currency Updated Successfully");
                        
                }
                  public function units_view()
                {
                 $allroles= CurrencyUnits::orderBy('id', 'DESC')->get();
                  return View('admin.currency_units')->with('data',$allroles);
                }
                 public function units_delete($del_id)
                {
                 if(is_numeric($del_id)):
                   $pic_id=CurrencyUnits::find($del_id)->get();
                   
                   if(isset($pic_id[0])):

                                      $delete = CurrencyUnits::where('id', '=', $del_id)->delete();
                        
                   if($delete):
                      
                          return Redirect::back()->with('succ_msg',"Unit Deleted Successfully");   
                      else:
                         return Redirect::back()->with('error_msg',"Invalid Request");    
                      endif;
                      
                   else:
                      return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;

                    
                   else:
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                   endif;
                }
                public function units_add(Request $request)
                {
                      if($request->input('Insert')=='Store')
                        {  
                            $rule  =  array(
                            'name' => 'required',
                             );
                            $validator = Validator::make(Input::all(),$rule);
                            if ($validator->fails())
                             {
                                 return Redirect::to('admin/currency_units')
                                                 ->withErrors($validator->messages());
                             }
                            else
                             {
                                $find_out=CurrencyUnits::where('units', '=', Input::get('name'))->first();
                                
                                if (is_null($find_out)) 
                                {
                                     $object= CurrencyUnits::create([
                                            'units' => trim(Input::get('name')),
                                           ]);
                                } 
                               else 
                                {
                                 return Redirect::back()->with('error_msg',"Given Unit Have Already Exists");    
                                }
                                
                                
                             }
                        } 
                        $allroles= CurrencyUnits::orderBy('id', 'DESC')->get();
                               return Redirect::to('admin/currency_units')->with('data',$allroles)->with('succ_msg',"Units Added Successfully");
                }
                
                   public function units_edit($user_id)
                {
                       $allroles= CurrencyUnits::orderBy('id', 'DESC')->get();
                
                     if(is_numeric($user_id)):
                         $user_data=CurrencyUnits::where('id','=',$user_id)->get();
                     
                            if(isset($user_data[0])):
                               // print_r($user_data[0]);exit;
                             return View('admin.currency_units')->with('user_info',$user_data)->with('data',$allroles);
                            else: 
                             return Redirect::back()->with('error_msg',"Invalid Request");    
                            endif;
                     else:   
                     return Redirect::back()->with('error_msg',"Invalid Request");    
                     endif;
    
      
                }
                  public function units_update(Request $request)
                {
                    if($request->input('Update')=='Store')
                             {  
                                 $rule  =  array(
                                 'name' => 'required',
                                  );
                                 $role_id=Input::get('role_id');
                                 $validator = Validator::make(Input::all(),$rule);
                                 if ($validator->fails())
                                  {
                                     return Redirect::to('admin/units_edit/'.$role_id)
                                         ->withErrors($validator->messages());
                                  }
                                 else
                                  {
                                     $find_out=CurrencyUnits::where('units', '=', Input::get('name'))->first();
                                
                                        if (is_null($find_out)) 
                                        {

                                          $update = CurrencyUnits::where('id', '=', $role_id)->update(array('units' => trim(Input::get('name'))));

                                         } 
                                       else 
                                        {
                                         return Redirect::back()->with('error_msg',"Given Units Have Already Exists");    
                                        }
                                     
                                      
                                  }

                                 
                             }  
                              $allroles= CurrencyUnits::orderBy('id', 'DESC')->get();
                  return Redirect::to('admin/currency_units')->with('data',$allroles)->with('succ_msg',"Units Updated Successfully");
                        
                }
                public function growth_view()
                {
                 $allroles= GrowthPerYear::orderBy('id', 'DESC')->get();
                
                  return View('admin.growth')->with('data',$allroles);
                }
                 public function growth_add(Request $request)
                {
                      if($request->input('Insert')=='Store')
                        {  
                            $rule  =  array(
                            'name' => 'required',
                             );
                            $validator = Validator::make(Input::all(),$rule);
                            if ($validator->fails())
                             {
                                 return Redirect::to('admin/growth')
                                                 ->withErrors($validator->messages());
                             }
                            else
                             {
                                $find_out=GrowthPerYear::where('percentage', '=', Input::get('name'))->first();
                                
                                if (is_null($find_out)) 
                                {
                                    $update = GrowthPerYear::where('id', '=', Input::get('per_id'))->update(array('percentage' => trim(Input::get('name'))));
                                } 
                               else 
                                {
                                 return Redirect::back()->with('error_msg',"Given Growth Have Already Exists");    
                                }
                                
                                
                             }
                        } 
                        $allroles= GrowthPerYear::orderBy('id', 'DESC')->get();
                               return Redirect::to('admin/growth')->with('data',$allroles)->with('succ_msg',"Growth Added Successfully");
                }
                 public function profile_view()
                {
                      
                         $user_data=User::where('user_type', '=', 'admin')->where('deleted', '=', '0')->get();
                     
                            if(isset($user_data[0])):
                               // print_r($user_data[0]);exit;
                             return View('admin.profile')->with('user_info',$user_data);
                            endif;
                         
                    
    
                }
               public function profile_update(Request $request)
                {
                    if($request->input('Update')=='Store')
                             {  
                                 $rule  =  array(
                                 'name' => 'required|max:255',
                                 'city' => 'required',
                                 'dob' => 'required',
                                 'email' => 'required|email|max:255',
                                 'gender' => 'required',
                                  );
                                 $user_id=Input::get('user_id');
                                 $validator = Validator::make(Input::all(),$rule);
                                 if ($validator->fails())
                                  {
                                     return Redirect::to('admin/profile/'.$user_id)
                                         ->withErrors($validator->messages());
                                  }
                                 else
                                  {
                                     $dob=  date('Y-m-d',  strtotime(Input::get('dob')));
                                    
                                      $delete = User::where('id', '=', $user_id)->where('user_type', '=', 'admin')->update(array('name' => trim(Input::get('name')),'city' => trim(Input::get('city')),'dob' => trim($dob),'gender' => trim(Input::get('gender')),'email' => trim(Input::get('email'))));
                                  }

                                 
                             }  
                              $allusers=User::where('user_type', '=', 'admin')->get();
                                   return Redirect::to('admin/profile')->with('data',$allusers)->with('succ_msg',"Profile Updated Successfully");
               }
               
                public function pswd_view()
                {
                      
                         $user_data=User::where('user_type', '=', 'admin')->where('deleted', '=', '0')->get();
                     
                            if(isset($user_data[0])):
                               // print_r($user_data[0]);exit;
                             return View('admin.change_pswd')->with('user_info',$user_data);
                            endif;
                         
                    
    
                }
               public function pswd_update(Request $request)
                {
                    if($request->input('Update')=='Store')
                             {  
                                 $rule  =  array(
                                 'cur_pswd' => 'required',
                                 'password' => 'required|min:6|confirmed',
                                 'password_confirmation' => 'required',
                                  );
                                
                                 $user_id=Input::get('user_id');
                                 $validator = Validator::make(Input::all(),$rule);
                                 
                                 if ($validator->fails())
                                  { 
                                     return Redirect::to('admin/changepwd/')
                                         ->withErrors($validator->messages());
                                  }
                                 else
                                  { 
                                     $user_data=Auth::user()->password;
                                    
                                     
                                     if(!Hash::check(Input::get('cur_pswd'), $user_data))
                                     {
                                        return Redirect::back()->with('error_msg',"Invalid Current Password");     
                                     }
                                     else
                                     {
                                          if(Input::get('cur_pswd') == Input::get('password'))
                                          {
                                            return Redirect::back()->with('error_msg',"Your New password and existing password never matched");    
                                          }
                                        else
                                          {
                                           $delete = User::where('id', '=', $user_id)->where('user_type', '=', 'admin')->update(array('password' => bcrypt(Input::get('password'))));
                                          }
                                     }
                                    // print_r($user_data);exit;
                                    
                                     
                                  }

                                 
                             }  
                              $allusers=User::where('user_type', '=', 'admin')->get();
                                   return Redirect::to('admin/changepwd')->with('data',$allusers)->with('succ_msg',"Password Updated Successfully");
               }
                
    /* Front End Content Pages*/            
    public function pages()
    {
        $data = Page::get();
      return view('admin.pages')->with(['data'=>$data]);
    }

    public function page_edit($page_id,Request $request)
    {
      if(is_numeric($page_id))
      {
        $page_result = Page::find($page_id);
        if(count($page_result)>0)
        {
          $input = $request->all();
          if(isset($input['Update']))
          {
            $page_result->page_title = $input['page_title'];
            $page_result->page_name = $input['page_name'];
            $page_result->page_description = $input['page_description'];
            $page_result->save();
            
            return redirect('/admin/pages')->with('succ_msg','Content Page Updated Successfully');
          }
          return view('admin.page_edit')->with(['page_det'=>$page_result]);
        }
        else
        {
          return redirect('/admin/pages')->with('error_msg','Invalid Request');
        }
      }
      else
      {
        return redirect('/admin/pages')->with('error_msg','Invalid Request');
      }
    }
    /* END Front End Content Pages*/
    
  /* Front End text Pages*/            
    public function text()
    {
        $data = Content::get();
    return view('admin.text')->with(['data'=>$data]);
    }

    public function text_edit($text_id,Request $request)
    {
      if(is_numeric($text_id))
      {
        $text_result = Content::find($text_id);
        if(count($text_result)>0)
        {
          $input = $request->all();
          if(isset($input['Update']))
          {
            $text_result->pagetitle = $input['pagetitle'];
            $text_result->title = $input['title'];
           $content = str_replace('<p>','',$input['content']);
            $text_result->content = str_replace('</p>','',$content);
            $text_result->save();
            
            return redirect('/admin/text')->with('succ_msg','Content Updated Successfully');
          }
          return view('admin.text_edit')->with(['page_det'=>$text_result]);
        }
        else
        {
          return redirect('/admin/text')->with('error_msg','Invalid Request');
        }
      }
      else
      {
        return redirect('/admin/text')->with('error_msg','Invalid Request');
      }
    }
    /* END Front End text lines*/
  
  
  
  
    /*legal functions*/
                public function list_legal()
                {    
                        $data = Legal::orderBy('id', 'desc')->get();
                       return view('admin.legal')->with(['data'=>$data]);
                }
                public function legal_del($del_id)
                {

                             if(is_numeric($del_id)):
                                                 $pic_id= Legal::find($del_id)->get();

                             if(isset($pic_id[0])):

                                                  $delete = Legal::where('id', '=', $del_id)->delete();

                             if($delete):

                                      return Redirect::back()->with('succ_msg',"Legal Deleted Successfully");   
                                  else:
                                     return Redirect::back()->with('error_msg',"Invalid Request");    
                                  endif;

                               else:
                                  return Redirect::back()->with('error_msg',"Invalid Request");    
                               endif;


                               else:
                                 return Redirect::back()->with('error_msg',"Invalid Request");   
                               endif;  
                }
                public function edit_legal($page_id,Request $request)
                {
                      
                  if(is_numeric($page_id))
                  { 
                    $page_result = Legal::find($page_id);
                    if(count($page_result)>0):
                        
                    
                            if($page_result->id)
                            {
                              $input = $request->all();

                              if(isset($input['Update']))
                              {
                                        $data = array(
                                                    'title' => $request->input('title'),
                                                    'subject'  => $request->input('subject'),
                                                    'content'     => $request->input('content'),
                                                   );
                                        $rule  =  array(
                                                    'title' => 'required|max:200',
                                                    'subject'  =>'required|max:250',
                                                    'content'     => 'required',
                                                    );
                                        $validation = Validator::make(Input::all(),$rule);
                                        if($validation->fails())
                                        {   
                                            return Redirect::to('legal')
                                                ->withErrors($validation->messages());
                                        }
                                        else
                                        { 

                                        $page_result->title = $input['title'];
                                        $page_result->subject = $input['subject'];
                                        $page_result->content = $input['content'];
                                        $page_result->save();

                                        return redirect('/admin/legal')->with('succ_msg','Content Page Updated Successfully');
                                        }
                              }
                              return view('admin.legal_edit')->with(['page_det'=>$page_result]);
                            }
                            else
                            {
                              return redirect('/admin/legal')->with('error_msg','Invalid Request');
                            }
                        else:
                           return redirect('/admin/legal')->with('error_msg','Invalid Request'); 
                       endif;
                  }
                  else
                  {
                    return redirect('/admin/legal')->with('error_msg','Invalid Request');
                  }
                 }
                public function view_legal(Request $request)
                {
                    if($request->input('legal')=='Insert')
                     {  
                                $data = array(
                                            'title' => $request->input('title'),
                                            'subject'  => $request->input('subject'),
                                            'content'     => $request->input('content'),
                                           );
                                $rule  =  array(
                                            'title' => 'required|max:200',
                                            'subject'  =>'required|max:250',
                                           // 'content'     => 'required',
                                            );
                                $validation = Validator::make(Input::all(),$rule);
                                if($validation->fails())
                                {   
                                    return Redirect::to('/admin/legal')
                                        ->withErrors($validation->messages());
                                }
                                else
                                {    $admin ="";
                               
                                     $result = Legal::create([
                                                'title'     => $data['title'],
                                                'subject'      => $data['subject'],
                                                'content'         => $data['content'],
                                                  ]);
                                     return redirect('/admin/legal')->with('succ_msg','Content Page Added Successfully');
                                }
                        }
                       
                        return view('admin.legal_view');

                }
                
                //legal end
                
                 //funding approval
                 public function funding()
                {
                     $userdata= Profile::funding_business();
                     return View('admin.fund_approve')->with('fund',$userdata);
                }
                public function fund_approve($fund_id, $status='')
                { 
                     if(is_numeric($fund_id)):
                     $pro_id=Profile::where('id','=',$fund_id)->get();
                     //print_r($fund_id); exit;
                     $userinfo = User::where('id','=',$pro_id[0]->user_id)->get()->first();
                     //echo $pro_id[0]->user_id; echo $userinfo->email; exit;
                     $type="";
                   
                       $action = "";
                        if($status == 'approve'):
                        $action = "YES"; 
                        elseif($status == 'pending'):
                        $action = "NO";
                        else:
                        $action = "YES";
                        endif;
                     
                            if(isset($pro_id[0])):
                                    $approved = Profile::where('id', '=', $fund_id)->update(array('is_approve' => $action));
                                    if($approved):
                                         $type=$pro_id[0]->status_business;
                                    $resmail = Mail::send('emails.adminapprove', ['name' => $userinfo->name,'status'=>$status], function($message)
                  use($userinfo){
                      $message->to($userinfo->email)->subject('Admin User Staus Updation');           
                  });
                                         return Redirect::back()->with('succ_msg',  ucfirst($status)." Action Successfully Updated");   
                                   else:
                                         return Redirect::back()->with('error_msg',"Invalid Request");    
                                   endif;
                                   
                                   
                                   
                            else:
                               return Redirect::back()->with('error_msg',"Invalid Request");
                            endif;
                    else:
                        return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;
                }
                public function fundOrgEnquiry()
                {
                    $input = Input::all();
                   // print_r($input); exit;
                    if(!empty($input['org_enq']))
                    {
                        
                        /*
                         * select `username`, `email` from `users` 
                         * inner join `profiles` on users.id =profiles.user_id  where profiles.id = 210
                         */
                        
                        $recever = User::select('username','email')
                                ->join('profiles','users.id' , '=','profiles.user_id')
                                ->where('profiles.id','=',$input['p_id'])->get()->first();
                        $name['name'] = $recever->username;
                        $name['email'] = $recever->email;
                        //$sender = Auth::user()->email;'rec_email' => $rec_email,
                        Mail::send('emails.adminenqry', ['name' => $recever->username,'query' => $input['org_enq']], function($message)
                  use($name){
                      $message->to($name['email'])->subject('Enquiry Details');           
                  });
                        return Redirect::back()->with('succ_msg',  ucfirst($recever->username)." Enquiry Form Submited Successfully ");   
                    }
                    else
                    {
                        return Redirect::back()->with('error_msg',"Please Enter Enquiry Information");
                    }
                    
                }
                    //contact importes
                 public function importes()
                {
                      $data = Import_contacts::select('id','importer','status','title','image')->orderBy('id', 'desc')->get()->toArray();
                      
                     return View('admin.import_contact')->with('data',$data);
                }
                public function import_status($fund_id, $status='')
                { 
                     if(is_numeric($fund_id)):
                     $pro_id=Import_contacts::where('id','=',$fund_id)->get();
                     //print_r($fund_id); exit;
                     
                       $action = "";
                        if($status == 'approve'):
                        $action = "OFF"; 
                        elseif($status == 'pending'):
                        $action = "ON";
                        else:
                        $action = "ON";
                        endif;
                     
                            if(isset($pro_id[0])):
                                    $approved = Import_contacts::where('id', '=', $fund_id)->update(array('status' => $action));
                                    if($approved):
                                        
                                         return Redirect::back()->with('succ_msg',  ucfirst($action)." Action Successfully Updated");   
                                   else:
                                         return Redirect::back()->with('error_msg',"Invalid Request");    
                                   endif;
                                   
                                   
                                   
                            else:
                               return Redirect::back()->with('error_msg',"Invalid Request");
                            endif;
                    else:
                        return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;
                }
                 public function add_contacts(Request $request)
                {   
                    
                    if($request->input('contact')=='Insert')
                     {  
                                $data = array(
                                            'importer' => $request->input('importer'),
                                            'title'  => $request->input('title'),
                                           );
                                $rule  =  array(
                                            'importer' => 'required|max:200',
                                            'title' => 'required|max:200',
                                            'image' => 'required|image|max:2000',
                                            );
                                $validation = Validator::make(Input::all(),$rule);
                                if($validation->fails())
                                {   
                                    return Redirect::to('/admin/add_contacts')
                                        ->withErrors($validation->messages());
                                }
                                else
                                {    $admin ="";
                               
                                     $result = Import_contacts::create([
                                                'importer'     => $data['importer'],
                                                'title'      => $data['title'],
                                                  ]);
                                       $id = $result->id;
                                       $image = Input::file('image');       
                                       $img_name  = $image->getClientOriginalName();
                                       $info = pathinfo($img_name);
                                       $org_name =  basename($img_name,'.'.$info['extension']);
                                       $tmp = explode('.', $img_name);
                                       $ext = end($tmp);
                                       $filename=$org_name.'_'.$id.'.'.$ext;
                        
                                      $destination = 'images/icons/';   
                                      //echo $filename;exit;
                                      $image->move($destination, $filename);
                                      $approved = Import_contacts::where('id', '=', $id)->update(array('image' => $filename));
                                    
                                     return redirect('/admin/add_contacts')->with('succ_msg','Import Contact Added Successfully');
                                }
                        }
                       
                       return View('admin.add_contacts');

                }
                 public function import_delete($del_id)
                {
                 if(is_numeric($del_id)):
                   $pic_id= Import_contacts::where('id','=',$del_id)->get()->first();
                   
                   if(isset($pic_id->id)):
                                     
                                        $dd = $pic_id->image;

                                         $m_img_path='images/icons/'.$dd;
                                         if (file_exists($m_img_path))
                                           {
                                               unlink($m_img_path);     
                                           }
                                         $delete = Import_contacts::where('id', '=', $del_id)->delete();
                   if($delete):
                      
                          return Redirect::back()->with('succ_msg',"Contact Deleted Successfully");   
                      else:
                         return Redirect::back()->with('error_msg',"Invalid Request");    
                      endif;
                      
                   else:
                      return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;

                    
                   else:
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                   endif;
                }
                 public function import_edit($user_id)
                {
                     
                     if(is_numeric($user_id)):
                         $data=Import_contacts::where('id','=',$user_id)->get();
                     
                            if(isset($data[0])):
                               // print_r($user_data[0]);exit;
                             return View('admin.edit_contacts')->with('data',$data);
                            else:
                            return Redirect::back()->with('error_msg',"Invalid Request");   
                            endif;
                     else:    
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                     endif;
    
      
                }
                 public function import_update(Request $request)
                {
                    if($request->input('Update')=='Store')
                             {  
                                $data = array(
                                            'importer' => $request->input('importer'),
                                            'title'  => $request->input('title'),
                                           );
                                $rule  =  array(
                                            'importer' => 'required|max:200',
                                            'title' => 'required|max:200',
                                            );
                                 $role_id=Input::get('role_id');
                                 $validator = Validator::make(Input::all(),$rule);
                                 if ($validator->fails())
                                  {
                                     return Redirect::to('admin/edit_contacts/'.$role_id)
                                         ->withErrors($validator->messages());
                                  }
                                 else
                                  {   
                                      $pic_id= Import_contacts::where('id','=',$role_id)->get()->first();
                   
                                      if(isset($pic_id->id)):
                                        $update = Import_contacts::where('id', '=', $role_id)->update(array('importer' => trim(Input::get('importer')),'title' => trim(Input::get('title'))));
                                        $dd = $pic_id->image;
                                        
                                         $image = Input::file('image'); 
                                         if($image):
                                            $m_img_path='images/icons/'.$dd;
                                                if (file_exists($m_img_path))
                                                  {
                                                      unlink($m_img_path);     
                                                  }
                                       $img_name  = $image->getClientOriginalName();
                                       $info = pathinfo($img_name);
                                       $org_name =  basename($img_name,'.'.$info['extension']);
                                       $tmp = explode('.', $img_name);
                                       $ext = end($tmp);
                                       $filename=$org_name.'_'.$role_id.'.'.$ext;
                        
                                      $destination = 'images/icons/';   
                                      //echo $filename;exit;
                                      $image->move($destination, $filename);
                                      $approved = Import_contacts::where('id', '=', $role_id)->update(array('image' => $filename));
                                         endif;
                                      
                                     else:
                                      return Redirect::back()->with('error_msg',"Invalid Request");   
                                     endif;
                                  }
                                 
                             }  
                              
                               $data = Import_contacts::select('id','importer','status','title','image')->orderBy('id', 'desc')->get()->toArray();
                      
                             return Redirect::to('admin/importes')->with('data',$data)->with('succ_msg',"Contact Updated Successfully");
                        
                }
                 public function subscribers()
                {
                 $subscribe= subscribe::orderBy('id', 'DESC')->get();
                  return View('admin.subscribers')->with('data',$subscribe);
                }
                public function remove_subscribe($del_id)
                {
                 
                 if(is_numeric($del_id)):
                   $pic_id= subscribe::where('id','=',$del_id)->get()->first();
                   
                   if(isset($pic_id->id)):
                                $delete = subscribe_mails::where('sub_id', '=', $del_id)->delete();
                                $delete = subscribe::where('id', '=', $del_id)->delete();
                     if($delete):
                      
                          return Redirect::back()->with('succ_msg',"subscriber Deleted Successfully");   
                      else:
                         return Redirect::back()->with('error_msg',"Invalid Request");    
                      endif;
                      
                   else:
                      return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;
                   else:
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                   endif;
                
                }
                public function reply_subscribe($user_id)
                {
                     
                     if(is_numeric($user_id)):
                         $data=subscribe::where('id','=',$user_id)->get()->first();
                     
                            if(isset($data)):
                               //print_r($data[0]);exit;
                             return View('admin.reply_subscriber')->with('data',$data);
                            else:
                            return Redirect::back()->with('error_msg',"Invalid Request");   
                            endif;
                     else:    
                     return Redirect::back()->with('error_msg',"Invalid Request");   
                     endif;
    
      
                }
               public function reply_mail()
                {
                      return View('admin.reply_mail');
                }
                
                public function send_mail(Request $request)
                 {
                            $input = $request->all();
                            if($request->input('send')=='Send')
                            {
                              
                              $message=str_ireplace('<p>','',$input['mail_description']);
                              $message=str_ireplace('</p>','',$message);

                              $sub = subscribe::where('status','=','1')->get(); 
                              if(count($sub)>0)
                              {
                                for($i=0;$i<count($sub);$i++)
                                {
                                $result= subscribe_mails::create(['sub_id'=>$sub[$i]['id'],'sub_email' => trim($sub[$i]['email']),'subject'=>$input['subject'],'message'=>$message]);
                             
                                if($result){
                                         Mail::send('emails.reply_subscribe',['email' => $sub[$i]['email'],'subject'=>$input['subject'],'message_reply'=>$message], function($message)
                                        use($input,$sub,$i){
                                            $message->to($sub[$i]['email'])->subject($input['subject']);          
                                             });
                        
                                         }
                                 }

                                 return redirect('/admin/subscribers')->with('succ_msg','Mail sent successfully');
                              }
                              else
                              {
                                 return redirect('/admin/subscribers')->with('error_msg','Please approve atleast one subscriber');
                              }
                            }
                            return view('admin.reply_subscriber')->with(['data'=>$page_result]);
                }
                public function send_reply($page_id,Request $request)
                 {
                       if(is_numeric($page_id))
                       {
                             
                          $page_result = subscribe::find($page_id);
                          if(count($page_result)>0)
                          {
                            $input = $request->all();
                            if($request->input('send')=='Send')
                            {
                              
                              $message=str_ireplace('<p>','',$input['mail_description']);
                              $message=str_ireplace('</p>','',$message);    
                              $result= subscribe_mails::create(['sub_id'=>$page_id,'sub_email' => trim($input['email']),'subject'=>$input['subject'],'message'=>$message]);
                             
                                if($result){
                                   Mail::send('emails.reply_subscribe',['email' => $input['email'],'subject'=>$input['subject'],'message_reply'=>$message], function($message)
                                  use($input){
                                      $message->to($input['email'])->subject($input['subject']);          
                                       });
                        
                                    }
                              return redirect('/admin/subscribers')->with('succ_msg','Content Page Updated Successfully');
                            }
                            return view('admin.reply_subscriber')->with(['data'=>$page_result]);
                          }
                          else
                          {
                            return redirect('/admin/subscribers')->with('error_msg','Invalid Request');
                          }
                       }
                      else
                      {
                        return redirect('/admin/subscribers')->with('error_msg','Invalid Request');
                      }
                }
                 public function subscribe_status($fund_id, $status='')
                { 
                     if(is_numeric($fund_id)):
                     $pro_id=subscribe::where('id','=',$fund_id)->get();
                     //print_r($fund_id); exit;
                     
                       $action = "";
                        if($status == 'approve'):
                        $action = "1"; 
                        elseif($status == 'pending'):
                        $action = "0";
                        else:
                        $action = "0";
                        endif;
                     
                            if(isset($pro_id[0])):
                                    $approved = subscribe::where('id', '=', $fund_id)->update(array('status' => $action));
                                    if($approved):
                                        
                                         return Redirect::back()->with('succ_msg',  "Status Successfully Updated");   
                                   else:
                                         return Redirect::back()->with('error_msg',"Invalid Request");    
                                   endif;
                                   
                                   
                                   
                            else:
                               return Redirect::back()->with('error_msg',"Invalid Request");
                            endif;
                    else:
                        return Redirect::back()->with('error_msg',"Invalid Request");    
                   endif;
                }
                
}
