<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Action\Enquiry;
use Illuminate\Http\Request;
// use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Action\Common;
use Illuminate\Http\Response;

use App\Http\Controllers\Action\Post;
use App\Http\Controllers\Auth\authentication;
use App\Http\Controllers\Auth\User;
use DOMDocument;
use DOMXPath;


use Illuminate\Http\JsonResponse;
use DateTime;
use DateTimeZone;
use CssToInlineStyles;

use DB;
use Jenssegers\Agent\Agent;
use Mail;
use Input;

/**
 * Class to handle /v1/action
 * Laravel controller
 * @version	0.1
 * @author saurabh singh
 * @github saurabhsingh
 */

class PostController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    private $user_id 	= '' ;
    private $email 		= '' ;
    private $uname	 	= ''  ;
    private $status;
    private $user ;
    private $request ;
    private $action;

    private $temp ;
    private $res ;

    /**
     * Main function of the action route, responsible for all return
     * @route:	/v1/action/{$method}
     * @param Request $request: Illuminate\Http\Request
     * @param unknown $method: route's subroute
     * @return Respose: Response to the api request
     */
    public function call(Request $request, $method)
    {

        /**
         * Some intialiation so that every function can globally access it
         */
        $this->request = $request ;
        $GLOBALS['currDate'] = date("Y-m-d");
        $GLOBALS['currDateTime'] = date("Y-m-d H:i:s") ;
        if ($request->has('token'))
        {
            $token = $request->input('token');
            $auth = new authentication();

            $user_id = $auth->authToken($token);
            if ($user_id) {
                /**
                 * Setting private variables of class to be globally access by other function
                 * Helps in accessing common variables need to be shared
                 * @var Ambiguous $user_id
                 * @var Ambiguous $email
                 * $var Ambiguous $action
                 */

                $us = new User();

                $this->user = $us->get($user_id) ;
                $this->user_id = $user_id ;

                $this->email = $this->user[$_ENV['EMAIL']];
                $this->uname = $this->user['username'];
                $this->status = $this->user['status'];
                $this->action = new Post($this->user_id, $this->email );
            }
            else {
                // return new Response(array( "res" => "Unauthorized action. Token access denied" ) , 200 );
                //abort(403, 'Unauthorized action. Token access denied');
				//if(!$user_id)
                return new JsonResponse(array(
                    "status#" => "403" ,
                    "message#" => "Token unauthenticated"
                )) ;
            }
        }
        else {
            /**
             * this column for guest user, which didn't login
             */
            $this->action = new Post();
        }

        /**
         * Switch case to call other function based on sub routes (method type)
         * @var $method
         */
        switch ($method) {
            case 'createpost':
                $res = $this->createpost();
                if ($res == false)
                    return new JsonResponse ( array ( "status#" => "1071" , "data#" => "" ));
                else if ($res === true )
                    return new JsonResponse( array ( "status#" => "1" ) ) ;
                else
                    return new JsonResponse ( array ( "status#" => "1" , "data#" => $res ));

                break;

            case 'getallposts':
                $res = $this->getallposts();
                if ( (!empty($res)) && ($res == false))
                    return new JsonResponse ( array ( "status#" => "1071" , "data#" => "" ));
                else
                    return new JsonResponse ( array ( "status#" => "1" , "data#" => $res ));
                break;

            case 'getleaddetail':
                $res = $this->getleaddetail();
                if ($res == false)
                    return new JsonResponse ( array ( "status#" => "1071" , "data#" => "" ));
                else
                    return new JsonResponse ( array ( "status#" => "1" , "data#" => $res ));

                break;

            case 'getalltags':
                $res = $this->getalltags();
                if ($res == false)
                    return new JsonResponse ( array ( "status#" => "1071" , "data#" => "" ));
                else
                    return new JsonResponse ( array ( "status#" => "1" , "data#" => $res ));

                break;

            case 'enquiry':
                $res = $this->enquiry();
                if ($res == false)
                    return new JsonResponse ( array ( "status#" => "1071" , "data#" => "" ));
                else if($res == true)
                    return new JsonResponse ( array ( "status#" => "1"  ));
                else
                    return new JsonResponse ( array ( "status#" => "1071" , "message#" => "unexpected error" ));

                break;

            default:
//                $this->action->createlog($this->uname, $method, '' , "", $GLOBALS['currDateTime'], "invalid method name");
                return new Response( array ( "status#" => "1060" , "message#" => "Not valid method" ) , 406 );
                break;
        }
    }


    public function getfaqs(Request $request)
    {

        $all= array(
            [
                "ques" => "What is Plant Bee?",
                "ans" => "PlantBee.com is a leading market place for buying/selling/renting used machines and plants across different sectors."
            ],
            [
                "ques" => "How does it work?",
                "ans" => "The seller/buyer uploads his offer/requirement on the www.plantbee.com. After our verification process the offer is listed on website and interested people start contacting the seller/buyer. Through the help of our paid services the publisher can reach more people and can get more enquiries."
            ],
            [
                "ques" => "Is it free?",
                "ans" => "Plantbee is a paid listing website. It is a premium market place for used plants and machines. Our objective is to bring genuine buyers and sellers on a single platform."
            ],
            [
                "ques" => "What do you charge?",
                "ans" => "For Sellers: We have two packages for sellers (pls find it above) For Buyers: We charge a fee of INR 8,000, INR 15000 plus GST from buyers"
            ],
            [
                "ques" => "How will you promote my lead?",
                "ans" => "We have various mediums of promotion such as: a) Weekly e-mailers to strong network of prospective buyers/seller brokers, traders, investors, project heads. b) SMS to selected people in our network. c) Ad in our monthly magazine."
            ],
            [
                "ques" => "What if I do not want to disclose my identity?",
                "ans" => "That is completely fine. Just mention that at the time of registration and we assure you 100% confidentiality of your identity. However, we still need your company details for the verification purpose."
            ],
            [
                "ques" => "How can I find a Plant/Machine on your site?",
                "ans" => "We have a fine search feature on our website which will guide you to the product you are looking for. You refine your search on the basis of region, plant, process type etc."
            ],
            [
                "ques" => "What is your verification process?",
                "ans" => "To make sure that the offers listed are by genuine parties each lead goes through a verification process. Under our verification process we check existence of the entity/publisher."
            ]
        );

        return new JsonResponse( array( "status#" => "1" , "data#" => $all ) );
    }


    private function createpost()
    {
        if( $this->request->has('category') &&      //
            $this->request->has('description') &&   //
            $this->request->has('country')      //
//            $this->request->has('plant_type')       //
        ) {
            //Array to be inserted in lead
            $req = array();

            // Array to be inserted in images
            $img = array();

            //array to store lead details
            $lead_details = array() ;

            $send_otp = false ;
            $new_user = true ;
            // In case of new user
            $name = null ;
            $company = null ;


            if (!empty($this->user))
            {
                $req['email_id'] = $this->user['email'];
                $req['mobile'] = $this->user['phoneno'];
                $req['company_make'] = $this->user['company']  ;
                $new_user = false ;

            } else if ($this->request->has('email') &&
                $this->request->has('phone') &&
                $this->request->has('name') &&
                $this->request->has('company')
            ) {
                $req['email_id'] = $this->request->input('email');
                $req['mobile'] = $this->request->input('phone');
                $name = $this->request->input('name');
                $req['company_make'] = $company = $this->request->input('company');

                /**
                 * Set otp variable
                 */
                $send_otp = true ;
            } else
                abort(206, 'Please authenticate request or send email/phone/company/name');

            /**
             * For images
             */
            if (Input::hasFile('images'))
            {
                $files = Input::file('images') ;
//                echo "in Images" ;
//                echo gettype($files) ;
                if(is_array($files))
                {
                    foreach ( $files as $file) {
//                    echo "In arrya0" ;
                        $rules = array('file' => 'required|mimes:png,jpeg'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
                        $validator = \Validator::make(array('file' => $file), $rules);

                        if ($validator->passes()) {
                            $destinationPath = $_ENV['PLANT_BEE_IMAGE_UPLOAD']; // upload path
                            $filename = rand(11111, 99999) . '_' . $file->getClientOriginalName();
                            $upload_success = $file->move($destinationPath, $filename);
                            $req['have_images'] = "yes" ;
                            $img[] = array(
                                "image_url" => $filename,
                                "table_type" => ""
                            ) ;
                        } else if ($validator->fails()) {
                            // Send errors if file not valid
                            abort(206 , "Image upload error");
                        }
                    }
                }
                else
                    abort(206, "Images should be in array");

            }


            /**
             * For documents
             */
            if (Input::hasFile('docs'))
            {
                if(is_array(Input::file('docs')))
                {
                    foreach (Input::file('docs') as $file) {
                        $rules = array('file' => 'required'); //'required|mimes:png,gif,jpeg,txt,pdf,doc'
                        $validator = \Validator::make(array('file' => $file), $rules);

                        if ($validator->passes()) {
                            $destinationPath = $_ENV['PLANT_BEE_DOC_UPLOAD']; // upload path
                            $filename = str_random(6) . '_' . $file->getClientOriginalName();
                            $upload_success = $file->move($destinationPath, $filename);
                            $req['have_doc'][] = $filename ;
                        } else if ($validator->fails()) {
                            // Send errors if file not valid
                            abort(206 , "Document upload error");;
                        }
                    }
                }
                else
                    abort(206, "Docs should be in array");


                $req['have_doc'] = implode(', ' ,  $req['have_doc'] ) ;
            }


            $req['country_id']    = $this->request->input('country') ;
            if($this->request->has('plant_type'))
                $req['plant_type_code']    = $this->request->input('plant_type') ;
            $req['offer_detail'] = $this->request->input('description') ;
            $req['verified'] = 'no' ;
            $req['status'] = 'blocked' ;
            $req['datetime'] = $GLOBALS['currDateTime'] ;
            $req['otp_verify'] = false ;

            $state = null ;
            $city = null ;
            if($this->request->has('state'))
                $req['state_id']  = $state  = $this->request->input('state') ;

            if($this->request->has('city'))
                $req['city_id'] =  $city   = $this->request->input('city') ;

            if($this->request->has('lead_details'))
            {
                if(is_array($this->request->input('lead_details')))
                {
                    for ($i = 0 ; $i< count($this->request->input('lead_details')) ; $i++ )
                    {
                        $lead_details[$i]['type'] = $this->request->input('lead_details')[$i]['type'] ;
                        if(!empty($this->request->input('lead_details')[$i]['name']))
                            $lead_details[$i]['particular'] = $this->request->input('lead_details')[$i]['name'];

                        if($lead_details[$i]['type'] == 'machine' )
                        {
                            $lead_details[$i]['numbers'] = $this->request->input('lead_details')[$i]['quantity'] ;
                            $lead_details[$i]['capacity'] = $this->request->input('lead_details')[$i]['capacity'];
                            $lead_details[$i]['make'] = $this->request->input('lead_details')[$i]['make'] ;
                            $lead_details[$i]['year'] = $this->request->input('lead_details')[$i]['year'] ;
                        }

                        if($lead_details[$i]['type']== 'land')
                        {
                            $lead_details[$i]['area'] = $this->request->input('lead_details')[$i]['area'] ;
                            $lead_details[$i]['location'] = $this->request->input('lead_details')[$i]['location'] ;

                        }
                        if($lead_details[$i]['type'] == 'misc')
                        {
                            $lead_details[$i]['numbers'] = $this->request->input('lead_details')[$i]['quantity'] ;
                            $lead_details[$i]['capacity'] = $this->request->input('lead_details')[$i]['capacity'];
                            $lead_details[$i]['make'] = $this->request->input('lead_details')[$i]['make'] ;
                            $lead_details[$i]['year'] = $this->request->input('lead_details')[$i]['year'] ;
                        }

                        if(!empty($this->request->input('lead_details')[$i]['remarks']))
                            $lead_details[$i]['remarks'] = $this->request->input('lead_details')[$i]['remarks'] ;

                    }
                }
                else
                    abort(206 , "lead details is not array");
            }

            /**
             * Create user if not exists
             */
            if($send_otp)
            {
                /**
                 * Check if user exists in database according to mobile number
                 */
                $result = DB::table('tbl_members')
                    ->select('phoneno' , 'id')
                    ->where('phoneno' , '=' , $req['mobile'])
                    ->first();

                //if phone exists then only send otp on phone number and email
                if($result)
                {
                    /**
                     * call send otp to mobile and email
                     */
                    $send_otp = true ;
                    /**
                     * Assign userid to $req
                     */
                    $req['user_personal_detail_id'] = $result['id'] ;
                    $new_user = false ;
                }
                //If user not exits then create user account and then send password to email and send otp on phone and email to validate
                else
                {
                    /**
                     * Create user and get userid
                     */
                    $source_from = null ;

                    /**
                     * For IpAddress
                     */
                    $ipAddress = $_SERVER['REMOTE_ADDR'];
                    if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
                        $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
                    }

                    $user = new User();
                    $password = str_random(10);
                    /**
                     * Automatic User creation
                     */
                    $user->create(
                        $req['email_id'] ,
                        $password ,
                        $req['email_id'] ,
                        $company ,
                        $name ,
                        $req['mobile'] ,
                        "SteelMint Mobileapp plantbee auto user creation" ,
                        $req['country_id'] ,
                        $state,
                        $ipAddress,
                        $source_from ) ;


                    /**
                     * Assign userid to $req
                     */
                    $req['user_personal_detail_id'] = DB::table('tbl_members')
                        ->select( 'id')
                        ->where('phoneno' , '=' , $req['mobile'])
                        ->first()['id'] ;
                    $new_user = true ;
                }

            }

            /**
             * Create entry of post in database
             * 1. create entry in leads table
             * 2. create entry in leads_detail table
             * 3. create entry in images
             */
            $lead_id = DB::table('leads')
                ->insertGetID($req) ;

            if(count($lead_details) > 1 )
            {
                foreach($lead_details as $details )
                {
                    $details['lead_id'] = $lead_id ;
                    DB::table('leads_detail')
                        ->insert($details) ;
                }
            }

            if( count($img) > 1 )
            {
                foreach($img as $images)
                {
                    $images['table_type'] = "leads" ;
                    $images['table_id'] = $lead_id ;
                }

            }

            $otp_id = null ;
//            if($send_otp)
//            {
//                $otp = new OTPverification() ;
//                if($new_user)
//                    $otp_id = $otp->sendOTP("plantbee" , $req['mobile']  , array( "user" => $req['user_personal_detail_id'] , "lead" => $lead_id ) ) ;
//                else
//                    $otp_id = $otp->sendOTP("plantbee" , $req['mobile']  , array( "lead" => $lead_id ) ) ;
//
//                return new JsonResponse (  array( "status#" => "1" , "data#" => array( "opt_id" => $otp_id )  ));
//            }

//            return new JsonResponse (  array( "status#" => "1" ));
            return true ;
        }

        abort(206 , "Partial Input") ;
    }

    /**
     * Get All Posts
     * @route:	/v1/action/getallposts
     * @return $res_arr: 	Response array having post information
     */
    private function getallposts()
    {
        $conditions = "1";
        $cityArr = array();

        if($this->request->has('zone'))
        {
            $zone = explode(";", $this->request->input('zone'));
            $cityArr = DB::table('tbl_state_city')
                ->select("city_id")
                ->whereIn('zone' , $zone )
                ->get();
        }

        $post_from = null ;
        if($this->request->has('postfrom'))
        {
            $post_from = $this->request->input('postfrom') ;
        }

        $result = DB::connection('mysql');
        $plant_type = null;
        if($this->request->has('plant_type')) {
            $plant_type = array() ;
            $plant_typearr = $this->request->input('plant_type');
            $this->cal_child_arr();
            foreach($plant_typearr as $plant )
            {
                if(is_array($this->res[$plant]))
                    $plant_type = array_merge( $this->res[$plant] , $plant_type ) ;
                $plant_type[] = $plant ;
            }

        }
		
		/*portfolio filter*/
		if($this->request->has('portfolio'))
        {
             if ($this->request->has('token')) {
				 $auth = new authentication();
				$token = $this->request->input('token');
				$user_id = $auth->authToken($token);
				
				if(!$user_id)
                return new JsonResponse(array(
                    "status#" => "403" ,
                    "message#" => "Token unauthenticated"
                )) ;
				
				$common = new Common();
				$temp = $common->getUserPortfolio($user_id, 'plantbee');	
				
				if(empty($temp['category']))
					$plant_type = array(0);
				else
					$plant_type = explode(',',$temp['category']);
				if(empty($temp['lead_type']))
					$lead_type = array(0);
				else
					$lead_type = strtolower($temp['lead_type']); 
				
				$plant_type = array_filter($plant_type);
				//$lead_type = array_filter($lead_type);
			}					
        } ///*end portfolio filter*/

        //var_dump($plant_type) ;

//,DB::raw('count(leads.id) as total_views')
        $most_viewed = false ;
        if($this->request->has('most_viewed'))
        {
            $most_viewed = $this->request->input('most_viewed');
            $most_viewed = $most_viewed === 'true' ? true: false ;
        }
        $query = $result->table('leads') ;
        if ($most_viewed)
        {
            $query->select('leads.id' ,'leads.title','leads.user_personal_detail_id','leads.plant_type_code','leads.offer_detail','leads.contact_person','leads.designation','leads.email_id','leads.mobile','leads.std_code','leads.status','leads.datetime','leads.state_id','leads.city_id','leads.locality','leads.verified','leads.user_status','leads.type','leads.tags_id','leads.prices_detail','leads.have_images','leads.have_doc','leads.country_id','leads.sold_out',
                'category' , 'undisclose_col_val' , 'latitude' , 'longitude' ,
                'tbl_members.pymDtls as about_company', 'tbl_members.company as company_name' , 'tbl_companytype.name as business_type' , 'tbl_members.address as address' , 'tbl_members.id as memid',
                DB::raw('count(leads.id) as total_views'));
        }
        else
            $query->select('leads.id','leads.title','leads.user_personal_detail_id','leads.plant_type_code','leads.offer_detail','leads.contact_person','leads.designation','leads.email_id','leads.mobile','leads.std_code','leads.status','leads.datetime','leads.state_id','leads.city_id','leads.locality','leads.verified','leads.user_status','leads.type','leads.tags_id','leads.prices_detail','leads.have_images','leads.have_doc','leads.country_id','leads.sold_out',
                'category', 'undisclose_col_val' , 'latitude' , 'longitude' ,
                'tbl_members.pymDtls as about_company', 'tbl_members.company as company_name' , 'tbl_companytype.name as business_type' , 'tbl_members.address as address' ,'tbl_members.id as memid' );

        if ($most_viewed)
            $query->leftJoin('impression', 'leads.id', '=', 'impression.lead_id');

        $query->leftJoin('tbl_members', 'leads.user_personal_detail_id', '=' , 'tbl_members.id' ) ;
        $query->leftJoin('tbl_companytype' , 'tbl_members.companytype' , '=', 'tbl_companytype.id') ;

        $query->where('leads.status','=', 'approved');
        $query->where('leads.verified','=', 'yes');
        $query->where('leads.user_status','=', 'enable');

        if(count($cityArr) || $this->request->has('zone') ) {
            $query->whereIn('leads.city_id', $cityArr);
        }

        if($this->request->has('on_rent')){
            $on_lease = $this->request->input('on_rent');
            $on_lease = $on_lease === 'true' ? 1: 0 ;
//            $on_lease =  ($on_lease)?1:0;
            $query->where('leads.on_lease','=', $on_lease);
        }

        if($this->request->has('have_images')){
            $have_images = $this->request->input('have_images');
            $have_images = ($have_images == 'true')?'yes':'no';
            $query->where('leads.have_images', $have_images);
        }



        $ntype = $this->request->input('ntype');

        if(is_array($ntype) && count($ntype)) {
            $query->whereIn('leads.plant_machinery', $ntype);
        }
       
        if((is_array($plant_type) && count($plant_type)) || $this->request->has('portfolio')) {
            $query->whereIn('leads.plant_type_code', $plant_type);
        }

        //$lead_type = null ;
        if($this->request->has('lead_type'))
            $lead_type = $this->request->input('lead_type');

//        else{
//            $query->where(function($q){
//                $q->where('category', '=', 'sell')
//                    ->orWhere('category', '=', 'Sell');
//            });
//        }


        if($this->request->has('search')) {
            $search = $this->request->input('search');

            if (empty($lead_type))
            {
                $pos = strpos($search, "buy:?");
                if ($pos !== false)
                    $lead_type = 'buy';

                $pos = strpos($search, "sell:?");
                if ($pos !== false)
                    $lead_type = 'sell';
            }

            $search = trim($search, "buy:?");
            $search = trim($search, "sell:?");

            $pos = strpos($search, 'tag:') ;
            if( is_bool ($pos) && $pos == false)
            {
                $query->where(function($q) use ($search){
                    // $search = global $search;
                    $q->where('leads.title', 'like', '%'.$search.'%')
                        ->orWhere('leads.offer_detail', 'like', '%'.$search.'%');
                });
            }
            else
            {
                $search = substr($search , 4 ) ;
                $tags = explode(',', $search);
                foreach($tags as $tag)
                {
                    $query->where(function ($q) use ($tag) {
                        $q->where('tags_id' , 'LIKE' , $tag . ',%' ) ;
                        $q->orWhere('tags_id' , 'LIKE' , '%,' . $tag.',%') ;
                        $q->orWhere('tags_id' , 'LIKE' , '%,' . $tag) ;
                    }) ;
                }

            }
        }

        if(!empty($lead_type)) {
            if($lead_type == 'buy'){
                $query->where(function($q){
                    $q->where('leads.category', '=', 'buy')
                        ->orWhere('leads.category', '=', 'Buy');
                });
            }
            elseif($lead_type == 'sell'){
                $query->where(function($q){
                    $q->where('leads.category', '=', 'sell')
                        ->orWhere('leads.category', '=', 'Sell');
                });
            }
        }


        // $query->where('category','=', 'Rent');

        $page_number = 0;
        if($this->request->has('page_number')){
            $page_number = $this->request->input('page_number') - 1;
            if($page_number<0)
            {
                $page_number = 0;
            }
        }

        $limit = $_ENV['PER_PAGE_NUMBER_LIMIT'];
        $offset = $limit * $page_number;

//        $query->offset($offset);
        $query->skip($offset)->take($limit);


        if(!empty($post_from))
        {
            $query->where('leads.id' , '>' , $post_from ) ;
        }

//        $query->whereRaw( $conditions );
        if($most_viewed){
            $query->groupBy('leads.id')->orderBy('total_views', 'desc');
        }else{
            $query->orderBy('leads.id', 'desc');
        }

//        $query->take($limit)->skip($offset);
//        echo $query->toSql() ;

        $data =  $query->get();
//        print_r($data);die;

        $finalData = array();
        if(count($data)) {
            $cityPreArr = array();
            $countryPreArr = array();
            $platTypePreArr = array();
            foreach ($data as $rowPre) {
                if(!$rowPre['id']){
                    unset($rowPre);
                    continue;
                }
                $cityPreArr[] = $rowPre['city_id'];
                $countryPreArr[] = $rowPre['country_id'];
                $platTypePreArr[] = $rowPre['plant_type_code'];

            }
            $cityStateIdArr = $this->cityStateIdArr($cityPreArr);
            $countryArr = $this->countryIdArr($countryPreArr);
            //$planTypePathArr = $this->planTypePathArr($platTypePreArr);
            //print_r($planTypePathArr);
            //die;
            foreach ($data as $row)
            {
                if(!$row['id']) {
                    unset($row);
                    continue;
                }

                $countryid = strval($row['country_id']);
                $cityid = strval($row['city_id']);
                $stateid = strval($row['state_id']);
                $row['country_name'] = isset($countryArr[$countryid]) ? $countryArr[$countryid] : '';
                $row['city_name'] = isset($cityStateIdArr['city'][$cityid]) ? $cityStateIdArr['city'][$cityid] : '';
                $row['state_name'] = isset($cityStateIdArr['state'][$stateid]) ? $cityStateIdArr['state'][$stateid] : '';
				 $row['mobile'] = $row['std_code'].$row['mobile'];
				 
				$row['sold_out_text'] ='';
				if($row['sold_out']==1 ){
					$row['sold_out_text'] = (strtolower($row['category'])=='buy' ) ? ' (Completed)':' (Sold Out)';
					
				}
                /**
                 * Empty fields which user not want to show
                 */
                if (!empty($row['undisclose_col_val']))
                {
                    $undisclose_col_val_arr = array_map('trim',explode(',', $row['undisclose_col_val']) );
                    foreach($undisclose_col_val_arr as $undisclose_col_val)
                    {
                        $row[$undisclose_col_val] = "" ;
                    }
                }

                unset($row['undisclose_col_val']);

                unset($row['user_personal_detail_id']) ;
                unset($row['status']) ;
//                unset($row['state_id']) ;
//                unset($row['city_id']) ;
//                unset($row['country_id']) ;
                unset($row['have_images']) ;
                unset($row['user_status']) ;
                unset($row['verified']) ;

                //$dataArr = $planTypePathArr[$row['plant_type_code']];
                //if($dataArr['parent_cat_code']) {

                //   $pathArr = isset($planTypePathArr[$dataArr['parent_cat_code']])?$planTypePathArr[$dataArr['parent_cat_code']]:array();
                //   $pathArr['chieldplant'] = $dataArr;
                //   if(isset($pathArr['parent_cat_code']))
                //   {
                //$pathArr = $this->getPlantTypePath($planTypePathArr,$pathArr);

                //   }

                //  }
                //  else{

                // $pathArr = $planTypePathArr[$row['plant_type_code']];
                //   }

                // $row['plantTypePath'] = $pathArr;

                /**
                 * Now get lead details of that lead id
                 */
                
				/* comment by mohan on 15/10/18 and recode below this comment
				$dataLead = $result->table('leads_detail')
                    ->where('lead_id','=',$row['id'])
                    ->get();

               for( $i = 0 ; $i< count($dataLead) ; $i++ )
                {
                    if ( $dataLead[$i]['images'] == 1 )
                    {
                        $temp = $result->table('images')
                            ->select('image_url')
                            ->where('table_id' , '=' , $row['id'] )
                            ->get();

                        for($j=0 ; $j< count($temp) ; $j++ )
                        {
                            $temp[$j]['image_url'] = $_ENV['PLANT_IMAGE_SUFFIX']. str_replace(' ', '%20', $temp[$j]['image_url']) ;

                            if(empty($dataLead[$i]['thumb_img']))
                                $dataLead[$i]['thumb_img'] = str_replace('assets/product_img/', 'images/leads/thumb/', $temp[$j]['image_url']);

                            if(empty($row['thumb_img']))
                                $row['thumb_img'] = str_replace('assets/product_img/', 'images/leads/thumb/', $temp[$j]['image_url']);

                            $temp[$j]['image_url'] = str_replace('assets/product_img/', 'images/leads/large/', $temp[$j]['image_url'] );
                        }

                        if(empty($dataLead[$i]['thumb_img']))
                            $dataLead[$i]['thumb_img'] = null;

                        if(empty($row['thumb_img']))
                            $row['thumb_img'] = null;

                        $dataLead[$i]['images'] = $temp ;
                        $dataLead[$i]['id'] = strval($dataLead[$i]['id']);
                        $dataLead[$i]['lead_id'] = strval($dataLead[$i]['lead_id']) ;
                    }
                    else
                    {
                        if(empty($dataLead[$i]['thumb_img']))
                            $dataLead[$i]['thumb_img'] = null;
                        if(empty($row['thumb_img']))
                            $row['thumb_img'] = null;

                        $dataLead[$i]['images'] = array() ;
                    }

                } */
				$dataLead = $result->table('leads_detail')
                    ->where('lead_id','=',$row['id'])
                    ->get();
				$_images =array();
				$_flag_img = false;
				$row['thumb_img'] = null;
				for( $i = 0 ; $i< count($dataLead) ; $i++ )
                {//$dataLead[$i]['images'] == 1 &&
					if (  $_flag_img==false){
						$temp = $result->table('images')
							->select('image_url')
							->where('table_id' , '=' , $row['id'] )
							->get();

						for($j=0 ; $j< count($temp) ; $j++ )
						{
					
							$temp[$j]['image_url'] = $_ENV['PLANT_IMAGE_SUFFIX']. str_replace(' ', '%20', $temp[$j]['image_url']) ;

							if(empty($row['thumb_img']))
								$row['thumb_img'] = str_replace('assets/product_img/', 'images/leads/thumb/', $temp[$j]['image_url']);

							if(!in_array(str_replace('assets/product_img/', 'images/leads/large/',$temp[$j]['image_url']), $_images))
								$_images[$j] = str_replace('assets/product_img/', 'images/leads/large/', $temp[$j]['image_url']);
						}
						
						$_flag_img=true;
						
						$row['images'] = $_images;
					}
					
					$dataLead[$i]['images'] = array();
					$dataLead[$i]['thumb_img'] = null;
					$dataLead[$i]['id'] = strval($dataLead[$i]['id']);
					$dataLead[$i]['lead_id'] = strval($dataLead[$i]['lead_id']) ;
				}
					
                $row['dataLead'] = $dataLead;
                $row['id'] = strval($row['id']);
                $finalData[] = $row;
            }
        }
        return $finalData  ;
    }

    public function getallplanttype( Request $request , $dealtype)
    {
        $result = DB::connection('mysql');

        $data = $result->table('plant_type')
            ->select('plant_type_name as name','plant_type_desc as desc','parent_cat_code','image','plant_type_code')
            // ->where('parent_cat_code','=','')
            ->orderBy('parent_cat_code', 'asc')
            ->orderBy('order_no', 'asc')
            ->orderBy('plant_type_name', 'asc')
            ->get();

        $finalArr =  $this->buildTree($data,'',$dealtype);
        return new JsonResponse(array ( "status#" => "1" , "data#" => $finalArr ) );
    }

    public function getPlanType(Request $request)
    {
        $maxLevel = 0;
        $rows = array();
        $finalArr = array();
        $parent_ids = array();

        $sql = "SELECT p.`plant_type_name` as name, p.`plant_type_desc` as `desc`, p.`parent_cat_code`, p.`image`, p.`plant_type_code`, p.`level`";
        
        $sql .= ", (SELECT COUNT(l.`id`) FROM `leads` l WHERE l.`plant_type_code` = p.`plant_type_code` AND l.`status` = 'approved' AND l.`category` = 'Buy') as total_buy_leads";
        
        $sql .= ", (SELECT COUNT(l.`id`) FROM `leads` l WHERE l.`plant_type_code` = p.`plant_type_code` AND l.`status` = 'approved' AND l.`category` = 'Sell') as total_sell_leads";

        $sql .= " FROM `plant_type` p";

        $sql .= " ORDER BY p.`parent_cat_code` ASC, p.`order_no` ASC, p.`plant_type_name` ASC";

        $results = DB::select($sql);

        if($results) {
            foreach($results as $result) {
                $level = $result['level'];

                unset($result['level']);
                $result['image'] = env('PLANT_IMAGE_SUFFIX') . $result['image'];
                $result['total_leads'] = $result['total_buy_leads'] + $result['total_sell_leads'];

                $rows[$level][$result['plant_type_code']] = $result;

                $parent_ids[$level][$result['parent_cat_code']] = $result['parent_cat_code'];

                if($maxLevel < $level) {
                    $maxLevel = $level;
                }
            }

            while($maxLevel > 1) {
                if(isset($parent_ids[$maxLevel]) && !empty($parent_ids[$maxLevel])) {
                    foreach($parent_ids[$maxLevel] as $key => $val) {
                        $children = array();
                        $total_buy_leads = 0;
                        $total_sell_leads = 0;
                        $total_leads = 0;
                        if(isset($rows[$maxLevel]) && !empty($rows[$maxLevel])) {
                            foreach($rows[$maxLevel] as $row) {
                                if($key == $row['parent_cat_code']) {
                                    $children[] = $row;
                                    $total_buy_leads += $row['total_buy_leads'];
                                    $total_sell_leads += $row['total_sell_leads'];
                                    $total_leads += $row['total_leads'];
                                }
                            }
                        }

                        if($children) {
                            if(isset($rows[($maxLevel - 1)][$key])) {
                                $rows[($maxLevel - 1)][$key]['children'] = $children;
                                $rows[($maxLevel - 1)][$key]['total_buy_leads'] = $total_buy_leads;
                                $rows[($maxLevel - 1)][$key]['total_sell_leads'] = $total_sell_leads;
                                $rows[($maxLevel - 1)][$key]['total_leads'] = $total_leads;
                            }
                        }
                    } 
                }

                $maxLevel--;
            }

            if(isset($rows[1]) && !empty($rows[1])) {
                foreach($rows[1] as $row) {
                    $finalArr[] = $row;
                }
            }
        }

        return new JsonResponse(array ( "status#" => "1" , "data#" => $finalArr ) );
    }

