<?php
namespace App\Http\Controllers\API;
error_reporting(-1);
ini_set('display_errors', 'On');
use Illuminate\Http\Request;
ini_set('max_execution_time', 0);
use App\Http\Controllers\Controller;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
use Auth;
use Session;
use validate;
use Sentinel;
use Response;
use Validator;
use DB;
use DataTables;
use App\Models\User;
use App\Models\Category;
use App\Models\Subcategory;
use App\Models\Token;
use App\Models\Resetpassword;
use App\Models\Package;
use App\Models\Package_FRQ;
use App\Models\Parameter;
use App\Models\FamilyMember;
use App\Models\Profiles;
use App\Models\TestDetails;
use App\Models\UserAddress;
use App\Models\Review;
use App\Models\Popular_package;
use App\Models\Setting;
use App\Models\Orders;
use App\Models\OrdersData;
use App\Models\PaymentGateway;
use App\Models\CartMember;
use App\Models\Feedback;
use App\Models\About;
use Hash;
use Mail;
use Illuminate\Support\Carbon;
class ApiController extends Controller
{

    public function add_all_reviews(){
        $user_arr = array(3,4,5,6);
        $review = array(
            "The quality of your report and your results made it easy to identify potential problems.",
            "The extractable organics GC/MS work was well documented, the best I have seen from a commercial lab.",
            "Very good just what you need every important test covered",
            "I have had nothing but wonderful service from them. I would highly recommend them and I would hire them again.",
            "it was a good value for the money!"
        );
        $str = array(5,4);

        $getallproduct = Profiles::all();

        foreach($getallproduct as $g){
            for($i=0;$i<4;$i++){
                $random_users = array_rand($user_arr,1);
                //echo $random_users;exit;
                $random_str =array_rand($str,1);
                $random_review =array_rand($review,1);
                $data = new Review();
                $data->user_id = $user_arr[$random_users];
                $data->type = '2';
                $data->type_id = $g->id;
                $data->ratting = $str[$random_str];
                $data->description = $review[$random_review];
                $data->date = $this->getsitedate();
                $data->save();
            }                
        }

        echo "done";

    }