//    public function test()
//    {
//
//
//    }

    private function cal_child_arr()
    {
        $result = DB::connection('mysql');

        $data = $result->table('plant_type')
            ->select('parent_cat_code','plant_type_code')
            // ->where('parent_cat_code','=','')
            ->orderBy('level', 'asc')
            ->get();

        $max_level = $result->table('plant_type')
            ->select(DB::raw("MAX(level) as level "))
            ->first()['level'];


        $this->res = array() ;
        for($i = 0 ; $i<count($data) ; $i ++ )
        {
            if(!empty($data[$i]['parent_cat_code']))
            {
                if(!in_array($data[$i]['plant_type_code'] , $this->res[$data[$i]['parent_cat_code']]))
                    $this->res[$data[$i]['parent_cat_code']][] = $data[$i]['plant_type_code'] ;
            }
        }
        $this->build_Tree_array($this->res , $max_level ) ;

    }

    private function build_Tree_array( &$main , $level )
    {
        if($level < 1 )
            return ;
        foreach( $main as $parent=>$value )
        {
            for($j = 0 ; $j<count($value) ; $j++ )
            {
                if(!empty($main[$value[$j]] ))
                {
                    for($i = 0 ; $i < count($main[$value[$j]]) ; $i++ )
                    {
                        if(!in_array($main[$value[$j]][$i] , $main[$parent] ) )
                            $main[$parent][] = $main[$value[$j]][$i] ;
                    }
                }
            }

        }
        $level -- ;
        $this->build_Tree_array( $main, $level) ;
    }

    /*
         * Get the buildTree
         * TODO
         */
    function buildTree(array $elements, $parentId = '',$dealtype='') {
        $branch = array();

        foreach ($elements as $element) {
            $element = (array)$element;
            $element['image'] = env('PLANT_IMAGE_SUFFIX').$element['image'];
            $element['total_leads'] = $this->totalLeadByPlantType($element['plant_type_code'],$dealtype);
            $total_leads = 0;
            if ($element['parent_cat_code'] == $parentId) {
                $children = $this->buildTree($elements, $element['plant_type_code'],$dealtype);
                if ($children) {
                    $element['children'] = $children;
                    foreach($children as $child){
                        $total_leads = $total_leads + $child['total_leads'];
                    }
                }
                $element['total_leads'] = $element['total_leads'] + $total_leads;
                $branch[] = $element;
            }
        }

        return $branch;
    }

    public function totalLeadByPlantType($plant_type_code,$dealtype='')
    {
        $result = DB::connection('mysql');
        $data = $result->table('leads')
            ->select(DB::raw('count(id) as total_leads'))
            ->where('plant_type_code','=',$plant_type_code);
        $data->where('status','=', 'approved');
        if($dealtype){
            $dealtype = ($dealtype == 'buy')?'buy':'sell';
            $data->where('category','=',$dealtype);
        }

        $dataLast = $data->first();
        return $dataLast['total_leads'];
    }

    /*
	 * Get the getalltags
	 * TODO
	 */
    private function getalltags()
    {

        $result = DB::connection('mysql');

        $data = $result->table('tags')
            ->select("name" , "id")
            ->orderBy('id', 'asc')
            ->get();
        // $cityIdArr = $this->cityIdArr();
        for($i = 0 ; $i<count($data) ; $i++)
            $data[$i]['name'] = trim($data[$i]['name']) ;

        return $data;
    }


    public function cityStateIdArr($cityPreArr = array())
    {
        $r = DB::table('tbl_state_city')
            ->select('city_id','city_name','state_id','state_name');
        if(count($cityPreArr)){
            $r->whereIn('city_id',$cityPreArr);
        }
        $data = $r->get();
        $cityArr = array();
        if(count($data)) {
            foreach ($data as $vr) {
                $citykey = $vr['city_id'];
                $statekey = $vr['state_id'];
                $cityArr['city'][$citykey] = $vr['city_name'];
                $cityArr['state'][$statekey] = $vr['state_name'];
            }
        }
        return $cityArr;
    }


    public function countryIdArr($countryPreArr = array())
    {
        $r = DB::table('tbl_country')
            ->select('id','country');
        if(count($countryPreArr)){
            $r->whereIn('id',$countryPreArr);
        }
        $data = $r->get();
        $countryArr = array();
        if(count($data)) {
            foreach ($data as $vr) {
                $key = $vr['id'];
                $countryArr[$key] = $vr['country'];
            }
        }
        return $countryArr;
    }


    public function planTypePathArr($platTypePreArr)
    {
        $result = DB::connection('mysql');
        $r = $result->table('plant_type as a')
            ->select('a.plant_type_code','a.parent_cat_code','a.plant_type_name','a.plant_type_desc','a.image','a.level');

        if(count($platTypePreArr)){
            //$r->whereIn('plant_type_code',$platTypePreArr)
            //   ->orWhereIn('parent_cat_code',$platTypePreArr);
        }

        $r->orderBy('level', 'asc');
        $items = $r->get();
        $data = array();
        if(count($items))
        {
            foreach ($items as $item) {

                $itemarr = array();
                $itemarr['plant_type_code'] = $item['plant_type_code'];
                $itemarr['parent_cat_code'] = $item['parent_cat_code'];
                $itemarr['plant_type_name'] = $item['plant_type_name'];
                $itemarr['plant_type_desc'] = $item['plant_type_desc'];
                $itemarr['image'] = $item['image'];
                $itemarr['level'] = $item['level'];
                $data[$item['plant_type_code']] = $itemarr;
            }

        }
//print_r($data);die;
        return $data;

    }


    public function getPlantTypePath($planTypePathArr,$cpathArr){
        if($cpathArr['parent_cat_code'])
        {
            $dataArr = isset($planTypePathArr[$cpathArr['parent_cat_code']])?$planTypePathArr[$cpathArr['parent_cat_code']]:array();
            $pathArr = $dataArr['chieldplant'] =  $cpathArr;
            if(isset($dataArr['parent_cat_code']))
            {
                $pathArr = $this->getPlantTypePath($planTypePathArr,$pathArr);
            }

        }
        else {
            $pathArr = $cpathArr;
        }
        return $pathArr;
    }

    /**
     * enquiry on lead
     * @route:	/v1/action/enquiry
     * @return $res_arr: 	Response success
     */
    private function enquiry(){
        $user_id = null ;
        $user = null ;

        if ($this->request->has('token')) {
            $auth = new authentication();
            $token = $this->request->input('token');
            $user_id = $auth->authToken($token);
            if ($user_id) {
                $user = new User($user_id);

            } else
                abort(403, 'Unauthorized action. Token access denied');
        }

		if(
            $this->request->has('lead_id') &&
            $this->request->has('name') &&
            $this->request->has('email') &&
            $this->request->has('mobile') &&
            $this->request->has('country_id') &&
            $this->request->has('comments') )
        {

            $this->temp = $this->request->input('country_id') ;

            $result = DB::table('leads')
                ->select('title' , 'contact_person', 'email_id as seller_email' , 'trial_email', 'category', 'type' )
                ->where('id' , '=' , $this->request->input('lead_id') )
                ->first();

            $data['offer'] = $this->request->input('comments');
            $data['title'] = $result['title'] ;
            $data['fname'] = '' ;
            $data['name'] = $this->request->input('name') ;
            $data['company'] = '' ;

            if($this->request->has('company'))
                $data['company'] = $this->request->input('company');

            $data['email'] = $this->request->input('email');
            $data['mobile'] = $this->request->input('mobile');
            $data['c_id_code'] = DB::table('calling_codes')
                ->select('prefix as c_id_code')
                ->where('comment' , '=' , function($query) {
                    $query->select('country')
                        ->from('tbl_country')
                        ->where('id' , '=' , $this->temp ) ;
                })
                ->first()['c_id_code'] ;

            $data['country_id'] = $this->request->input('country_id') ;
            $data['state_id'] = '' ;

            if($this->request->has('state_id'))
                $data['state_id'] = $this->request->input('state_id') ;

            $data['city_id'] = '' ;

            if($this->request->has('city_id'))
                $data['city_id'] = $this->request->input('city_id') ;

            $data['lead_id'] = $this->request->input('lead_id') ;
            $data['lead_type'] = "leads" ;

//            if( strcasecmp($result['category'], 'Sell' ) == 0 )
//                $data['lead_type'] .= 'selling_' ;
//            elseif ( strcasecmp($result['category'], 'Buy' ) == 0 )
//                $data['lead_type'] .= 'buying_' ;
//            if( strcasecmp($result['type'], 'p' ) == 0 )
//                $data['lead_type'] .= 'plant' ;
//            elseif ( strcasecmp($result['category'], 'm' ) == 0 )
//                $data['lead_type'] .= 'machinery' ;

            $data['datetime'] = $GLOBALS['currDateTime'] ;
            $data['status'] = "pending";
            $data['verified'] = "no";
            $data['free_paid']='';

			if($data["title"] == '') $data["title"] = "";
			if($data["offer"] == '') $data["offer"] = "";
			if($data["company"] == '') $data["company"] = "";
			if($data["state_id"] == '') $data["state_id"] = "";
			if($data["city_id"] == '') $data["city_id"] = "";
			if($data["website"] == '') $data["website"] = "";
			
			if(empty($user_id) || $user_id == null) $user_id = 0;
            $table = array(
                "title" => $data["title"] ,
                "offer" => $data["offer"] ,
                "fname" => $data["fname"] ,
                "name" => $data["name"] ,
                "company" => $data["company"] ,
                "email" => $data["email"] ,
                "mobile" => $data["mobile"] ,
                "country_id" => $data["country_id"] ,
                "state_id" => $data["state_id"] ,
                "city_id" => $data["city_id"] ,
                "website" => "" ,
                "datetime" => $data["datetime"] ,
                "status" => $data["status"] ,
                "verified" => $data["verified"] ,
                "lead_id" => $data["lead_id"] ,
                "lead_type" => $data["lead_type"] ,
                "free_paid" => $data["free_paid"] ,
                "lead_for" => "plantbee" ,
				"memid"=>$user_id
            );



            $sel_eml= $result['seller_email'] ;
            $contact_person=$result['contact_person'] ;
            $trial_email=$result['trial_email'];

            $enquiry_id = DB::table('submit_enquiry')
                ->insert($table);

            if( $trial_email < 2 )
                $this->plantbee_enquiry($data , $sel_eml , $contact_person , $trial_email , 1001 ) ;
            else
                $this->plantbee_enquiry($data , $sel_eml , $contact_person , $trial_email , 1002 ) ;

            return true ;
        }
        else{
            abort(403, 'parameter missing.');
            return false ;
        }
    }

    private function getleaddetail(){
        if(!$this->request->has('lead_id')){
            abort(403, 'Unauthorized action.');
        }



        $result = DB::connection('mysql');
        $lead_id = $this->request->input('lead_id');
        $data = $result->table('leads')
            ->where('id','=',$lead_id)
            ->first();


        $countryid = strval($data['country_id']);
        $cityid = strval($data['city_id']);
        $stateid = strval($data['state_id']);
        $countryArr = $this->countryIdArr(array($countryid));
        $cityStateIdArr = $this->cityStateIdArr(array($cityid));

        $data['country_name'] = isset($countryArr[$countryid]) ? $countryArr[$countryid] : '';
        $data['city_name'] = isset($cityStateIdArr['city'][$cityid]) ? $cityStateIdArr['city'][$cityid] : '';
        $data['state_name'] = isset($cityStateIdArr['state'][$stateid]) ? $cityStateIdArr['state'][$stateid] : '';


        if(count($data))
        {
            $dataLead = $result->table('leads_detail')
                ->where('lead_id','=',$lead_id)
                ->get();
            for( $i = 0 ; $i< count($dataLead) ; $i++ )
            {
                if ( $dataLead[$i]['images'] == 1 )
                {
                    $temp = $result->table('images')
                        ->select('image_url')
                        ->where('table_id' , '=' , $lead_id )
                        ->get();

                    for($j=0 ; $j< count($temp) ; $j++ )
                    {
                        $temp[$j]['image_url'] = $_ENV['PLANT_IMAGE_SUFFIX']. $temp[$j]['image_url'] ;
                    }
                    $dataLead[$i]['images'] = $temp ;
                }
            }
            $data['dataLead'] = $dataLead;

        }

        $this->insertLeadImpression($lead_id);

        return $data;

    }

    private function insertLeadImpression($leadid){
        $result = DB::connection('mysql');
        $particularArr['lead_id'] = $leadid;
        /**
         * For IpAddress
         */
        $ipAddress = $_SERVER['REMOTE_ADDR'];
        if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
            $ipAddress = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
        }
        $particularArr['IP'] = $ipAddress ;
        $particularArr['date'] = date('Y-m-d');
        $result->table('impression')
            ->insertGetId($particularArr);
    }
    public function LeadImpression($leadid)
    {
        $this->insertLeadImpression($leadid);
        return new JsonResponse(array( "status#" => "1" ));
    }

    public function searchfilers(){
        $query = DB::select ('select DISTINCT c.country as country , s.zone as zone
                 from leads lead
                    left join
                    tbl_country c
                    ON lead.country_id = c.id
                    left join
                    tbl_state_city s
                    ON ( lead.state_id = s.state_id) and (lead.city_id = s.city_id )');

        $coutryData = array() ;
        foreach ($query as $rs )
        {
            if(empty($rs["zone"]))
                $coutryData[$rs["country"]] = null ;
            else
                $coutryData[$rs["country"]][$rs["zone"]] = null ;
        }

        $query = array() ;
        foreach( $coutryData as $keys => $values  )
        {
            if(empty($values))
                $query[] = array(
                    "filter" => $keys ,
                ) ;
            else
            {
                $zone = null ;
                foreach( $values as $k => $val )
                {
                    $zone[] = array(
                        "filter" => $k
                    );
                }
                $query[] = array(
                    "filter" => $keys ,
                    "sub_filter" => $zone
                );
            }
        }

//        $query = array() ;
//        foreach ( $coutryData as $keys => $values ) {
//            if(empty($values))
//                $query[] = array(
//                    "filter" => $keys ,
//                ) ;
//            else
//            {
//                $state = array() ;
//                foreach( $values as $key=> $value )
//                {
//                    $temp_city = array() ;
//                    foreach( $value as $city )
//                    {
//                        $temp_city[] = array(
//                            "filter" => $city
//                        ) ;
//                    }
//                    $state[] = array(
//                        "filter" => $key ,
//                        "sub_filter" => $temp_city
//                    ) ;
//                }
//                $query[] = array(
//                    "filter" => $keys ,
//                    "sub_filter" => $state
//                ) ;
//            }
//        }

        $filters[] = array('filter' => 'country','sub_filter' => $query  );
        $filters[] = array('filter' => 'lead_type','sub_filter' => array( [ "filter" => 'buy' ] , [ "filter" => 'sell'] ));

        $filters[] = array('filter' => 'on_rent');
        $filters[] = array('filter' => 'have_images');
        $filters[] = array('filter' => 'most_viewed');
//        $filters[] = array('filter' => 'plant_type', 'sub_filter' => array());
        return new JsonResponse(array ("status#" => "1" , "data#" => $filters ) ) ;
    }

    public function homePageImage()
    {
        $res = array(			
					[                
						"image" => "https://www.plantbee.com/assets/bootstrap/img/Banner_700_400.jpg" ,                
						"click" => ""            
					],
             [
                "image" => "https://www.plantbee.com/assets/bootstrap/img/map_1.jpg" ,
                "click" => ""
            ],
            [
                "image" => "https://www.plantbee.com/assets/bootstrap/img/What-We-Do.jpg",
                "click" => ""
            ],
            [
                "image" => "https://www.plantbee.com/assets/bootstrap/img/How-It-Works.jpg",
                "click" => ""
            ],
            [
                "image" => "https://www.plantbee.com/assets/bootstrap/img/Bee-VS-News.jpg",
                "click" => ""
            ]
        ) ;
        return new JsonResponse( array("status#" => "1" , "data#" => $res ) ) ;
    }

    private function plantbee_enquiry($data,$email, $contact_person,  $trial_email, $id, $_admin_email='support@plantbee.com')
    {
        $to=$email;
        $subject='';
        $message='';
        $rep='';

        $contact_person=$contact_person;
        $title=$data['title'];
        $offer=$data['offer'];

        $name=$data['name'];
        $company_name=$data['company'];
        $RMemail=$data['email'];
        $RMmobile=$data['mobile'];

        if( $id==1002){
            $company_name="xxxxxxxxxxxx";
            $RMemail="xxxxxxxxxxxx";;
            $RMmobile="xxxxxxxxxxxx";;
        }

        $type = $data['lead_type'];
        $tbl = 'leads';
        if($type =='selling_machinery')
            $tbl = 'seller_machinary_detail';
        elseif($type =='selling_plant')
            $tbl = 'seller_plant_detail';
        elseif($type =='buying_machinery')
            $tbl = 'buyer_machinery_detail';
        elseif($type =='buying_plant')
            $tbl = 'buyer_plant_detail';

        /**
         * Update table for trail email
         */
        DB::table($tbl)
            ->where('id' , '=' , $data['lead_id'] )
            ->update( ['trial_email' => $trial_email+1 ]) ;

        /// mail to OWNER OF LEAD

        $res=$res = DB::table('tbl_email_template')
            ->where('id' , '=' , $id )
            ->first() ;

        $subject=$res['sub_txt'];
        $subject.="[Response #".($trial_email+1)."]";
        $message=$res['body_txt'];
        $rep=$res['to_be_replace'];
        $exp=explode(',',$rep);
        for($i=0;$i<count($exp);$i++){
            $find_str='%recipient.'.$exp[$i].'%';
            $message=str_replace($find_str,$$exp[$i],$message);
        }
        //echo $message;
        //echo $to;
		ob_start();
        require_once("/home/steelmin/public_html/mf.php");
		if($to != '') {
	        sendSMMail( $message , $to, $to_name="", $subject , $attachment='' , 'support@plantbee.com' );
		}
		ob_end_clean();
//        $this->sentinal->mail_to_user($to.','.$_admin_email,$subject,$message);

        //MAIL TO USER
        $res = DB::table('tbl_email_template')
            ->where('id' , '=' , 1005 )
            ->first() ;

        $subject=$res['sub_txt'];
        $message=$res['body_txt'];
        $rep=$res['to_be_replace'];
        //$exp=explode(',',$rep);

        $res = DB::table('leads')
            ->select('contact_person' , 'designation' , 'email_id' , 'mobile')
            ->where('id' , '=' , $data['lead_id'])
            ->first();

        $contact_person = $res['contact_person'] ;
        $designation = $res['designation'] ;
        $email_id = $res['email_id'] ;
        $mobile = $res['mobile'] ;

        //contact_person,title,offer,name,company_name,RMemail,RMmobile
        $message=str_replace('%recipient.name%',$data['name'],$message);
        $message=str_replace('%recipient.title%',$data['title'],$message);
        $message=str_replace('%recipient.offer%',$data['offer'],$message);

        $message=str_replace('%recipient.contact_person%',$contact_person,$message);
        $message=str_replace('%recipient.designation%',$designation,$message);
        $message=str_replace('%recipient.RMemail%',$email_id,$message);
        $message=str_replace('%recipient.RMmobile%',$mobile,$message);

//        $this->sentinal->mail_to_user($to=$data['email'],$subject,$message);

        require_once("/home/steelmin/public_html/mf.php");
        sendSMMail($message, $data['email'] , $to_name="", $subject );

    }
}