    public function post_register(Request $request)
    {
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['password' => 'required', 'email' => 'required|unique:users', 'name' => 'required', 'token' => 'required', 'phone' => 'required', 'type' => 'required'];

        $messages = array(
            'password.required' => "password is required",
            'email.required' => 'Email is required',
            'name.required' => 'name is required',
            'email.unique' => 'Email Already exist',
            'token.required' => "token are required",
            'phone.required' => "phone are required",
            'type.required' => "type are required"
        );

        $validator = Validator::make($request->all() , $rules, $messages);

        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            $getemail = User::where("email", $request->get("email"))
                ->first();
            if (isset($getemail))
            {
                $response['status'] = "0";
                $response['msg'] = "Email id Already Exist";
            }
            $inset = new User();
            $inset->name = $request->get("name");
            $inset->password = Hash::make($request->get("password"));
            $inset->email = $request->get("email");
            $inset->phone = $request->get("phone");
            $inset->save();
            $gettoken = Token::where("token", $request->get("token"))
                ->first();
            if ($gettoken)
            {
                $store = Token::where("token", $request->get("token"))
                    ->update(["user_id" => $inset->id]);
            }
            else
            {
                $store = new Token();
                $store->token = $request->get("token");
                $store->type = $request->get("type");
                $store->user_id = $inset->id;
                $store->save();
            }
            $response['status'] = "1";
            $response['msg'] = "User Register Successfully";
            $response['register'] = array(
                "user_id" => $inset->id,
                "name" => $request->get("name") ,
                "email" => $inset->email,
                "phone" => $inset->phone
            );

        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function post_login(Request $request)
    {
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['login_type' => 'required', 'token' => 'required', 'token_type' => 'required'];
        if ($request->input('login_type') == '1')
        {
            $rules['password'] = 'required';
            $rules['email'] = 'required';
        }
        if ($request->input('login_type') == '2' || $request->input('login_type') == '3')
        {
            $rules['name'] = 'required';
            $rules['soical_id'] = 'required';
        }

        $messages = array(
            'login_type.required' => "login_type is required",
            'token.required' => "token is required",
            'token_type.required' => "token_type is required",
            'email.required' => "email is required",
            'password.required' => "password is required",
            "name.required" => "name is required",
            "soical_id.required" => "soical_id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            if ($request->input('login_type') == '1')
            {
                $user = User::where("email", $request->get("email"))
                    ->where("user_type", '3')
                    ->first();
                   
                if ($user)
                {
                    if (Hash::check($request->get("password") , $user->password))
                    {
                        $gettoken = Token::where("token", $request->get("token"))
                            ->first();
                        if (!$gettoken)
                        {
                            $store = new Token();
                            $store->token = $request->get("token");
                            $store->type = $request->get("token_type");
                            $store->user_id = $user->id;
                            $store->save();
                        }
                        else
                        {
                            $gettoken->user_id = $user->id;
                            $gettoken->save();
                        }
                        $user->login_type = $request->get("login_type");
                        $user->save();
                        if ($user->profile_pic != "")
                        {
                            $image = asset("storage/app/public/profile") . '/' . $user->profile_pic;
                        }
                        else
                        {
                            $image = asset("public/upload/profile/profile.png");
                        }
                        $response['status'] = "1";
                        $response['headers'] = array(
                            'Access-Control-Allow-Origin' => '*'
                        );
                        $response['msg'] = "Login Successfully";
                        $response['register'] = array(
                            "user_id" => $user->id,
                            "name" => $user->name,
                            "phone" => $user->phone,
                            "email" => $user->email,
                            "profile_pic" => $image
                        );
                    }
                    else
                    {
                        $response = array(
                            "status" => 0,
                            "msg" => "Paaword Are Wrong"
                        );
                    }

                }
                else
                {
                    $response = array(
                        "status" => 0,
                        "msg" => "User Not Found"
                    );
                }
            }
            if ($request->input('login_type') == '2' || $request->input('login_type') == '3')
            {
                $checkuser = User::where("email", $request->get("email"))
                    ->first();
                if ($checkuser)
                {
                    $gettoken = Token::where("token", $request->get("token"))
                        ->first();
                    if (!$gettoken)
                    {
                        $store = new Token();
                        $store->token = $request->get("token");
                        $store->type = $request->get("token_type");
                        $store->user_id = $checkuser->id;
                        $store->save();
                    }
                    else
                    {
                        $gettoken->user_id = $checkuser->id;
                        $gettoken->save();
                    }

                    $checkuser->login_type = $request->input('login_type');
                    $checkuser->soical_id = $request->get('soical_id');
                    $checkuser->save();
                    $imgdata = $checkuser->profile_pic;
                    $png_url = "";
                    if ($request->get("image") != "")
                    {
                        $png_url = "profile-" . mt_rand(100000, 999999) . ".png";
                        $path = storage_path() . '/app/public/profile/' . $png_url;
                        $content = $this->file_get_contents_curl($request->get("image"));
                        $savefile = fopen($path, 'w');
                        fwrite($savefile, $content);
                        fclose($savefile);
                        $img = storage_path() . '/app/public/profile/' . $png_url;
                        $checkuser->login_type = $request->get("login_type");
                        $checkuser->profile_pic = $png_url;
                        $checkuser->save();
                    }
                    if ($imgdata != $png_url && $imgdata != "")
                    {
                        $image_path = storage_path() . "/app/public/profile/" . $imgdata;
                        if (file_exists($image_path) && $imgdata != "")
                        {
                            try
                            {
                                unlink($image_path);
                            }
                            catch(Exception $e)
                            {
                            }
                        }
                    }

                    if ($checkuser->profile_pic != "")
                    {
                        $image = asset("storage/app/public/profile") . '/' . $checkuser->profile_pic;
                    }
                    else
                    {
                        $image = asset("public/upload/profile/profile.png");
                    }
                    $response['status'] = "1";
                    $response['headers'] = array(
                        'Access-Control-Allow-Origin' => '*'
                    );
                    $response['msg'] = "Login Successfully";
                    $response['register'] = array(
                        "user_id" => $checkuser->id,
                        "name" => $checkuser->name,
                        "phone" => $checkuser->phone,
                        "email" => $checkuser->email,
                        "profile_pic" => $image
                    );
                }
                else
                {
                    $str = explode(" ", $request->get("name"));
                    $store = new User();
                    $store->name = $str[0];
                    $store->email = $request->get("email");
                    $store->login_type = $request->get("login_type");
                    $store->soical_id = $request->get('soical_id');
                    $store->phone = $request->get("phone");
                    if ($request->get("image") != "")
                    {
                        $png_url = "profile-" . mt_rand(100000, 999999) . ".png";
                        $path = storage_path() . '/app/public/profile/' . $png_url;
                        $content = $this->file_get_contents_curl($request->get("image"));
                        $savefile = fopen($path, 'w');
                        fwrite($savefile, $content);
                        fclose($savefile);
                        $img = storage_path() . '/app/public/profile/' . $png_url;
                        $getuser->profile_pic = $png_url;
                    }
                    $store->save();
                    if ($store->profile_pic != "")
                    {
                        $image = storage_path() . '/app/public/profile' . '/' . $store->profile_pic;
                    }
                    else
                    {
                        $image = asset("public/upload/profile/profile.png");
                    }
                    $gettoken = Token::where("token", $request->get("token"))
                        ->first();
                    if (!$gettoken)
                    {
                        $store = new Token();
                        $store->token = $request->get("token");
                        $store->type = $request->get("token_type");
                        $store->user_id = $store->id;
                        $store->save();
                    }
                    else
                    {
                        $gettoken->user_id = $store->id;
                        $gettoken->save();
                    }
                    $response['status'] = "1";
                    $response['headers'] = array(
                        'Access-Control-Allow-Origin' => '*'
                    );
                    $response['msg'] = "Login Successfully";
                    $response['register'] = array(
                        "user_id" => $store->id,
                        "name" => $store->name,
                        "phone" => $store->phone,
                        "email" => $store->email,
                        "profile_pic" => $image
                    );
                }
            }
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function file_get_contents_curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

    public function get_category(Request $request)
    {
        $getcategory = Subcategory::select('id', 'name', 'image', 'short_desc')->where("is_deleted", '0')
            ->get();
        foreach ($getcategory as $g)
        {
            $g->image = asset('storage/app/public/Subcategory') . '/' . $g->image;
        }
        $response = array(
            "status" => 1,
            "msg" => "Get Category List",
            "data" => $getcategory
        );
        return json_encode($response, JSON_NUMERIC_CHECK);
    }
    public function serach_category(Request $request)
    {
        
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['term' => 'required'];
        $messages = array(
            'term.required' => "term is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            $getcategory = Subcategory::select('id', 'name', 'image', 'short_desc')->where("is_deleted", '0')->where('name', 'like', '%' . $request->get("term") . '%' )
                ->get();
            foreach ($getcategory as $g)
            {
                $g->image = asset('storage/app/public/Subcategory') . '/' . $g->image;
            }
            $response = array(
                "status" => 1,
                "msg" => "Get Category List",
                "data" => $getcategory
            );
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function post_savetoken(Request $request)
    {
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['token' => 'required', 'type' => 'required'];
        $messages = array(
            'token.required' => "token is required",
            'type.required' => "type is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            if ($request->get("token") != "" && $request->get("type") != "" && $request->get("token") != "null")
            {
                $store = new Token();
                $store->token = $request->get("token");
                $store->type = $request->get("type");
                $store->save();
                $response = array(
                    "status" => 1,
                    "msg" => "Token Save Successfully",
                    "data" => $store
                );
            }
            else
            {
                $response = array(
                    "status" => 0,
                    "msg" => "Fields is Required"
                );
            }
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function forgotpassword(Request $request)
    {
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['email' => 'required'];

        $messages = array(
            'email.required' => "email is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {

            $checkmobile = User::where("email", $request->get("email"))
                ->first();

            if ($checkmobile)
            {
                $code = mt_rand(100000, 999999);
                $store = array();
                $store['email'] = $checkmobile->email;
                $store['name'] = $checkmobile->name;
                $store['code'] = $code;
                $add = new Resetpassword();
                $add->user_id = $checkmobile->id;
                $add->code = $code;
                $add->save();
                try
                {
                    Mail::send('email.forgotpassword', ['user' => $store], function ($message) use ($store)
                    {
                        $message->to($store['email'], $store['name'])->subject(__('message.site_name'));
                    });
                }
                catch(\Exception $e)
                {
                }
                $response['status'] = "1";
                $response['msg'] = "Mail Send Successfully";
            }
            else
            {
                $response['status'] = "0";
                $response['msg'] = "Email Not Found";

            }

        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function get_category_detail(Request $request)
    {
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['cat_id' => 'required'];

        $messages = array(
            'cat_id.required' => "cat_id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            $getcategory = Subcategory::find($request->get("cat_id"));
            if ($getcategory)
            {
                    $getcategory->image = asset('storage/app/public/Subcategory') . '/' . $getcategory->image;
                    $data1 = Package::where("category_id",$request->get("cat_id"))->whereNull('deleted_at')->orderby('id','desc')->limit(5)->get();
                    $data2 = Profiles::where("category_id",$request->get("cat_id"))->whereNull('deleted_at')->get();
                    $data3 = Parameter::where("category_id",$request->get("cat_id"))->whereNull('deleted_at')->get();
                    $ls = array();
                    foreach($data1 as $d1){
                        $find_pa = TestDetails::where("package_id",$d1->id)->get();
                        $parameter = 0;
                        $ls1 = array();
                        foreach($find_pa as $d){
                            if($d->type==1){
                                $ls1[] = Parameter::find($d->package_id)?Parameter::find($d->package_id)->name:'';
                                $parameter = $parameter+1;
                            }
                            if($d->type==2){
                                $a = Profiles::find($d->package_id);
                                if($a){
                                    $arr = explode(",",$a->no_of_parameter);
                                    foreach($arr as $l){
                                        $ls1[] = Parameter::find($l)?Parameter::find($l)->name:'';
                                    }
                                    $parameter = $parameter+count($arr);
                                }
                            }
                        }
                        $a = array();
                        $a['id'] = $d1->id;
                        $a['name'] = $d1->name;
                        $a['mrp'] = number_format($d1->mrp,2,'.','');
                        $a['price'] = number_format($d1->price,2,'.','');
                        $total = 100 * ($d1->mrp - $d1->price) / $d1->mrp;
                        $a['discount'] = number_format($total,'2','.','');
                        $a['type'] = '3';
                        $a['no_of_parameter'] = $parameter;
                        $a['parameter_list'] = array_slice($ls1, 0, 4);
                        $ls[] = $a;
                    }
                    foreach($data3 as $d1){
                        $a = array();
                        $a['id'] = $d1->id;
                        $a['name'] = $d1->name;
                        $a['mrp'] = number_format($d1->mrp,2,'.','');
                        $a['price'] = number_format($d1->price,2,'.','');
                        $total = 100 * ($d1->mrp - $d1->price) / $d1->mrp;
                        $a['discount'] = number_format($total,'2','.','');
                        $a['type'] = '2';
                        $a['no_of_parameter'] = 1;
                        $a['parameter_list'] = array($d1->name);                        
                        $ls[] = $a;                        
                    }
                    foreach($data2 as $d1){

                        $arr = explode(",",$d1->no_of_parameter);                    
                        $i=0;
                        $ls1 = array();
                        foreach($arr as $a){
                            if($i<=3){
                                $ls1[] = Parameter::find($a)?Parameter::find($a)->name:'';
                            }$i++;                        
                        }
                        
                        $a = array();
                        $a['id'] = $d1->id;
                        $a['name'] = $d1->profile_name;
                        $a['mrp'] = number_format($d1->mrp,2,'.','');
                        $a['price'] = number_format($d1->price,2,'.','');
                        $total = 100 * ($d1->mrp - $d1->price) / $d1->mrp;
                        $a['discount'] = number_format($total,'2','.','');
                        $a['type'] = '2';
                        $a['no_of_parameter'] = count($arr);
                        $a['parameter_list'] = $ls1;
                        $ls[] = $a;

                    }
                    $page = 1;
                    if($request->get('page')){
                        $page = $request->get('page');
                    }
                    $getcategory->package_detail = $this->paginate($ls,5,$page);
                    $getcategory->currency = Setting::find(1)?Setting::find(1)->currency:'';
                $response['status'] = "1";
                $response['msg'] = "Category Detail Get Successfully";
                $response['data'] = $getcategory;
            }
            else
            {
                $response['status'] = "0";
                $response['msg'] = "Category Not Found";

            }
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }


    public function paginate($items, $perPage = 5, $page = null, $options = [])
    {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof Collection ? $items : Collection::make($items);
        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    }


    public function package_detail(Request $request)
    {
        $response = array(
            "status" => 0,
            "msg" => "Validation error"
        );
        $rules = ['id' => 'required'];

        $messages = array(
            'id.required' => "id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            $package = Package::find($request->get("id"));
           
            if ($package)
            {
                    $find_pa = TestDetails::where("package_id",$package->id)->get();
                    $parameter = 0;
                    $ls1 = array();
                        foreach($find_pa as $d){
                            if($d->type==1){
                                $a  = array();
                                $a['name'] = Parameter::find($d->type_id)?Parameter::find($d->type_id)->name:'';
                                $a['id'] = Parameter::find($d->type_id)?Parameter::find($d->type_id)->id:'';
                                $a['type'] = '2';
                                $a['parameter'] = array();
                                $parameter = $parameter+1;
                                $ls1[] = $a;
                            }
                            if($d->type==2){
                                $a = Profiles::find($d->type_id);
                                if($a){
                                    $a1  = array();
                                    $a1['name'] = $a->profile_name;
                                    $a1['id'] = $a->id;
                                    $a1['type'] = '3';
                                    $k = array();
                                    $arr = explode(",",$a->no_of_parameter);
                                    foreach($arr as $l){
                                        $c= array();
                                        $c['name'] = Parameter::find($l)?Parameter::find($l)->name:'';
                                        $c['id'] = $l;
                                        $k [] = $c;
                                    }
                                    $a1['parameter'] = $k;
                                    $ls1[] = $a1;
                                    $parameter = $parameter+count($arr);
                                }
                            }
                        }   
                    $package->no_of_parameter = $parameter;
                    $package->parameter_list = $ls1;
                    if(!empty($package->paramter_included)){
                       
                        $package->paramter_included = $package->paramter_included;
                    }else{
                        $package->paramter_included = "";
                    }
                    if(!empty($package->sample_collection_fee)){
                       
                        $package->sample_collection_fee = $package->sample_collection_fee;
                    }else{
                        $package->sample_collection_fee = "";
                    }
                    if(!empty($package->fast_time)){
                       
                        $package->fast_time = $package->fast_time;
                    }else{
                        $package->fast_time = "";
                    }
                    if(!empty($package->realted_package)){
                       
                        $package->realted_package = $package->realted_package;
                    }else{
                        $package->realted_package = "";
                    }
                     if(!empty($package->deleted_at)){
                       
                        $package->deleted_at = $package->deleted_at;
                    }else{
                        $package->deleted_at = "";
                    }
                    
                    $package->frqlist = Package_FRQ::select('question','ans')->where("package_id",$package->id)->where("type",'1')->get();
                    $package->review = Review::select('user_id','ratting','date','description')->where("type",'1')->where("type_id",$package->id)->get();
                    foreach($package->review as $r){
                        $r->username = User::find($r->user_id)?User::find($r->user_id)->name:'';
                        $r->profile_pic = User::find($r->user_id)?User::find($r->user_id)->profile_pic:'';
                    }
                    $total = 100 * ($package->mrp - $package->price) / $package->mrp;
                    $package->discount = number_format($total,'2','.','');
                    $package->totalreview = count(Review::with('userdata')->where("type",'1')->where("type_id",$package->id)->get());
                    $package->avgreview = (string)Review::where("type",'1')->where("type_id",$package->id)->avg('ratting');
                    $response['status'] = 1;
                    $response['msg'] = "Package Detail Get Successfully";
                    $response['data'] = $package;
            }
            else
            {
                $response['status'] = 0;
                $response['msg'] = "Package Not Found";

            }
        }
        return json_encode($response);
    }


     public function profile_detail(Request $request)
    {
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['id' => 'required'];

        $messages = array(
            'id.required' => "id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            $package = Profiles::find($request->get("id"));
            if ($package)
            {
                    $find_pa = TestDetails::where("package_id",$package->id)->get();
                    $arr = explode(",",$package->no_of_parameter); 
                    $ls = array();                   
                    $i=0;
                    foreach($arr as $a){   
                            $k = array();                     
                            $k['name'] = Parameter::find($a)?Parameter::find($a)->name:'';
                            $k['id'] = $a;
                            $ls[] = $k;    
                    } 
                    $package->no_of_parameter = count($arr);
                    $package->parameter_list = $ls;
                    $package->frqlist = Package_FRQ::select('question','ans')->where("package_id",$package->id)->where("type",'3')->get();
                    $package->review = Review::select('user_id','ratting','date','description')->where("type",'3')->where("type_id",$package->id)->get();
                    foreach($package->review as $r){
                        $r->username = User::find($r->user_id)?User::find($r->user_id)->name:'';
                        $r->profile_pic = User::find($r->user_id)?User::find($r->user_id)->profile_pic:'';
                    }
                     $total = 100 * ($package->mrp - $package->price) / $package->mrp;
                        $package->discount = number_format($total,'2','.','');
                    $package->totalreview = count(Review::with('userdata')->where("type",'3')->where("type_id",$package->id)->get());
                    $package->avgreview = Review::where("type",'3')->where("type_id",$package->id)->avg('ratting');
                    $response['status'] = "1";
                    $response['msg'] = "Profile Detail Get Successfully";
                    $response['data'] = $package;
            }
            else
            {
                $response['status'] = "0";
                $response['msg'] = "Profile Not Found";

            }
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function parameter_detail(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['id' => 'required'];

        $messages = array(
            'id.required' => "id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            $package = Parameter::find($request->get("id"));
            if ($package)
            {                    
                    $package->frqlist = Package_FRQ::select('question','ans')->where("package_id",$package->id)->where("type",'3')->get();
                    $package->review = Review::select('user_id','ratting','date','description')->where("type",'3')->where("type_id",$package->id)->get();
                    foreach($package->review as $r){
                        $r->username = User::find($r->user_id)?User::find($r->user_id)->name:'';
                        $r->profile_pic = User::find($r->user_id)?User::find($r->user_id)->profile_pic:'';
                    }
                     $total = 100 * ($package->mrp - $package->price) / $package->mrp;
                        $package->discount = number_format($total,'2','.','');
                    $package->totalreview = count(Review::with('userdata')->where("type",'3')->where("type_id",$package->id)->get());
                    $package->avgreview = Review::where("type",'3')->where("type_id",$package->id)->avg('ratting');
                    $response['status'] = "1";
                    $response['msg'] = "Parameter Detail Get Successfully";
                    $response['data'] = $package;
            }
            else
            {
                $response['status'] = "0";
                $response['msg'] = "Parameter Not Found";

            }
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function get_popular_package_list(){
        $popular = Popular_package::all();
        if(count($popular)>0){
            foreach ($popular as $p) {
            if($p->type==1){ //package
                $ls = array();
                $pa_data = Package::find($p->type_id);
                $find_pa = TestDetails::where("package_id",$p->type_id)->get();
                $parameter = 0;
                foreach($find_pa as $d){
                    if($d->type==1){
                        $ls[] = Parameter::find($d->package_id)?Parameter::find($d->package_id)->name:'';
                        $parameter = $parameter+1;
                    }
                    if($d->type==2){
                        $a = Profiles::find($d->package_id);
                        if($a){
                            $arr = explode(",",$a->no_of_parameter);
                            foreach($arr as $l){
                                $ls[] = Parameter::find($l)?Parameter::find($l)->name:'';
                            }
                            $parameter = $parameter+count($arr);
                        }
                    }
                }

                $p->no_of_parameter = $parameter;
                $p->paramater_data = array_slice($ls, 0, 4);
                $p->mrp = $pa_data->mrp;
                $p->price = $pa_data->price;
                $total = 100 * ($p->mrp - $p->price) / $p->mrp;
                $p->discount = round($total);
            }else if($p->type==2){ //parameters
              $ls = array();
              $ls[] = Parameter::find($p->type_id)?Parameter::find($p->type_id)->name:'';
              $p->paramater_data = $ls;
              $p->no_of_parameter = 1;
              $p->mrp = Parameter::find($p->type_id)?Parameter::find($p->type_id)->mrp:'';
              $p->price = Parameter::find($p->type_id)?Parameter::find($p->type_id)->price:'';
              $total = 100 * ($p->mrp - $p->price) / $p->mrp;
                $p->discount = round($total);
            }else{ //profiles
                $data = Profiles::find($p->type_id);                
                $ls = array();
                if($data){
                    $arr = explode(",",$data->no_of_parameter);                    
                    $i=0;
                    foreach($arr as $a){
                        if($i<=3){
                            $ls[] = Parameter::find($a)?Parameter::find($a)->name:'';
                        }$i++;                        
                    }
                    $p->paramater_data = $ls;
                    $p->no_of_parameter = count($arr);
                }
                
                $p->mrp = Profiles::find($p->type_id)?Profiles::find($p->type_id)->mrp:'';
                $p->price = Profiles::find($p->type_id)?Profiles::find($p->type_id)->price:'';
                $total = 100 * ($p->mrp - $p->price) / $p->mrp;
                $p->discount = round($total);
            }
        }
            $response = array(
                "status" => 1,
                "msg" => "Get Popular List",
                "data" => $popular
            );
        }else{
            $response = array(
                "status" => 0,
                "msg" => "Popular List Not Found"
            );
        }
        
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function save_member(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = [
            'id' => 'required',
            'user_id' => 'required',
            'name' => 'required',
            'mobile_no' => 'required',
            'age' => 'required',
            'email' => 'required',
            'dob' => 'required',
            'relation' => 'required',
            'gender' => 'required'
        ];

        $messages = array(
            'id.required' => "id is required",
            'user_id.required' => "user_id is required",
            'name.required' => "name is required",
            'mobile_no.required' => "mobile_no is required",
            'age.required' => "age is required",
            'email.required' => "email is required",
            'dob.required' => "dob is required",
            'relation.required' => "relation is required",
            'gender.required' => "gender is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {   
            if($request->get("id")==0){
                $store = new FamilyMember();
                $msg = "Member Add Successfully";
            }else{
                $store = FamilyMember::find($request->get("id"));
                if(empty($store)){
                        $response['status'] = "0";
                        $response['msg'] = "Member Not Found";
                }
                 $msg = "Member Update Successfully";               
            }

            $store->name = $request->get("name");
            $store->mobile_no = $request->get("mobile_no");
            $store->age = $request->get("age");
            $store->email = $request->get("email");
            $store->dob = $request->get("dob");
            $store->relation = $request->get("relation");
            $store->gender = $request->get("gender");
            $store->user_id = $request->get("user_id");
            $store->save();
            $response['status'] = "1";
            $response['msg'] = $msg;
            $response['data'] = $store;
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function delete_member(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['id' => 'required'];

        $messages = array(
            'id.required' => "id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            $data = FamilyMember::find($request->get("id"));
            if ($data)
            {      
                $data->delete();
                $response['status'] = "1";
                $response['msg'] = "Member Delete Successfully";
            }
            else
            {
                $response['status'] = "0";
                $response['msg'] = "Member Not Found";
            }
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function get_member_list(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['id' => 'required'];

        $messages = array(
            'id.required' => "id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            $data = FamilyMember::where("user_id",$request->get("id"))->wherenull('deleted_at')->get();
            if (count($data)>0)
            {  
                $response['status'] = "1";
                $response['msg'] = "Member Get Successfully";
                $response['data'] = $data;
            }
            else
            {
                $response['status'] = "0";
                $response['msg'] = "Member Not Found";
            }
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function save_address(Request $request){
          $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = [
            'id' => 'required',
            'user_id' => 'required',
            'name' => 'required',
            'house_no' => 'required',
            'pincode' => 'required',
            'city' => 'required',
            'state' => 'required',
            'address' => 'required',
            'lat' => 'required',
            'long' => 'required'
        ];

        $messages = array(
            'id.required' => "id is required",
            'user_id.required' => "user_id is required",
            'name.required' => "name is required",
            'house_no.required' => "house_no is required",
            'pincode.required' => "pincode is required",
            'state.required' => "state is required",
            'address.required' => "address is required",
            'lat.required' => "lat is required",
            'long.required' => "long is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {   
            if($request->get("id")==0){
                $store = new UserAddress();
                $msg = "Address Add Successfully";
            }else{
                $store = UserAddress::find($request->get("id"));
                if(empty($store)){
                        $response['status'] = "0";
                        $response['msg'] = "Address Not Found";
                        return json_encode($response, JSON_NUMERIC_CHECK);
                }
                 $msg = "Address Update Successfully";               
            }

            $store->name = $request->get("name");
            $store->user_id = $request->get("user_id");
            $store->house_no = $request->get("house_no");
            $store->pincode = $request->get("pincode");
            $store->city = $request->get("city");
            $store->address = $request->get("address");
            $store->state = $request->get("state");
            $store->lat = $request->get("lat");
            $store->long = $request->get("long");
            $store->phone = $request->get("phone_no");
            $store->save();
            if($request->get("is_default")==1){
                    UserAddress::where("user_id",$request->get("user_id"))->update(['is_default'=>0]);
                    $store->is_default = '1';
                    $store->save();
            }else{
                $store->is_default = '0';
                $store->save();
            }
           
            $response['status'] = "1";
            $response['msg'] = $msg;
            $response['data'] = $store;
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function getaddress(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['id' => 'required'];

        $messages = array(
            'id.required' => "id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            $data = UserAddress::where("user_id",$request->get("id"))->wherenull('deleted_at')->get();
            if (count($data)>0)
            {  
                $response['status'] = "1";
                $response['msg'] = "Addresses Get Successfully";
                $response['data'] = $data;
            }
            else
            {
                $response['status'] = "0";
                $response['msg'] = "Address Not Found";
            }
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function delete_address(Request $request){
$response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = ['id' => 'required'];

        $messages = array(
            'id.required' => "id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {
            $data = UserAddress::find($request->get("id"));
            if ($data)
            {      
                $data->delete();
                $response['status'] = "1";
                $response['msg'] = "Address Delete Successfully";
            }
            else
            {
                $response['status'] = "0";
                $response['msg'] = "Address Not Found";
            }
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }


    public function booknow(Request $request){

        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = [
            'user_id' => 'required',
            'sample_collection_address_id' => 'required',
            'date' => 'required',
            'time' => 'required',
            'payment_method' => 'required',
            'subtotal' => 'required',
            'tax' => 'required',
            'final_total' => 'required',
            'test_json' => 'required'
        ];
        // if($request->input('payment_method')=="braintree"){
        //     $rules['payment_method_nonce'] = 'required';
        // }

        if($request->input('payment_method')=="stripe"){
            $rules['stripeToken'] = 'required';
        }

        $messages = array(
            'user_id.required' => "user_id is required",
            'sample_collection_address_id.required' => "sample_collection_address_id is required",
            'date.required' => "date is required",
            'time.required' => "time is required",
            'payment_method.required' => "payment_method is required",
            'subtotal.required' => "subtotal is required",
            'tax.required' => "tax is required",
            'final_total.required' => "final_total is required",
            'test_json.required' => "test_json is required",
            'payment_method_nonce.required' => "payment_method_nonce is required",
            'stripeToken.required' => "stripeToken is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {   
            $getallkeys = PaymentGateway::all();
            $ls = array();
            foreach($getallkeys as $g){
                $ls[$g->payment_gateway_name."_".$g->key_name] = $g->meta_value;
            }
          
            $setting=Setting::find(1);

            if($request->get("payment_method")=="cod"  || $request->get("payment_method")=="stripe"){
                //echo "hey";exit;
            DB::beginTransaction();      
            try {
                            $store = new Orders();
                            $store->user_id = $request->get("user_id");
                            $store->sample_collection_address_id = $request->get("sample_collection_address_id");
                            $store->date = $request->get("date");
                            $store->time = $request->get("time");
                            $store->payment_method = $request->get("payment_method");
                            if($request->get("payment_method")=="stripe"){
                                $store->token = $request->get("stripeToken");
                            }else{
                                $store->token = '';
                            }
                            $store->subtotal = $request->get("subtotal");
                            $store->tax = $request->get("tax");
                            $store->final_total = $request->get("final_total");
                            $store->status = 1;
                            // $store->orderplace_date = $this->getsitedate();
                              $store->orderplace_date = Carbon::now();
                            $store->save();
                            $jsondata = json_decode($request->get("test_json"));
                            foreach($jsondata->Testdata as $jt){
                                foreach($jt->items as $ji){
                                        if($ji->type==1){
                                            $item_data = Package::find($ji->id);
                                        }else if($ji->type==2){
                                            $item_data = Parameter::find($ji->id);
                                        }else{
                                            $item_data = Profiles::find($ji->id);
                                            if($item_data){
                                                $item_data->name = $item_data->profile_name;
                                            }
                                        }
                                        $data = new OrdersData();
                                        $data->order_id = $store->id;
                                        $data->member_id = $jt->member_id;
                                        $data->item_id = $ji->id;
                                        $data->type = $ji->type;
                                        $data->item_name = isset($item_data->name)?$item_data->name:'';
                                        $data->parameter = $ji->parameter;
                                        $data->mrp = isset($item_data->mrp)?$item_data->mrp:'';
                                        $data->price = isset($item_data->mrp)?$item_data->mrp:'';
                                        $data->save();
                                }
                            }
                            CartMember::where("user_id",$request->get("user_id"))->delete();
                            DB::commit();                            
                            $getuseraddress = UserAddress::find($store->sample_collection_address_id);
                            if($getuseraddress){
                                 $getmanager = User::where("user_type","2")->where("city",$getuseraddress->city)->get();
                                 foreach($getmanager as $gm){
                                    $gm->order_notification = $gm->order_notification+1;
                                    $gm->save();
                                    $data1 = array();
                                    $data1['email']=$gm->email;
                                    $data1['msg']= "You Get New Booking For Test";
                                    $data1['order_id']=$store->id;
                                    $data1['customer_name'] = User::find($data->user_id)?User::find($data->user_id)->name:'';
                                    $data1['manager_name'] = $gm->name;
                                    try {
                                            $result=Mail::send('email.order_status', ['user' => $data1], function($message) use ($data1){
                                                    $message->to($data1['email'],$data1['manager_name'])->subject(__('message.site_name')); 
                                            });
                                    } catch (\Exception $e) {
                                    } 
                                 }
                            }
                            $msg = "Test Booked Successfully";
                            $android = $this->send_notification_order_android($setting->android_server_key,$store->user_id,$msg,$store->id);
                            
                            $ios = $this->send_notification_order_ios($setting->ios_server_key,$store->user_id,$msg,$store->id);
                            $response['status'] = "1";
                            $response['msg'] = "Test Book Successfully";
                            $response['data'] = $store->id;
                    }catch (\Exception $e) {
                           // DB::rollback();
                            $response['status'] = "0";
                            $response['msg'] = $e;
                    }
        }
            if($request->get("payment_method")=="braintree"){
                
                  
                            $store = new Orders();
                            $store->user_id = $request->get("user_id");
                            $store->sample_collection_address_id = $request->get("sample_collection_address_id");
                            $store->date = $request->get("date");
                            $store->time = $request->get("time");
                            $store->payment_method = $request->get("payment_method");
                           
                            $store->subtotal = $request->get("subtotal");
                            $store->tax = $request->get("tax");
                            $store->final_total = $request->get("final_total");
                            $store->status = 1;
                            $store->orderplace_date = $this->getsitedate();
                            $store->is_completed = 0;
                            $store->save();
                            $jsondata = json_decode($request->get("test_json"));
                            foreach($jsondata->Testdata as $jt){
                                foreach($jt->items as $ji){
                                        if($ji->type==1){
                                            $item_data = Package::find($ji->id);
                                        }else if($ji->type==2){
                                            $item_data = Parameter::find($ji->id);
                                        }else{
                                            $item_data = Profiles::find($ji->id);
                                            if($item_data){
                                                $item_data->name = $item_data->profile_name;
                                            }
                                        }
                                        $data = new OrdersData();
                                        $data->order_id = $store->id;
                                        $data->member_id = $jt->member_id;
                                        $data->item_id = $ji->id;
                                        $data->type = $ji->type;
                                        $data->item_name = isset($item_data->name)?$item_data->name:'';
                                        $data->parameter = $ji->parameter;
                                        $data->mrp = isset($item_data->mrp)?$item_data->mrp:'';
                                        $data->price = isset($item_data->mrp)?$item_data->mrp:'';
                                        $data->save();
                                }
                            }
                            CartMember::where("user_id",$request->get("user_id"))->delete();                          
                                              
                            $getuseraddress = UserAddress::find($store->sample_collection_address_id);
                            if($getuseraddress){
                                 $getmanager = User::where("user_type","2")->where("city",$getuseraddress->city)->get();
                                 foreach($getmanager as $gm){
                                    $gm->order_notification = $gm->order_notification+1;
                                    $gm->save();
                                    $data1 = array();
                                    $data1['email']=$gm->email;
                                    $data1['msg']= "You Get New Booking For Test";
                                    $data1['order_id']=$store->id;
                                    $data1['customer_name'] = User::find($data->user_id)?User::find($data->user_id)->name:'';
                                    $data1['manager_name'] = $gm->name;
                                    try {
                                            $result=Mail::send('email.order_status', ['user' => $data1], function($message) use ($data1){
                                                    $message->to($data1['email'],$data1['manager_name'])->subject(__('message.site_name')); 
                                            });
                                    } catch (\Exception $e) {
                                    } 
                                 }
                            }
                    
                            $msg = "Test Booked Successfully";
                            // $android = $this->send_notification_order_android($setting->android_server_key,$store->user_id,$msg,$store->id);
                            // $ios = $this->send_notification_order_ios($setting->ios_server_key,$store->user_id,$msg,$store->id);
                            $response['status'] = "1";
                            $response['msg'] = "Test Book Successfully";
                            $response['data'] = $store->id;
            }
            if($request->get("payment_method")=="paystack"){
            DB::beginTransaction();      
            try {
                    $store = new Orders();
                    $store->user_id = $request->get("user_id");
                    $store->sample_collection_address_id = $request->get("sample_collection_address_id");
                    $store->date = $request->get("date");
                    $store->time = $request->get("time");
                    $store->payment_method = $request->get("payment_method");
                    
                    $store->subtotal = $request->get("subtotal");
                    $store->tax = $request->get("tax");
                    $store->final_total = $request->get("final_total");
                    $store->orderplace_date = $this->getsitedate();
                    $store->status = 1;
                    $store->is_completed = 0;
                    $store->save();
                    $jsondata = json_decode($request->get("test_json"));
                    foreach($jsondata->Testdata as $jt){
                        foreach($jt->items as $ji){
                                if($ji->type==1){
                                    $item_data = Package::find($ji->id);
                                }else if($ji->type==2){
                                    $item_data = Parameter::find($ji->id);
                                }else{
                                    $item_data = Profiles::find($ji->id);
                                    if($item_data){
                                        $item_data->name = $item_data->profile_name;
                                    }
                                }
                                $data = new OrdersData();
                                $data->order_id = $store->id;
                                $data->member_id = $jt->member_id;
                                $data->item_id = $ji->id;
                                $data->type = $ji->type;
                                $data->item_name = isset($item_data->name)?$item_data->name:'';
                                $data->parameter = $ji->parameter;
                                $data->mrp = isset($item_data->mrp)?$item_data->mrp:'';
                                $data->price = isset($item_data->mrp)?$item_data->mrp:'';
                                $data->save();
                        }
                    }
                    CartMember::where("user_id",$request->get("user_id"))->delete();
                    DB::commit();
                    $getuseraddress = UserAddress::find($store->sample_collection_address_id);
                    if($getuseraddress){
                         $getmanager = User::where("user_type","2")->where("city",$getuseraddress->city)->get();
                         foreach($getmanager as $gm){
                            $gm->order_notification = $gm->order_notification+1;
                            $gm->save();
                            $data1 = array();
                            $data1['email']=$gm->email;
                            $data1['msg']= "You Get New Booking For Test";
                            $data1['order_id']=$store->id;
                            $data1['customer_name'] = User::find($data->user_id)?User::find($data->user_id)->name:'';
                            $data1['manager_name'] = $gm->name;
                            try {
                                    $result=Mail::send('email.order_status', ['user' => $data1], function($message) use ($data1){
                                            $message->to($data1['email'],$data1['manager_name'])->subject(__('message.site_name')); 
                                    });
                            } catch (\Exception $e) {
                            } 
                         }
                    }

                    // $msg = "Test Booked Successfully";
                    // $android = $this->send_notification_order_android($setting->android_server_key,$store->user_id,$msg,$store->id);
                    // $ios = $this->send_notification_order_ios($setting->ios_server_key,$store->user_id,$msg,$store->id);
                    $response['status'] = "1";
                    $response['msg'] = "Test Book Successfully";
                    $response['data'] = $store->id;

            } catch (\Exception $e) {
                    DB::rollback();
                    $response['status'] = "0";
                     $response['msg'] = "Something Getting Worng";
            }
        }
            
      }
      return json_encode($response, JSON_NUMERIC_CHECK);
    }
    
    public function send_notification_order_android($key,$user_id,$msg,$id){
          $getuser=Token::where("type",1)->where('user_id',$user_id)->get();
          if(count($getuser)!=0){               
               $reg_id = array();
               foreach($getuser as $gt){
                   $reg_id[]=$gt->token;
               }
               $registrationIds =  $reg_id;    
               $message = array(
                    'message' => $msg,
                    'key'=>'Booking',
                    'title' => 'Booking Successfull',
                    'order_id'=>$id
                );
                
               $fields = array(
                  'registration_ids'  => $registrationIds,
                  'data'              => $message
               );

               $url = 'https://fcm.googleapis.com/fcm/send';
               $headers = array(
                 'Authorization: key='.$key,// . $api_key,
                 'Content-Type: application/json'
               );
              
              $json =  json_encode($fields);   
              try {
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$json);
                    $result = curl_exec($ch);  

                    if ($result === FALSE){
                       die('Curl failed: ' . curl_error($ch));
                    }     
                   curl_close($ch);
                   $response=json_decode($result,true); 
                  } catch (\Exception $e) {
                    return 0;
                 }
                 
             if(isset($response)&&$response['success']>0)
              {
                   return 1;
              }
            else
               {
                  return 0;
               }
            }
            return 0;
    }
   
    public function send_notification_order_ios($key,$user_id,$msg,$id){
          $getuser=Token::where("type",2)->where('user_id',$user_id)->get();
          if(count($getuser)!=0){               
               $reg_id = array();
               foreach($getuser as $gt){
                   $reg_id[]=$gt->token;
               }
               $registrationIds =  $reg_id;    
               $message = array(
                    'message' => $msg,
                    'key'=>'Booking',
                    'title' => 'Booking Successfull',
                    'order_id'=>$id
                );
               $fields = array(
                  'registration_ids'  => $registrationIds,
                  'data'              => $message
               );

               $url = 'https://fcm.googleapis.com/fcm/send';
               $headers = array(
                 'Authorization: key='.$key,// . $api_key,
                 'Content-Type: application/json'
               );
              $json =  json_encode($fields);   
              try {
                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_POSTFIELDS,$json);
                    $result = curl_exec($ch);  

                    if ($result === FALSE){
                       die('Curl failed: ' . curl_error($ch));
                    }     
                   curl_close($ch);
                   $response=json_decode($result,true); 
                  } catch (\Exception $e) {
                    return 0;
                 }
                 
             if(isset($response)&&$response['success']>0)
              {
                   return 1;
              }
            else
               {
                  return 0;
               }
            }
            return 0;
    }
    
    public function edit_profile(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = [
            'id' => 'required',
            'name' => 'required',
            'email' => 'required',
            'phone' => 'required'
        ];

        $messages = array(
            'id.required' => "id is required",
            'name.required' => "name is required",
            'email.required' => "email is required",
            'phone.required' => "phone is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {   
            $update = User::find($request->get("id"));
            if($update){
                $getemail = User::where("email",$request->get("email"))->where("id","!=",$request->get("id"))->where("user_type",2)->first();
                if(empty($getemail)){
                    $update->email = $request->get("email");
                    $update->name = $request->get("name");
                    $update->phone = $request->get("phone");
                    if($request->file("image")){
                        
                       $file = $request->file('image');
                       $filename = $file->getClientOriginalName();
                       $extension = $file->getClientOriginalExtension() ?: 'png';
                       $folderName=Storage_path("app/public/profile/"); 
                       $picture = rand().time() . '.' . $extension;
                       //$picture = str_random(10).time().'.'.$extension;
                       //$destinationPath = public_path() . $folderName;
                       $request->file('image')->move($folderName, $picture);
                        $image_path = Storage_path() ."/app/public/profile/".$update->profile_pic;
                              if(file_exists($image_path)&&$update->image!="") {
                                  try {
                                       unlink($image_path);
                                  }
                                  catch(Exception $e) {
                                    
                                  }                        
                              }
                        $update->profile_pic =$picture;
                    }
                    $update->save();
                    $response['status'] = "1";
                    $response['msg'] = "Profile Update Successfully";
                    $response['data'] = $update;
                }else{
                    $response['status'] = "0";
                    $response['msg'] = "Email Already Exist";
                }
                
            }else{
                $response['status'] = "0";
                $response['msg'] = "Profile Not Found";
            }
           
            
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }
    public function add_review(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = [
            'user_id' => 'required',
            'type' => 'required',
            'type_id' => 'required',
            'ratting' => 'required',
            'description' => 'required'
        ];

        $messages = array(
            'user_id.required' => "user_id is required",
            'type.required' => "type is required",
            'type_id.required' => "type_id is required",
            'ratting.required' => "ratting is required",
            'description.required' => "description is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {   
                $data = new Review();
                $data->user_id = $request->get("user_id");
                $data->type = $request->get("type");
                $data->type_id = $request->get("type_id");
                $data->ratting = $request->get("rating");
                $data->description = $request->get("description");
                $data->date = $this->getsitedate();
                $data->save();
                $response['status'] = "1";
                $response['msg'] = "Review Add Successfully";
                $response['data'] = $data;
                
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }
    

    public function add_feedback(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = [
            'user_id' => 'required',
            'order_id' => 'required',
            'ratting' => 'required',
            'description' => 'required'
        ];

        $messages = array(
            'user_id.required' => "user_id is required",
            'order_id.required' => "order_id is required",
            'ratting.required' => "ratting is required",
            'description.required' => "description is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {   
                $data = new Feedback();
                $data->user_id = $request->get("user_id");
                $data->order_id = $request->get("order_id");
                $data->ratting = $request->get("ratting");
                $data->description = $request->get("description");
                $data->date = $this->getsitedate();
                $data->save();
                $response['status'] = "1";
                $response['msg'] = "Feedback Save Successfully";
                $response['data'] = $data;
                
        }
        return json_encode($response, JSON_NUMERIC_CHECK);
    }

    public function update_cart(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = [
            'user_id' => 'required',
            'member_id' => 'required',
            'type_id' => 'required',
            'type' => 'required',
            'parameter'=>'required',
            'action'=>'required'
        ];

        $messages = array(
            'user_id.required' => "user_id is required",
            'member_id.required' => "member_id is required",
            'type_id.required' => "type_id is required",
            'type.required' => "type is required",
            'parameter.required' => "parameter is required",
            'action.required' => "action is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {   
              if($request->get("action")==0){
                  $ls = explode(",",$request->get("member_id"));
                  foreach($ls as $l){
                        $data = new CartMember();
                        $data->user_id = $request->get("user_id");
                        $data->family_member_id = $l;
                        $data->type_id = $request->get("type_id");
                        $data->type = $request->get("type");
                        $data->parameter = $request->get("parameter");
                        $data->save();
                  }
                   
                    $response['status'] = "1";
                    $response['msg'] = "CartMember Save Successfully";
              }else{ // delete
                $ls = explode(",",$request->get("member_id"));
                  foreach($ls as $l){
                    CartMember::where("user_id",$request->get("user_id"))->where("family_member_id",$l)->where("type_id",$request->get("type_id"))->where("type",$request->get("type"))->delete();
                  }
                    $response['status'] = "1";
                    $response['msg'] = "Cart Delete Successfully";
              }              
                
        }
        return json_encode($response, JSON_NUMERIC_CHECK);    
    }

    public function get_cart(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = [
            'user_id' => 'required'
        ];

        $messages = array(
            'user_id.required' => "user_id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {   
             $data=DB::table('cart_member')
                 ->select('cart_member.family_member_id')
                 ->join('family_member', 'family_member.id', '=', 'cart_member.family_member_id')    
                 ->where("cart_member.user_id",$request->get("user_id"))             
                 ->groupBy('cart_member.family_member_id') 
                 ->get();
                 $getdefaultaddress = array();
                 
              $setting = Setting::find(1);
              $getdefaultaddress = UserAddress::where("is_default",'1')->where('user_id',$request->get("user_id"))->first();
              if(empty($getdefaultaddress)){
                     $getdefaultaddress = array();
                 }
              if(count($data)>0){
                    $ls = array();
                    foreach($data as $g){
                        $arr = array();
                        $getfamilyinfo = FamilyMember::find($g->family_member_id);
                        $arr['member_id'] = $g->family_member_id;
                        $arr['member_name'] = isset($getfamilyinfo->name)?$getfamilyinfo->name:'';
                        $arr['relation'] = isset($getfamilyinfo->relation)?$getfamilyinfo->relation:'';
                        $arr['gender'] = isset($getfamilyinfo->gender)?$getfamilyinfo->gender:'';
                        $arr['age'] = isset($getfamilyinfo->age)?$getfamilyinfo->age:'';
                        $getcartinfo = CartMember::where("user_id",$request->get("user_id"))->where("family_member_id",$g->family_member_id)->get();
                        foreach($getcartinfo as $g){
                            $b = array();
                            if($g->type==1){
                                $item_data = Package::find($g->type_id);
                            }else if($g->type==2){
                                $item_data = Parameter::find($g->type_id);
                            }else{
                                $item_data = Profiles::find($g->type_id);
                                if($item_data){
                                    $item_data->name = $item_data->profile_name;
                                }
                            }
                            $b['test_name'] = isset($item_data->name)?$item_data->name:'';
                            $b['mrp'] = isset($item_data->mrp)?$item_data->mrp:'';
                            $b['price']= isset($item_data->price)?$item_data->price:'';
                            $b['parameter']=$g->parameter;
                            $b['type']=$g->type;
                            $b['type_id']=$g->type_id;
                            $arr['testdata'][]=$b;
                        }
                        $ls[] = $arr;
                    }
                    
                    $getdefaultaddress = UserAddress::where("is_default",'1')->where('user_id',$request->get("user_id"))->first();
                    
                    $response['status'] = '1';
                    $response['msg'] = "Cart Data";
                    $response['data'] = array("cart"=>$ls,"txt"=>$setting->txt_charge,"default_address"=>$getdefaultaddress);
              }else{
                  $response['status'] = '0';
                  $response['msg'] = "Cart is empty";
                  $response['data'] = array("cart"=>array(),"txt"=>$setting->txt_charge,"default_address"=>$getdefaultaddress);
              }        
                
        }
        return json_encode($response, JSON_NUMERIC_CHECK); 
    }

    public function book_detail(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = [
            'order_id' => 'required'
        ];

        $messages = array(
            'order_id.required' => "order_id is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {  
            $get_order = Orders::with("useraddressdetails")->find($request->get("order_id"));
            if($get_order){
                $get_order->phone = User::find($get_order->user_id)?User::find($get_order->user_id)->phone:'';
                $data=DB::table('orders_data')
                         ->select('orders_data.member_id')
                         ->join('family_member', 'family_member.id', '=', 'orders_data.member_id')    
                         ->where("orders_data.order_id",$request->get("order_id"))             
                         ->groupBy('orders_data.member_id') 
                         ->get();
                $ls = array();
                foreach($data as $g){
                        $arr = array();
                        $getfamilyinfo = FamilyMember::find($g->member_id);
                        $arr['member_id'] = $g->member_id;
                        $arr['member_name'] = isset($getfamilyinfo->name)?$getfamilyinfo->name:"";
                        $arr['relation'] = isset($getfamilyinfo->relation)?$getfamilyinfo->relation:'';
                        $arr['gender'] = isset($getfamilyinfo->gender)?$getfamilyinfo->gender:'';
                        $arr['age'] = isset($getfamilyinfo->age)?$getfamilyinfo->age:'';
                        $getcartinfo = OrdersData::where("order_id",$request->get("order_id"))->where("member_id",$g->member_id)->get();
                        foreach($getcartinfo as $g){
                            $b = array();
                            if($g->type==1){
                                $item_data = Package::find($g->item_id);
                            }else if($g->type==2){
                                $item_data = Parameter::find($g->item_id);
                            }else{
                                $item_data = Profiles::find($g->item_id);
                                if($item_data){
                                    $item_data->name = $item_data->profile_name;
                                }
                            }
                            $b['test_name'] = isset($item_data->name)?$item_data->name:'';
                            $b['mrp'] = isset($item_data->mrp)?$item_data->mrp:'';
                            $b['price']= isset($item_data->price)?$item_data->price:'';
                            $b['parameter']=$g->parameter;
                            $b['type']=$g->type;
                            $b['type_id']=$g->item_id;
                            $arr['testdata'][]=$b;
                        }
                        $ls[] = $arr;
                    }
                    $get_order->orderdata = $ls;
                $response['status'] = '1';
                $response['msg'] = "Order Detail Get Successfully";
                $response['data'] = $get_order;
            }else{
                $response['status'] = '0';
                $response['msg'] = "Order Not Found";
            }
                
        }
        return json_encode($response, JSON_NUMERIC_CHECK); 
    }
    public function get_city(Request $request)
    {
        $city_data=DB::table('city')->select('city.id','city.name')->orderBy("city.id", 'DESC')->get();


        if(count($city_data)>0)
        {
             $response = array(
                "status" => 1,
                "msg" => "Get City List",
                "data" => $city_data
            );
        }
        else
        {
            $response = array(
                "status" => 0,
                "msg" => "No Data Found",
            );
        }
        
       
        return json_encode($response, JSON_NUMERIC_CHECK);
    }
    
    
    
    public function book_filter(Request $request){
        $response = array(
            "status" => "0",
            "msg" => "Validation error"
        );
        $rules = [
            'user_id' => 'required',
            'status'=>'required'
        ];

        $messages = array(
            'user_id.required' => "user_id is required",
            'status.required' => "status is required"
        );
        $validator = Validator::make($request->all() , $rules, $messages);
        if ($validator->fails())
        {
            $message = '';
            $messages_l = json_decode(json_encode($validator->messages()) , true);
            foreach ($messages_l as $msg)
            {
                $message .= $msg[0] . ", ";
            }
            $response['msg'] = $message;
        }
        else
        {   
            //echo $this->getsitedateonly();exit;
               if($request->get("status")==2){//pending
                    $data=Orders::select('id','payment_method','date','time','final_total','status')->where("user_id",$request->get("user_id"))->wherein("status",[1,2,5,6])->where("is_completed",1)->orderBy('id','DESC')->paginate(10);
               }else if($request->get("status")==3){//complete
                    $data=Orders::select('id','payment_method','date','time','final_total','status')->where("user_id",$request->get("user_id"))->where("status",7)->where("is_completed",1)->orderBy('id','DESC')->paginate(10);
               }else if($request->get("status")==4){//reject
                    $data=Orders::select('id','payment_method','date','time','final_total','status')->where("user_id",$request->get("user_id"))->wherein("status",[3,4])->where("is_completed",1)->orderBy('id','DESC')->paginate(10);
               }else{//all
                   $data=Orders::select('id','payment_method','date','time','final_total','status')->where("user_id",$request->get("user_id"))->where("is_completed",1)->orderBy('id','DESC')->paginate(10);
               }
                
            

            if($data){
                $response['status'] = '1';
                $response['msg'] = "Order List Get Successfully";
                $response['data'] = $data;
            }else{
                $response['status'] = '0';
                $response['msg'] = "Data Not Found";
            }
            
            
                
        }
        return json_encode($response, JSON_NUMERIC_CHECK); 
    }
    
    
    public function about(){
        $data=About::find(1);
        if($data){
              $response['status']= 1;
              $response['msg']="About List";
              $response['data']=$data;
              
          }else{
               $data3 =array();
               $response['status']= 0;
               $response['message']="Data Not Found";
               $response['data'] = $data;               
          }
        return Response::json($response);
   }
   
   public function privecy(){
       $data=About::find(1);
       unset($data->privacy);
        unset($data->about);
        unset($data->data_deletion);
       if($data){
              $response['status']= 1;
              $response['msg']="Terms And Condition List";
              $response['data']=$data;
              
          }else{
               $data3 =array();
               $response['status']= 0;
               $response['message']="Data Not Found";
               $response['data'] = $data;               
          }
        return Response::json($response);
   }
   
   
   public function delete_user(Request $request){
    $response = array(
                "status" => "0",
                "msg" => "Validation error"
            );
            $rules = ['id' => 'required'];

            $messages = array(
                'id.required' => "id is required"
            );
            $validator = Validator::make($request->all() , $rules, $messages);
            if ($validator->fails())
            {
                $message = '';
                $messages_l = json_decode(json_encode($validator->messages()) , true);
                foreach ($messages_l as $msg)
                {
                    $message .= $msg[0] . ", ";
                }
                $response['msg'] = $message;
            }
            else
            {
                $data = User::where("user_type", '3')->where("id", $request->get("id"))->first();
                if ($data)
                {
                    $data->delete();
                    $response['status'] = "1";
                    $response['msg'] = "User Delete Successfully";
                }
                else
                {
                    $response['status'] = "0";
                    $response['msg'] = "User Not Found";
                }
            }
            return json_encode($response, JSON_NUMERIC_CHECK);
        }
        

}

