<?php

namespace App\Http\Controllers\Api\v1;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use App\Feedback;
use App\EmailTemplate;
use App\ManagerPlan;
use App\SubscriptionPlans;
use App\Employee;
use App\Http;
use App\User;
use App\Organization;
use App\EmailQueue;
use App\Coupon;
use App\Manager;
use App\Branch;
use App\Http\Controllers\Api\v1\ModifyUrlController;
use App\Http\Controllers\Api\v1\SMSController;


/**
 * FeedbackController Class Doc Comment
 *
 * @category Class
 * @package  Api
 * @author   Ketan Patel - ketan.patel@brainvire.com
 *
 */
class FeedbackController extends Controller
{

    public function __construct()
    {

        //$this->middleware('oauth', ['except' => ['index']]);
        //$this->middleware('auth:api', ['except' => ['saveMedia', 'showAsset', 'save']]);


    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function adminDashboard()
    {
        $helperObj = new \App\CommonHelper();
        $dateformat = env("DATE_FORMAT");
        $timeformat = env("TIME_FORMAT");

        // get five recent feedbacks of employee
        $subscriptions = DB::table('manager_plans as mp')
            ->select('u.name as manager_name', 'u.email', 'u.mobile', 'sp.validity', 'sp.name as plan_name', 'sp.price', 'mp.activated_at', 'mp.expire_on')
            ->leftJoin('subscription_plans as sp', 'sp.id', '=', 'mp.plan_id')
            ->leftJoin('users as u', 'u.id', '=', 'mp.manager_id')
            ->where('mp.status', '=', 'current')
            ->where('mp.status', '!=', 'deleted')
            ->where('u.deleted_at',null)
            ->take(5)->orderBy('mp.id', 'desc')
            ->get();
        foreach ($subscriptions as $key => $val) {
            $subscriptions[$key]->activated_at = $helperObj->convertDateByFormat($val->activated_at, $dateformat);
            $subscriptions[$key]->expire_on = $helperObj->convertDateByFormat($val->expire_on, $dateformat);
        }
        // get five recent feedbacks of employee
        $empFeedbacks = DB::table('employees as em')
            ->select('u.id as user_id', 'u.name as employee_name', 'org.name as organisazion', 'em.feedback', 'em.feedback_on', 'u.status as status')
            ->leftJoin('users as u', 'u.id', '=', 'em.user_id')
            ->leftJoin('organizations as org', 'em.organization_id', '=', 'org.id')
            ->where('em.feedback', '!=', null)
            ->where('em.feedback', '!=', '')
            ->where('em.status', '!=', 'deleted')
            ->where('u.status', 1)
            ->where('u.deleted_at',null)    
            ->take(5)->orderBy('em.feedback_on', 'desc')
            ->get();

        
        foreach($empFeedbacks as $key => $val){
            $empFeedbacks[$key]->feedback_on = $helperObj->convertDateByFormat($val->feedback_on, $dateformat);
        }
        // Get the total feedbacks for the employee
        //$feedbackResults = Employee::leftjoin()->where('feedback', '!=', '');
        $feedbackResults = DB::table('employees as em')
            ->select('u.id as user_id', 'u.name as employee_name', 'em.feedback', 'em.feedback_on', 'u.status as status')
            ->leftJoin('users as u', 'u.id', '=', 'em.user_id')
            ->where('em.feedback', '!=', null)
            ->where('em.feedback', '!=', '')
            ->where('em.status', '!=', 'deleted')
            ->where('u.deleted_at',null)     
            ->where('u.status', 1)
            ->get();

        $totalFeedbackCount = $feedbackResults->count();

        // Get the total business
        $avgRating = count(User::all()->where('role', '=', 'ROLE_MANAGER'));

        // Get the net revenue
        $netRevenue = round(ManagerPlan::where('status', '!=', 'canceled')->where('status', '!=', 'deleted')->get()->sum('final_price'), 1);

        // get the number of subscription plans
        $plansResults = ManagerPlan::all()->where('status', '=', 'current');
        $totalPlanCount = $plansResults->count();

        $reponseArray = array(
            'subscription_count' => $totalPlanCount,
            'average_rating' => $avgRating,
            'net_revenue' => $netRevenue,
            'total_feedback' => $totalFeedbackCount,
            'subscription_orders' => $subscriptions,
            'feedbacks' => $empFeedbacks
        );

        return response()->json($reponseArray);
    }

    /**
     * get revenue for dashboard
     *
     * @return \Illuminate\Http\Response
     */
    public function getRevenue(Request $request)
    {
        if ($request->type == "yearly") {
            $year = $request->year;
            $revenue = ManagerPlan::where('status', '!=', 'canceled')->where('status', '!=', 'deleted');
            $revenue = $revenue->where(DB::raw('YEAR(created_at)'), '=', $year);
            $revenue = $revenue->get()->sum('final_price');
            $revenue = round($revenue, 1);
        } else {
            $from_year = $request->from_year;
            $from_month = $request->from_month;
            $to_year = $request->to_year;
            $to_month = $request->to_month;
            $months = $this->getMonthList($from_year, $from_month, $to_year, $to_month);
            if (!empty($months)) {
                $revenue = $this->calculate_revenue($months);
            } else {
                return response()->json(['status' => 'fail', 'message' => 'No correct month selected']);
            }
        }
        return response()->json(array('revenue' => $revenue));
    }
    /**
     * Calculate revenue for month
     *
     * @return \Illuminate\Http\Response
     */
    public function calculate_revenue($months)
    {
        $all_month_revenue = array();
        foreach ($months as $key => $val) {
            $revenue = ManagerPlan::where('status', '!=', 'canceled')->where('status', '!=', 'deleted');
            $revenue = $revenue->where('created_at', 'like', "$val%");
            $revenue = $revenue->get()->sum('final_price');
            $revenue = round($revenue, 1);
            $date = date_create($val);
            $all_month_revenue[$key]['month'] = date_format($date, "F Y");
            $all_month_revenue[$key]['revenue'] = $revenue;
        }
        return $all_month_revenue;
    }

    /**
     * get total Send link by user (manager or employee)
     *
     * @return \Illuminate\Http\Response
     */
    public function totalLink($user_id)
    {
        $total_link = count(Feedback::where('user_id', $user_id)->get());
        return response()->json(array('total_link' => $total_link));
    }
    /**
     * get total Send link by organization
     *
     * @return \Illuminate\Http\Response
     */

    public function totalsendLinkByOrg($org_id)
    {
        $total_link_sent = 0;
        $total_link_clicked = 0;
        $feedback = Feedback::select('id')->where('organization_id', $org_id)->get();
        $total_link_sent += count($feedback);
        foreach ($feedback as $k => $v) {
            $feedback = DB::table('feedback_send_link_log')
                ->where('feedback_id', $v->id)
                ->first();
            if (!empty($feedback)) {
                $total_link_clicked += $feedback->is_clicked_count;
            }
        }
        return response()->json(array('total_link_sent' => $total_link_sent, 'total_link_clicked' => $total_link_clicked));
    }
    /**
     * get list of month
     *
     * @return \Illuminate\Http\Response
     */
    public function getMonthList($start_year, $start_month, $end_year, $end_month)
    {
        $month = [];
        for ($i = $start_year; $i <= $end_year; $i++) {
            for ($m = 1; $m <= 12; $m++) {
                if ($i == $start_year) {
                    if ($m < $start_month) {
                        continue;
                    }
                }
                if ($i == $end_year) {
                    if ($m > $end_month) {
                        break;
                    }
                }
                $month[] = date('Y-m', mktime(0, 0, 0, $m, 1, $i));
            }
        }
        return $month;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $this->validate($request, [
            'organization_id' => 'required',
            'manager_id' => 'required',
        ]);

        $managerId = $request->manager_id;
        $organizationId = $request->organization_id;
        $baseUrl = url();
        $helperobj = new \App\CommonHelper();
        $docUrl = $helperobj->publicPath();
        $dateformat = env("DATE_FORMAT");
        $timeformat = env("TIME_FORMAT");
        $feedbacks = array();

        $results = Feedback::select('id', 'customer_name', 'mobile', 'profile_pic', 'feedback', 'rating', 'email', 'created')
            ->where('feedback', '!=', null)
            ->where('feedback', '!=', '')
            ->where('organization_id', $organizationId)->take(5)->orderBy('id', 'desc')->get();

        foreach ($results as $key => $value) {
            $feedbacks[$key]['id'] = $value['id'];
            $feedbacks[$key]['customer_name'] = $value['customer_name'];
            $feedbacks[$key]['mobile'] = $value['mobile'];
            $feedbacks[$key]['feedback'] = $value['feedback'];
            $feedbacks[$key]['rating'] = $value['rating'];
            $feedbacks[$key]['email'] = $value['email'];
            $feedbacks[$key]['created'] = $helperobj->convertDateByFormat($value['created'], $dateformat . ' ' . $timeformat);

            $docpath = $docUrl . '/customers/' . $value['id'] . '/' . $value['profile_pic'];
            $webpath = $baseUrl . '/customers/' . $value['id'] . '/' . $value['profile_pic'];

            if ($value['profile_pic'] != '' && file_exists($docpath)) {
                $feedbacks[$key]['profile_path'] = $webpath;
            } else {
                $feedbacks[$key]['profile_path'] = $baseUrl . '/default-profile.png';
            }

            $webVideo = $docUrl . '/customers/' . $value['id'] . '/' . $value['video'];
            if ($value['video'] != '' && file_exists($webVideo)) {
                $feedbacks[$key]['video'] = 'Yes';
            } else {
                $feedbacks[$key]['video'] = 'No';
            }
        }

        // Get the total feedbacks for the manager's organization
        $totalFeedbackCount = 0;
        if ($organizationId != '') {
            $totalFeedbackCount = DB::table('feedback as fd')
                ->leftJoin('managers as m', 'fd.organization_id', '=', 'm.organization_id')
                ->where('fd.organization_id', '=', $organizationId)
                ->where('fd.feedback', '!=', null)
                ->where('fd.feedback', '!=', '')
                ->count();
            // $totalFeedbackCount = $feedbackResults->count();
        }

        // Get the total apps being used in manager's organization
        $totalAppsCount = 0;
        //        if ($organizationId != '') {
        //            $appsResults = DB::table('devices as dv')
        //                    ->leftJoin('managers as m', 'dv.organization_id', '=', 'm.organization_id')
        //                    ->where('dv.organization_id', '=', $organizationId)
        //                    ->where('dv.status', 1)
        //                    ->get();
        //            $totalAppsCount = $appsResults->count();
        //        }

        if ($organizationId != '') {
            $totalAppsCount = DB::table('feedback as fb')
                ->where('fb.organization_id', '=', $organizationId)
                //                    ->where('dv.status', 1)
                ->count();
            // $totalAppsCount = $appsResults->count();
        }


        // Get current plan of manager
        $hasPlan = 0;
        $planActivation = $planExpireOn = $planName = $planPrice = '';

        if ($managerId != '') {
            $plan = ManagerPlan::where('manager_id', $managerId)->get()->where('status', 'current')->first();
            $date = new \DateTime();

            if (!empty($plan)) {
                if ($plan->expire_on < $date->format('Y-m-d')) {
                    $plan->status = 'expired';
                    $plan->save();
                }
                $planId = $plan->plan_id;
                $actDate = new \DateTime($plan->activated_at);
                $planActivation = $actDate->format(env('DATE_FORMAT'));

                $expDate = new \DateTime($plan->expire_on);
                $planExpireOn = $expDate->format(env('DATE_FORMAT'));
                $planInfo = SubscriptionPlans::where('id', $planId)->get()->first();
                if (!empty($planInfo)) {
                    $hasPlan = 1;
                    $planName = $planInfo->name;
                    $planPrice = $planInfo->price;
                }
            }
        }


        $reponseArray = array(
            'hasPlan' => $hasPlan,
            'total_feedback' => $totalFeedbackCount,
            'app_usage' => $totalAppsCount,
            'subscribed_plan' => $planName,
            'price' => $planPrice,
            'activated' => $planActivation,
            'expiry' => $planExpireOn,
            'feedbacks' => $feedbacks
        );
        return response()->json($reponseArray);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function customers(Request $request)
    {
        // get employee feedbacks
        $organizationId = $request->organizationId;
        $baseUrl = url();
        $feedbacks = Feedback::select('id', 'customer_name', 'profile_pic', 'rating', 'feedback', 'video', 'email', 'created', 'feedback', 'fb_shared', 'twitter_shared', 'insta_shared')
            // ->where('feedback', '!=', null)
            ->where('organization_id', '=', $organizationId)
            ->where('is_queue', '=', 1)
            ->orderBy('id', 'desc')->get();
        $helperobj = new \App\CommonHelper();
        $dateformat = env("DATE_FORMAT");
        $timeformat = env("TIME_FORMAT");
        $docUrl = $helperobj->publicPath();
        foreach ($feedbacks as $key => $value) {
            $webVideo = $docUrl . '/customers/' . $value->id . '/' . $value->video;
            $ratingImg = ANGULARURL . 'assets/img/' . $value->rating . 'star.png';
            if ($value->video != '' && file_exists($webVideo)) {
                $feedbacks[$key]['video'] = 'Yes';
            } else {
                $feedbacks[$key]['video'] = 'No';
            }
            $feedbacks[$key]['ratingImg'] = $ratingImg;
            $docpath = $docUrl . '/customers/' . $value['id'] . '/' . $value['profile_pic'];
            $webpath = $baseUrl . '/customers/' . $value['id'] . '/' . $value['profile_pic'];

            if ($value['profile_pic'] != '' && file_exists($docpath)) {
                $feedbacks[$key]['profile_path'] = $webpath;
            } else {
                $feedbacks[$key]['profile_path'] = $baseUrl . '/default-profile.png';
            }
            $feedbacks[$key]['created'] = $helperobj->convertDateByFormat($value['created'], $dateformat . ' ' . $timeformat);
        }

        $reponseArray = array('feedbacks' => $feedbacks);
        return response()->json($reponseArray);
    }

    /**
     * Get the specified resource from storage.
     *
     * @param  int $rid
     * @return \Illuminate\Http\Response
     */
    public function show($rid)
    {
        $baseUrl = url();
        $helperobj = new \App\CommonHelper();
        $dateformat = env("DATE_FORMAT");
        $timeformat = env("TIME_FORMAT");
        $docUrl = $helperobj->publicPath();
        $feedback = DB::table('feedback as fb')
            ->select('fb.*', 'u.name as employee_name')
            ->leftJoin('employees as em', 'em.id', '=', 'fb.user_id')
            ->leftJoin('users as u', 'u.id', '=', 'fb.user_id')
            ->where('fb.id', '=', $rid)
            ->get()->toArray();

        if (!empty($feedback) && isset($feedback[0])) {
            $docpath = $docUrl . '/customers/' . $feedback[0]->id . '/' . $feedback[0]->profile_pic;
            $webpath = $baseUrl . '/customers/' . $feedback[0]->id . '/' . $feedback[0]->profile_pic;

            $docVideo = $docUrl . '/customers/' . $feedback[0]->id . '/' . $feedback[0]->video;
            $webVideo = $baseUrl . '/customers/' . $feedback[0]->id . '/' . $feedback[0]->video;

            if ($feedback[0]->profile_pic != '' && file_exists($docpath)) {
                $feedback[0]->profile_pic = $webpath;
            } else {
                $feedback[0]->profile_pic = ANGULARURL . DEFAULT_PROFILE_IMAGE;
            }

            if ($feedback[0]->video != '' && file_exists($docVideo)) {
                $feedback[0]->video = $webVideo;
            } else {
                $feedback[0]->video = '';
            }

            $feedback[0]->ratingImg = ANGULARURL . 'assets/img/' . $feedback[0]->rating . 'star.png';
            $feedback[0]->created = $helperobj->convertDateByFormat($feedback[0]->created, $dateformat . ' ' . $timeformat);
            $feedback[0]->appointment_dt = date("m-d-Y H:i:s", strtotime($feedback[0]->appointment_dt));

            return response()->json($feedback);
        } else {
            return response()->json(['status' => 'fail', 'message' => 'No matching record found.']);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function sendlink(Request $request)
    {
        $this->validate($request, [
            'email' => 'required',
            'mobile' => 'required',
            'user_id' => 'required',
            'organization_id' => 'required',
            //  'place'=>'required',
        ]);

        $email = $request->email;
        $place = $request->place;
        $user = User::where('email', $email)->get()->first();
        if ($user) {
            return response()->json(['code' => 400, 'status' => 'fail', 'message' => NOT_ALLOWED]);
        }
        $feedback = new Feedback();
        $feedback->email = $email;
        $feedback->mobile = $request->mobile;
        $feedback->user_id = $request->user_id;
        $feedback->organization_id = $request->organization_id;
        $feedback->token = str_random(60);
        $feedback->by_link = 1;
        $date = new \DateTime();
        $ddf = $date->format('Y-m-d H:i:s');

        $feedback->created = $ddf;

        if ($feedback->save()) {
            $manager = Manager::where('user_id', $feedback->user_id)->first();
            if ($manager && $manager->review_identifier != '') {
                $link = ANGULARURL . 'feedback-facebook?token=' . $feedback->token . '&place=' . $place;
            } elseif ($place != '') {
                $link = ANGULARURL . 'feedbackplace?token=' . $feedback->token . '&place=' . $place;
            } else {
                $link = ANGULARURL . 'feedback-options?token=' . $feedback->token . '&place=' . $place;
            }
            $helperobj = new \App\CommonHelper();
            $shortUrl = $helperobj->routeSortner($link);
            $body = EmailTemplate::where('slug', 'FEEDBACK_LINK')->first();

            if (!empty($body)) {
                $organization = Organization::find($request->organization_id);
                $mngrUser = User::find($organization->user_id);
                if ($organization) {
                    $helperobj = new \App\CommonHelper();
                    $docUrl = $helperobj->publicPath();
                    $image = $docUrl . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                    $mobileImg = $image;
                    if (!file_exists($image)) {
                        $image = ANGULARURL . PU_LOGO;
                        $mobileImg = ANGULARURL . 'assets/img/PU-SMS-logo_new.png';
                    } else {
                        $image = url() . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                        $mobileImg = $image;
                    }
                } else {
                    $image = ANGULARURL . PU_LOGO;
                    $mobileImg = ANGULARURL . 'assets/img/PU-SMS-logo_new.png';
                }
                $tmp1 = str_replace("##FEEDBACK_LINK##", $link, $body['description']);
                $tmp2 = str_replace("##LOGO##", $image, $tmp1);
                $tmp3 = str_replace("##YEAR##", date('Y'), $tmp2);
                $data['html'] = str_replace("##SUPPORT_LINK##", SUPPORT_LINK, $tmp3);
                $subject = str_replace("##USER_NAME##", $organization->name, $body['subject']);

                $emailQueue = new EmailQueue();
                $emailQueue->type = TYPE_SENDLINK;
                $emailQueue->mail_subject = $subject;
                $emailQueue->mail_to = $email;
                $emailQueue->mail_from = FROM_IN_MAIL;
                $emailQueue->mail_body = $data['html'];
                $emailQueue->is_send = 0;
                $date = new \DateTime();
                $ddf = $date->format('Y-m-d H:i:s');
                $emailQueue->created = $ddf;
                $emailQueue->save();
            }

            if (!is_numeric($shortUrl)) {
                $link = $shortUrl;
                $orgName = $organization->name ? $organization->name : '-';
                $data['type'] = 'feedback';
                $data['to'] = $request->mobile;
                $data['msgBody'] = $orgName . ' Your feedbalink is ' . $link;
                $data['media'] = $mobileImg;

                $smsResult = $helperobj->sendSMS($data);

                if (empty($smsResult)) {
                    return response()->json(['code' => 200, 'status' => 'success', 'message' => FEEDBACK_LINK_SEND]);
                } else {
                    $errorMsg = (isset($smsResult['message'])) ? $smsResult['message'] : 'Something went wrong!';
                    return response()->json(['code' => 400, 'status' => 'fail', 'message' => $errorMsg]);
                }
            }

            return response()->json(['code' => 200, 'status' => 'success', 'message' => FEEDBACK_LINK_SEND]);
        } else {
            return response()->json(['code' => 400, 'status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
        }
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function sendlinknew(Request $request)
    {



        $this->validate($request, [
            'email' => 'required',
            'mobile' => 'required',
            'user_id' => 'required',
            'organization_id' => 'required',
            //  'place'=>'required',
        ]);

        $email = $request->email;
        $place = $request->place;

        $user_emp = User::select('status')->where('id', $request->user_id)->first();

        $manager_org = Manager::select('user_id')->where('organization_id', $request->organization_id)->first();

        if ($user_emp) {

            if ($user_emp->status === 2 || $user_emp->status === 0) {
                return response()->json(['status' => 'fail', 'code' => 400, 'message' => ACC_BLOCKED]);
            }

            if ($manager_org) {

                $emp_mn = User::select('status')->where('id', $manager_org->user_id)->where('status', 1)->where('deleted_at', NULL)->first();


                if (empty($emp_mn)) {
                    return response()->json(['status' => 'fail', 'code' => 400, 'message' => EMPLOYEE_DELETE]);
                }
            }
        } else {

            return response()->json(['status' => 'fail', 'code' => 400, 'message' => EMPLOYEE_DELETE]);
        }

        $user = User::where('email', $email)->first();
        if ($user) {
            return response()->json(['code' => 400, 'status' => 'fail', 'message' => NOT_ALLOWED]);
        }



        if ($manager_org) {
            $manager_plan = ManagerPlan::select('expire_on')->where('manager_id', $manager_org->user_id)->orderBy('id', 'DESC')->first();

            if ($manager_plan) {
                $current_date = date('Y-m-d');

                if (strtotime($manager_plan->expire_on) < strtotime($current_date)) {

                    return response()->json(['status' => 'fail', 'message' => MANAGER_PLAN_EXPIRED]);
                }
            }
        }


        $feedback = new Feedback();
        $feedback->email = $email;
        $feedback->mobile = $request->mobile;
        $feedback->user_id = $request->user_id;
        $feedback->organization_id = $request->organization_id;
        $feedback->token = str_random(60);
        $feedback->by_link = 1;
        $date = new \DateTime();
        $ddf = $date->format('Y-m-d H:i:s');

        $feedback->created = $ddf;

        if ($feedback->save()) {
            $manager = Manager::where('user_id', $feedback->user_id)->first();
            if ($manager && $manager->review_identifier != '') {
                $link = ANGULARURL . 'feedback-facebook?token=' . $feedback->token . '&place=' . $place;
            } elseif ($place != '') {
                $link = ANGULARURL . 'feedbackplace?token=' . $feedback->token . '&place=' . $place;
            } else {
                $link = ANGULARURL . 'feedback-options?token=' . $feedback->token . '&place=' . $place;
            }

            $helperobj = new \App\CommonHelper();
            //$shortUrl = $helperobj->routeSortner($link);
            $shortUrl = $helperobj->routeSortnerNew($link, $feedback);
            $link = $shortUrl;
            $EmailTemplateData = Manager::where('organization_id', $request->organization_id)->first();

            $isHippa = "";
            if ($EmailTemplateData) {
                if ($EmailTemplateData->isHippa == '1') {
                    $body = EmailTemplate::where('slug', 'FEEDBACK_LINK_MEDICAL')->first();
                    $isHippa = 1;
                } else {
                    $body = EmailTemplate::where('slug', 'FEEDBACK_LINK_NONMEDICAL')->first();
                }
            } else {
                $body = EmailTemplate::where('slug', 'FEEDBACK_LINK')->first();
            }


            if (!empty($body)) {
                $organization = Organization::find($request->organization_id);
                $mngrUser = User::find($organization->user_id);
                if ($organization) {
                    $helperobj = new \App\CommonHelper();
                    $docUrl = $helperobj->publicPath();

                    if ($organization->organization_pic != "") {
                        $image = $docUrl . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                        $mobileImg = $image;
                        if (!file_exists($image)) {
                            $image = ANGULARURL . PU_LOGO;
                            $mobileImg = ANGULARURL . 'assets/img/PU-SMS-logo_new.png';
                        } else {
                            $image = url() . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                            $mobileImg = $image;
                        }
                    } else {
                        $image = ANGULARURL . PU_LOGO;
                        $mobileImg = ANGULARURL . 'assets/img/PU-SMS-logo_new.png';
                    }
                } else {
                    $image = ANGULARURL . PU_LOGO;
                    $mobileImg = ANGULARURL . 'assets/img/PU-SMS-logo_new.png';
                }

                $orgName = $organization->name ? $organization->name : '-';
                $tmp1 = str_replace("##FEEDBACK_LINK##", $link, $body['description']);
                $tmp2 = str_replace("##LOGO##", $image, $tmp1);
                $tmp3 = str_replace("##ORGANIZATION_NAME##", $orgName, $tmp2);
                $tmp4 = str_replace("##YEAR##", date('Y'), $tmp3);
                $data['html'] = str_replace("##SUPPORT_LINK##", SUPPORT_LINK, $tmp4);
                $subject = str_replace("##USER_NAME##", $organization->name, $body['subject']);

                $emailQueue = new EmailQueue();
                $emailQueue->type = TYPE_SENDLINK;
                $emailQueue->mail_subject = $subject;
                $emailQueue->mail_to = $email;
                $emailQueue->mail_from = FROM_IN_MAIL;
                $emailQueue->mail_body = $data['html'];
                $emailQueue->is_send = 0;
                $date = new \DateTime();
                $ddf = $date->format('Y-m-d H:i:s');
                $emailQueue->created = $ddf;
                $emailQueue->save();
            }

            //            if (!is_numeric($shortUrl)) {
            if (isset($shortUrl)) {
                $link = $shortUrl;
                $orgName = $organization->name ? $organization->name : '-';
                $data['type'] = 'feedback';
                $data['to'] = $request->mobile;
                // $data['msgBody'] = $orgName . ' Your feedbalink is ' . $link;
                if ($isHippa == 1) {

                    $data['msgBody'] = 'Hi,We would like to thank you for choosing ' . $organization->name . ' and for being such a wonderful patient. We would greatly appreciate you giving us a positive review online.  Please click the link below to leave a review. It will take about 30 seconds.  Thank you. Click here : ' . $link;
                } else {

                    $data['msgBody'] = 'Hi,We would like to thank you for choosing ' . $organization->name . ' and for being such a wonderful patron of our business. We would greatly appreciate you giving us a positive review online.  Please click the link below to leave a review. It will take about 30 seconds.  Thank you. Click here : ' . $link;
                }

                $data['media'] = $mobileImg;


                $smsResult = $helperobj->sendSMS($data);

                if (empty($smsResult)) {
                    return response()->json(['code' => 200, 'status' => 'success', 'message' => FEEDBACK_LINK_SEND]);
                } else {
                    $errorMsg = (isset($smsResult['message'])) ? $smsResult['message'] : 'Something went wrong!';
                    return response()->json(['code' => 400, 'status' => 'fail', 'message' => $errorMsg]);
                }
            }

            return response()->json(['code' => 200, 'status' => 'success', 'message' => FEEDBACK_LINK_SEND]);
        } else {
            return response()->json(['code' => 400, 'status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
        }
    }

    /**
     * Send link to feedback queued user
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function sendlinkFromQueueListing(Request $request)
    {

        $this->currentUser = app('auth')->guard()->user();
        $this->organization = Organization::where('user_id', $this->currentUser->id)->first();

        $this->validate($request, [
            'feedback_id' => 'required',
        ]);
        $request->user_id = $this->currentUser->id;
        $request->organization_id = $this->organization->id;

        $feedback = Feedback::select('feedback.email', 'feedback.id', 'feedback.token', 'feedback.user_id', 'feedback.mobile', 'branches.place_value')->leftjoin('branches', 'branches.sycle_clinic_id', '=', 'feedback.clinic_id')->where('feedback.id', $request->feedback_id)->first();

        if (empty($feedback)) {
            return response()->json(['status' => 'fail', 'code' => 400, 'message' => "Invalid data."]);
        } elseif (empty($feedback->email) && empty($feedback->mobile)) {

            return response()->json(['status' => 'fail', 'code' => 400, 'message' => "Mobile number or email not available to send link."]);
        }

        $request->email = $feedback->email;
        $request->place = $feedback->place_value;
        $request->mobile = $feedback->mobile;
        $email = $request->email;
        $place = $request->place;


        $user_emp = User::select('status')->where('id', $request->user_id)->first();

        $manager_org = Manager::select('user_id')->where('organization_id', $request->organization_id)->first();

        if ($user_emp) {

            if ($user_emp->status === 2 || $user_emp->status === 0) {
                return response()->json(['status' => 'fail', 'code' => 400, 'message' => ACC_BLOCKED]);
            }

            if ($manager_org) {

                $emp_mn = User::select('status')->where('id', $manager_org->user_id)->where('status', 1)->where('deleted_at', NULL)->first();
                if (empty($emp_mn)) {
                    return response()->json(['status' => 'fail', 'code' => 400, 'message' => EMPLOYEE_DELETE]);
                }
            }
        } else {

            return response()->json(['status' => 'fail', 'code' => 400, 'message' => EMPLOYEE_DELETE]);
        }

        $user = User::where('email', $email)->first();
        if ($user) {
            return response()->json(['code' => 400, 'status' => 'fail', 'message' => NOT_ALLOWED]);
        }



        if ($manager_org) {
            $manager_plan = ManagerPlan::select('expire_on')->where('manager_id', $manager_org->user_id)->orderBy('id', 'DESC')->first();

            if ($manager_plan) {
                $current_date = date('Y-m-d');

                if (strtotime($manager_plan->expire_on) < strtotime($current_date)) {

                    return response()->json(['status' => 'fail', 'message' => MANAGER_PLAN_EXPIRED]);
                }
            }
        }


        if ($feedback) {
            $manager = Manager::where('user_id', $feedback->user_id)->first();
            if ($manager && $manager->review_identifier != '') {
                $link = ANGULARURL . 'feedback-facebook?token=' . $feedback->token . '&place=' . $place;
            } elseif ($place != '') {
                $link = ANGULARURL . 'feedbackplace?token=' . $feedback->token . '&place=' . $place;
            } else {
                $link = ANGULARURL . 'feedback-options?token=' . $feedback->token . '&place=' . $place;
            }

            $helperobj = new \App\CommonHelper();
            //$shortUrl = $helperobj->routeSortner($link);
            $shortUrl = $helperobj->routeSortnerNew($link, $feedback);
            $link = $shortUrl;
            $isHippa = "";
            $organization = Organization::find($request->organization_id);

            if ($organization) {
                $helperobj = new \App\CommonHelper();
                $docUrl = $helperobj->publicPath();

                if ($organization->organization_pic != "") {
                    $image = $docUrl . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                    $mobileImg = $image;
                    if (!file_exists($image)) {
                        $image = ANGULARURL . PU_LOGO;
                        $mobileImg = ANGULARURL . 'assets/img/PU-SMS-logo_new.png';
                    } else {
                        $image = url() . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                        $mobileImg = $image;
                    }
                } else {
                    $image = ANGULARURL . PU_LOGO;
                    $mobileImg = ANGULARURL . 'assets/img/PU-SMS-logo_new.png';
                }
            } else {
                $image = ANGULARURL . PU_LOGO;
                $mobileImg = ANGULARURL . 'assets/img/PU-SMS-logo_new.png';
            }



            if (!empty($email)) {
                $EmailTemplateData = Manager::where('organization_id', $request->organization_id)->first();


                if ($EmailTemplateData) {
                    if ($EmailTemplateData->isHippa == '1') {
                        $body = EmailTemplate::where('slug', 'FEEDBACK_LINK_MEDICAL')->first();
                        $isHippa = 1;
                    } else {
                        $body = EmailTemplate::where('slug', 'FEEDBACK_LINK_NONMEDICAL')->first();
                    }
                } else {
                    $body = EmailTemplate::where('slug', 'FEEDBACK_LINK')->first();
                }
                if (!empty($body)) {

                    $mngrUser = User::find($organization->user_id);

                    $orgName = $organization->name ? $organization->name : '-';
                    $tmp1 = str_replace("##FEEDBACK_LINK##", $link, $body['description']);
                    $tmp2 = str_replace("##LOGO##", $image, $tmp1);
                    $tmp3 = str_replace("##ORGANIZATION_NAME##", $orgName, $tmp2);
                    $tmp4 = str_replace("##YEAR##", date('Y'), $tmp3);
                    $data['html'] = str_replace("##SUPPORT_LINK##", SUPPORT_LINK, $tmp4);
                    $subject = str_replace("##USER_NAME##", $organization->name, $body['subject']);

                    $emailQueue = new EmailQueue();
                    $emailQueue->type = TYPE_SENDLINK;
                    $emailQueue->mail_subject = $subject;
                    $emailQueue->mail_to = $email;
                    $emailQueue->mail_from = FROM_IN_MAIL;
                    $emailQueue->mail_body = $data['html'];
                    $emailQueue->is_send = 0;
                    $date = new \DateTime();
                    $ddf = $date->format('Y-m-d H:i:s');
                    $emailQueue->created = $ddf;
                    $emailQueue->save();
                }
            }

            //Removing from queue//
            $feedback->is_queue = 1;
            $feedback->is_send_link = 1;
            $feedback->update();

            if (isset($shortUrl) && !empty($request->mobile)) {
                $link = $shortUrl;
                $orgName = $organization->name ? $organization->name : '-';
                $data['type'] = 'feedback';
                $data['to'] = $request->mobile;
                // $data['msgBody'] = $orgName . ' Your feedbalink is ' . $link;
                if ($isHippa == 1) {

                    $data['msgBody'] = 'Hi,We would like to thank you for choosing ' . $organization->name . ' and for being such a wonderful patient. We would greatly appreciate you giving us a positive review online.  Please click the link below to leave a review. It will take about 30 seconds.  Thank you. Click here : ' . $link;
                } else {

                    $data['msgBody'] = 'Hi,We would like to thank you for choosing ' . $organization->name . ' and for being such a wonderful patron of our business. We would greatly appreciate you giving us a positive review online.  Please click the link below to leave a review. It will take about 30 seconds.  Thank you. Click here : ' . $link;
                }

                $data['media'] = $mobileImg;


                $smsResult = $helperobj->sendSMS($data);

                if (!empty($smsResult)) {
                    if (!empty($email)) {
                        $errorMsg = (isset($smsResult['message'])) ? $smsResult['message'] : 'We have send the review link to the provided email. Can not able to send the link on the provided mobile number.';
                        return response()->json(['code' => 200, 'status' => 'success', 'message' => $errorMsg]);
                    } else {
                        return response()->json(['code' => 400, 'status' => 'fail', 'message' => "Can not able to send the link on the provided mobile number."]);
                    }
                }
            }
            return response()->json(['code' => 200, 'status' => 'success', 'message' => "Feedback link has been sent successfully."]);
        } else {
            return response()->json(['code' => 400, 'status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
        }
    }






    /**
     * getSendFeedbackLinkLog
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */

    public function getSendFeedbackLinkLog($token = 'getAll')
    {
        try {
            if ($token == "getAll") {
                $feedback = DB::table('feedback_send_link_log')
                    ->select('*', 'feedback_send_link_log.id as send_link_id')
                    ->join('feedback', 'feedback_send_link_log.feedback_id', '=', 'feedback.id')->get();
            } else {
                $feedback = DB::table('feedback_send_link_log')->where('feedback_send_link_log.token', $token)
                    ->select('*', 'feedback_send_link_log.id as send_link_id')
                    ->join('feedback', 'feedback_send_link_log.feedback_id', '=', 'feedback.id')->first();
                if ($feedback && !empty($feedback)) {
                    $send_link_id = $feedback->send_link_id;
                    DB::table('feedback_send_link_log')->where('id', $send_link_id)->increment('is_clicked_count', 1, ['is_clicked' => 1]);
                    $feedback->is_clicked_count = $feedback->is_clicked_count + 1;
                }
            }
            if (!empty($feedback)) {
                return response()->json(['status' => 'success', 'message' => RECORD_FOUND, 'data' => $feedback]);
            } else {
                return response()->json(['status' => 'fail', 'message' => RECORD_NOT_FOUND]);
            }
        } catch (Exception $e) {
            return response()->json(['status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function save(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'token' => 'required',
            'feedback' => 'required',
            'rating' => 'required',
        ]);

        $token = $request->token;
        $place = $request->get('place');
        $feedback = Feedback::where('token', $token)->get()->first();
        if ($feedback) {
            $feedback->customer_name = $request->name;
            $feedback->feedback = $request->feedback;
            $feedback->rating = $request->rating;
            $feedback->email = $feedback->email;
            $feedback->token = '';
            $date = new \DateTime();
            $ddf = $date->format('Y-m-d');
            $feedback->updated = $ddf;

            $user = User::find($feedback->user_id);
            if ($user && $user->role == 'ROLE_EMPLOYEE') {

                $employees = Employee::where('user_id', $feedback->user_id)->get()->first();
                $customers = $employees->total_customers > 0 ? $employees->total_customers : 0;
                $employees->total_customers = $customers + 1;
                $employees->save();
            }
            if ($feedback->save()) {

                //feedback_send_link_log        
                $feedbackLogs = DB::table('feedback_send_link_log')
                    ->where('feedback_id', $feedback->id)
                    ->update(['status' => 'ignore']);

                $this->sendCouponMail($feedback);

                return response()->json(['status' => 'success', 'message' => THANKS_FEEDBACK, 'place' => $place]);
            } else {
                return response()->json(['status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
            }
        } else {
            return response()->json(['status' => 'fail', 'message' => LINK_EXPIRED]);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function storeFeedbackOld(Request $request)
    {

        $this->validate($request, [
            'name' => 'required',
            'email' => 'required',
            'feedback' => 'required',
            'location' => 'required',
            'rating' => 'required',
            'mobile' => 'required',
            'user_id' => 'required',
            'organization_id' => 'required',
        ]);

        //$emailMedia = $request->email_media;
        $feedback = new Feedback();

        $feedback->customer_name = $request->name;
        $feedback->email = $request->email;
        $feedback->feedback = $request->feedback;
        $feedback->rating = $request->rating;
        $feedback->location = $request->location;
        $feedback->user_id = $request->user_id;
        $feedback->mobile = $request->mobile;
        $feedback->organization_id = $request->organization_id;
        $feedback->token = null;
        $date = new \DateTime();
        $ddf = $date->format('Y-m-d H:i:s');
        $feedback->created = $ddf;
        $feedback->email_media = 1;

        if ($feedback->save()) {
            $this->sendCouponMail($feedback);
            $lastFeedbackId = $feedback->id;
            $user = User::find($request->user_id);
            if ($user->role == 'ROLE_EMPLOYEE') {
                $employee = Employee::where('user_id', $request->user_id)->first();
                $customers = $employee->total_customers > 0 ? $employee->total_customers : 0;
                $employee->total_customers = $customers + 1;
                $employee->save();
            }

            $responseArray = array('feedbackId' => $lastFeedbackId);
            return response()->json([
                'code' => 200,
                'status' => 'success',
                'data' => $responseArray,
                'message' => FEEDBACK_SAVED
            ]);
        } else {
            return response()->json([
                'code' => 400,
                'status' => 'fail',
                'data' => '',
                'message' => SOMETHING_WENT_WRONG
            ]);
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function storeFeedback(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'email' => 'required',
            'feedback' => 'required',
            //'location'         => 'required',
            'rating' => 'required',
            'mobile' => 'required',
            'user_id' => 'required',
            'signature' => 'required',
            'organization_id' => 'required',
        ]);

        $manager_org = Manager::select('user_id')->where('organization_id', $request->organization_id)->first();

        $user_emp = User::select('status')->where('id', $request->user_id)->first();

        if ($user_emp) {

            if ($user_emp->status === 2 || $user_emp->status === 0) {
                return response()->json(['status' => 'fail', 'code' => 400, 'message' => ACC_BLOCKED]);
            }

            if ($manager_org) {

                $emp_mn = User::select('status')->where('id', $manager_org->user_id)->where('status', 1)->where('deleted_at', NULL)->first();


                if (empty($emp_mn)) {
                    return response()->json(['status' => 'fail', 'code' => 400, 'message' => EMPLOYEE_DELETE]);
                }
            }
        } else {

            return response()->json(['status' => 'fail', 'code' => 400, 'message' => EMPLOYEE_DELETE]);
        }

        $user = User::where('email', $request->email)->first();
        if ($user) {
            return response()->json(['code' => 400, 'status' => 'fail', 'message' => NOT_ALLOWED]);
        }



        if ($manager_org) {
            $manager_plan = ManagerPlan::select('expire_on')->where('manager_id', $manager_org->user_id)->orderBy('id', 'DESC')->first();

            if ($manager_plan) {
                $current_date = date('Y-m-d');

                if (strtotime($manager_plan->expire_on) < strtotime($current_date)) {

                    return response()->json(['status' => 'fail', 'message' => MANAGER_PLAN_EXPIRED]);
                }
            }
        }

        $orgName = $placeName = $assetlink = '';
        $emailMedia = $request->email_media;
        $feedback = new Feedback();

        $branch = Branch::where('organization_id', $request->organization_id)->first();

        $feedback->customer_name = $request->name;
        $feedback->email = $request->email;
        $feedback->feedback = $request->feedback;
        $feedback->rating = $request->rating;
        $feedback->location = $branch ? $branch->name : 'mumbai';
        $feedback->user_id = $request->user_id;
        $feedback->mobile = $request->mobile;

        $profileImage = $request->file('profile_pic');
        $signatureImage = $request->file('signature');
        $feedbackVideo = $request->file('video');


        $feedback->organization_id = $request->organization_id;
        $feedback->token = null;
        $date = new \DateTime();
        $ddf = $date->format('Y-m-d H:i:s');
        $feedback->created = $ddf;
        $feedback->email_media = $emailMedia;


        $organization = Organization::find($request->organization_id);
        if ($organization) {
            $orgName = $organization->name;
        }

        $employee = Employee::where('user_id', $request->user_id)->first();

        if ($employee) {
            $emBranch = $employee->branch_id;
            $brData = Branch::find($emBranch);
            if ($brData) {
                $placeName = $brData->name;
            }
        }

        if ($profileImage) {
            $profileFileName = str_random(12) . '.' . $profileImage->getClientOriginalExtension();
            $feedback->profile_pic = $profileFileName;
        }
        if ($signatureImage) {
            $feedback->signature = $request->signature;
            $signatureFileName = str_random(12) . '.' . $signatureImage->getClientOriginalExtension();
            $feedback->signature = $signatureFileName;
        }
        if ($feedbackVideo) {
            $videoFileName = str_random(12) . '.' . $feedbackVideo->getClientOriginalExtension();
            $feedback->video = $videoFileName;
        }

        if ($feedback->save()) {
            $helperobj = new \App\CommonHelper();
            $lastFeedbackId = $feedback->id;
            $cid = $helperobj->encrypt($lastFeedbackId);

            $destinationPath = 'customers' . '/' . $lastFeedbackId . '/';
            if (!file_exists('customers')) {
                mkdir('customers');
            }

            if ($profileImage) {
                $profileImage->move($destinationPath, $profileFileName);
                $assetFile = $helperobj->encrypt($profileFileName);
                $assetType = $helperobj->encrypt('image');
                $assetlink = DOMAIN_URL . "static/$cid/$assetType/$assetFile";
            }

            if ($signatureImage) {
                $signatureImage->move($destinationPath, $signatureFileName);
            }

            if ($feedbackVideo) {
                $feedbackVideo->move($destinationPath, $videoFileName);
                $assetFile = $helperobj->encrypt($videoFileName);
                $assetType = $helperobj->encrypt('video');
                $assetlink = DOMAIN_URL . "static/$cid/$assetType/$assetFile";
            }

            if ($emailMedia == true) {

                // $body = EmailTemplate::where('slug', 'FEEDBACK_MEDIA')->first();
                //Code added by jatin
                $manager_id = $organization->user_id;
                $mngrData = Manager::where('user_id', $manager_id)->get();

                if ($mngrData[0]->isHippa == 1) {
                    $body = EmailTemplate::where('slug', 'FEEDBACK_MEDIA_MEDICAL')->first();
                } else {
                    $body = EmailTemplate::where('slug', 'FEEDBACK_MEDIA_NONMEDICAL')->first();
                }
                //end


                if (!empty($body)) {
                    if ($organization) {
                        $helperobj = new \App\CommonHelper();
                        $docUrl = $helperobj->publicPath();
                        $image = $docUrl . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                        if (!file_exists($image)) {
                            $image = ANGULARURL . 'assets/img/PU-logo.png';
                        } else {
                            $image = url() . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                        }
                        $mngrUser = User::find($organization->user_id);
                    } else {
                        $image = ANGULARURL . 'assets/img/PU-logo.png';
                    }
                    $tmp1 = str_replace("##USER_NAME##", ucfirst($request->name), $body['description']);
                    $tmp2 = str_replace("##SUPPORT_MAIL##", SUPPORT_MAIL, $tmp1);
                    $tmp3 = str_replace("##PLACE_NAME##", $placeName, $tmp2);
                    $tmp4 = str_replace("##LOGO##", $image, $tmp3);
                    $tmp5 = str_replace("##YEAR##", date('Y'), $tmp4);
                    $tmp5 = str_replace("##business_name##", ucfirst($orgName), $tmp5);
                    $data['html'] = str_replace("##FEEDBACK_ASSET_LINK##", $assetlink, $tmp5);
                    $mailSubject = $orgName . " - Your  Survey Feedback Media Copy";
                    $email = $request->email;
                    //echo $mailSubject;
                    //echo "<br>====<br>";
                    //echo $data['html']; die();
                    $emailQueue = new EmailQueue();
                    $emailQueue->type = TYPE_FEEDBACK_ASSET;
                    $emailQueue->mail_subject = $mailSubject;
                    $emailQueue->mail_to = $email;
                    $emailQueue->mail_from = FROM_IN_MAIL;
                    $emailQueue->mail_body = $data['html'];
                    $emailQueue->is_send = 0;
                    $date = new \DateTime();
                    $ddf = $date->format('Y-m-d H:i:s');
                    $emailQueue->created = $ddf;
                    $emailQueue->save();
                }
            }

            $this->sendCouponMail($feedback);

            $user = User::find($request->user_id);
            if ($user && $user->role == 'ROLE_EMPLOYEE') {
                $customers = $employee->total_customers > 0 ? $employee->total_customers : 0;
                $employee->total_customers = $customers + 1;
                $employee->save();
            } else {
                return response()->json(['code' => 400, 'status' => 'fail', 'message' => RECORD_NOT_FOUND]);
            }

            $responseArray = array('feedbackId' => $lastFeedbackId);
            return response()->json([
                'code' => 200,
                'status' => 'success',
                'data' => $responseArray,
                'message' => FEEDBACK_SAVED
            ]);
        } else {
            return response()->json([
                'code' => 400,
                'status' => 'fail',
                'data' => '',
                'message' => SOMETHING_WENT_WRONG
            ]);
        }
    }

    /**
     * Get the specified resource from storage.
     *
     * @return \Illuminate\Http\Response
     */
    public function showAsset($cid, $type, $file)
    {

        // image = WVZjeGFGb3lWVDA=
        // video = Wkcxc2ExcFhPRDA=

        $helperobj = new \App\CommonHelper();
        $cid1 = $helperobj->decrypt($cid);
        $filetype = $helperobj->decrypt($type);
        $filename = $helperobj->decrypt($file);
        $assefile = PUBLIC_ASSET_URL . "$cid1/$filename";

        if ('image' == $filetype) {
            if (@getimagesize($assefile)) {
                $getInfo = getimagesize($assefile);
                header('Content-type: ' . $getInfo['mime']);
                readfile($assefile);
            } else {
                echo 'file not exists!';
                die;
            }
        } elseif ('video' == $filetype) {
            echo "<video style='display:block; margin: 0 auto;' width='750' height='500' controls><source src='$assefile' type='video/mp4'>Your browser does not support the video tag.
</video>";
        }
        die;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param int                      $rid
     * @return \Illuminate\Http\Response
     */
    public function saveMedia(Request $request)
    {
        $rid = $request->feedback_id;
        $this->validate($request, [
            'feedback_id' => 'required',
        ]);

        $feedback = Feedback::find($rid);
        if ($feedback) {
            $feedback->video = $request->video;
            $feedback->profile_pic = $request->profile_pic;
            $feedback->signature = $request->signature;
            $date = new \DateTime();
            $ddf = $date->format('Y-m-d H:i:s');
            $feedback->updated = $ddf;
            if ($feedback->save()) {
                if ($feedback->email_media == 1) {
                    $data['html'] = 'testing email text';
                    $mailSubject = 'Feedback Saved';
                    $email = $feedback->email;

                    $emailQueue = new EmailQueue();
                    $emailQueue->type = TYPE_SAVE_MEDIA;
                    $emailQueue->mail_subject = $mailSubject;
                    $emailQueue->mail_to = $email;
                    $emailQueue->mail_from = FROM_IN_MAIL;
                    $emailQueue->mail_body = $data['html'];
                    $emailQueue->is_send = 0;
                    $date = new \DateTime();
                    $ddf = $date->format('Y-m-d H:i:s');
                    $emailQueue->created = $ddf;
                    $emailQueue->save();
                }
                return response()->json(['code' => 200, 'status' => 'success', 'message' => FEEDBACK_SAVED]);
            } else {
                return response()->json(['code' => 400, 'status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
            }
        } else {
            return response()->json(['code' => 400, 'status' => 'fail', 'message' => RECORD_NOT_FOUND]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int                      $rid
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {

        $rid = $request->feedback_id;
        $this->validate($request, [
            'customer_name' => 'required',
            'mobile' => 'required',
            'feedback' => 'required',
            'email' => 'required|unique:users,email',
        ]);

        $user = User::where('email', $request->email)->first();
        if ($user) {
            return response()->json(['code' => 400, 'status' => 'fail', 'message' => EMAIL_EXIST]);
        }

        $feedback = Feedback::find($rid);
        if ($feedback) {

            $feedback->customer_name = $request->customer_name;
            $feedback->mobile = $request->mobile;

            $feedback->feedback = $request->feedback;
            $feedback->email = $request->email;
            //            $feedback->location = $request->location;
            $feedback->status = $request->status;
            $feedback->rating = $request->rating;
            $date = new \DateTime();
            $ddf = $date->format('Y-m-d H:i:s');
            $feedback->updated = $ddf;


            if ($feedback->save()) {
                return response()->json(['status' => 'success', 'message' => FEEDBACK_UPDATED]);
            } else {
                return response()->json(['status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
            }
        } else {
            return response()->json(['status' => 'fail', 'message' => RECORD_NOT_FOUND]);
        }
    }

    /**
     * Get the organization logo.
     *
     * @param \Illuminate\Http\Request $request
     * @param int                      $rid
     * @return \Illuminate\Http\Response
     */
    public function getImage(Request $request)
    {

        $rid = $request->token;
        $place = $request->place;
        $organization = '';
        if ($rid) {
            $feedback = Feedback::where('token', $rid)->first();
            if ($feedback) {
                $organization = Organization::find($feedback->organization_id);
            }
        } elseif ($place) {
            $branch = Branch::where('place_value', $place)->first();
            if ($branch) {
                $organization = Organization::find($branch->organization_id);
            }
        }
        if ($organization) {
            $helperobj = new \App\CommonHelper();
            $docUrl = $helperobj->publicPath();
            $image = $docUrl . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
            if (file_exists($image)) {
                $image = url() . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                return response()->json(['status' => 'success', 'image' => $image]);
            } else {
                return response()->json(['status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
            }
        } else {
            return response()->json(['status' => 'fail', 'message' => RECORD_NOT_FOUND]);
        }
    }

    public function sendCouponMail($feedback)
    {
        $organization = Organization::find($feedback->organization_id);
        if ($organization) {
            $coupon = Coupon::where('user_id', $organization->user_id)->where('is_send', 0)->first();
            $user = User::find($organization->user_id);
            if ($organization) {
                $helperobj = new \App\CommonHelper();
                $docUrl = $helperobj->publicPath();
                $image = $docUrl . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                if (!file_exists($image)) {
                    $image = ANGULARURL . 'assets/img/PU-logo.png';
                } else {
                    $image = url() . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                }
            } else {
                $image = ANGULARURL . 'assets/img/PU-logo.png';
            }
            if ($coupon) {

                $body = EmailTemplate::where('slug', 'COUPON_CODE')->first();

                if (!empty($body)) {
                    $tmp1 = str_replace("##USER_NAME##", ' ', $body['description']);
                    $tmp2 = str_replace("##SUPPORT_LINK##", SUPPORT_LINK, $tmp1);
                    $tmp3 = str_replace("##LOGO##", $image, $tmp2);
                    $tmp4 = str_replace("##COUPON_DESC##", $coupon->description, $tmp3);
                    $tmp5 = str_replace("##YEAR##", date('Y'), $tmp4);
                    $data['html'] = str_replace("##COUPON_CODE##", $coupon->code, $tmp5);
                    $subject = str_replace("##USER_NAME##", $organization->name, $body['subject']);
                    $emailQueue = new EmailQueue();
                    $emailQueue->type = TYPE_COUPON;
                    $emailQueue->mail_subject = $subject;
                    $emailQueue->mail_to = $feedback->email;
                    $emailQueue->mail_from = FROM_IN_MAIL;
                    $emailQueue->mail_body = $data['html'];
                    $emailQueue->is_send = 0;
                    $date = new \DateTime();
                    $ddf = $date->format('Y-m-d H:i:s');
                    $emailQueue->created = $ddf;
                    $emailQueue->save();
                }
            }
        }
        return true;
    }

    public function review(Request $request)
    {
        $manager = Manager::where('user_id', $request->input('userId'))->first();
        if ($manager) {
            $manager->review_identifier = $request->input('name');
            $manager->save();
            return response()->json(['status' => 'success', 'message' => REVIEW_IDENTIFIER_SAVED]);
        } else {
            return response()->json(['status' => 'fail', 'message' => RECORD_NOT_FOUND]);
        }
    }

    public function destroy($rid)
    {
        $feedback = Feedback::find($rid);
        if (!$feedback) {
            return response()->json(['status' => 'fail', 'message' => RECORD_NOT_FOUND]);
        }
        $employee_id = $feedback->user_id;
        $feedback->delete();
        $employee = Employee::where('user_id', $employee_id)->first();
        if (!empty($employee)) {
            $employee->decrement('total_customers');
            $employee->save();
        }
        return response()->json(['status' => 'success', 'message' => FEEDBACK_DELETED]);
    }

    /**
     * get facebook option
     * @param Request $request
     * @return type
     */
    public function getOptions(Request $request)
    {
        $rid = $request->token;
        $data = [];

        $data['is_facebook'] = 0;
        if ($rid) {
            $feedback = Feedback::where('token', $rid)->first();
            if ($feedback) {
                // get employee who has taken feedback
                $employee = Employee::where('user_id', $feedback->user_id)->first();
                if ($employee && $employee->organization_id != '') {
                    // get employee organization
                    $emOrg = $employee->organization_id;
                    $organization = Organization::find($emOrg);
                    if ($organization && $organization->user_id != '') {
                        $manager = Manager::where('user_id', $organization->user_id)->first();
                        if ($manager && $manager->review_identifier != '') {
                            $data['is_facebook'] = 1;
                            $data['review_identifier'] = $manager->review_identifier;
                        }
                    }
                }
            }
        }
        return response()->json(['status' => 'success', 'data' => $data]);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function employeeFeedback(Request $request)
    {
        $this->validate($request, [
            'employee_id' => 'required',
            'duration' => 'required'
        ]);

        $baseUrl = url();
        $helperobj = new \App\CommonHelper();
        $docUrl = $helperobj->publicPath();
        $feedbacks = array();
        $duration = $request->input('duration');

        switch ($duration) {
            case 'today':
                $start = date('Y-m-d 00:00:00');
                $end = date("Y-m-d H:i:s");
                break;
            case 'week':
                $day = date('w');
                $start = date('Y-m-d 00:00:00', strtotime('-' . $day . ' days'));
                $end = date('Y-m-d 00:00:00', strtotime('+' . (6 - $day) . ' days'));
                break;
            case 'month':
                $start = date('Y-m-01 00:00:00');
                $end = date('Y-m-t 00:00:00');
                break;
            case 'year':
                $start = date('Y-m-d 00:00:00', strtotime(date('Y-01-01')));
                $end = date('Y-m-d 00:00:00', strtotime('last day of december'));
                break;
            default:
                $day = date('w');
                $start = date('Y-m-d 00:00:00', strtotime('-' . $day . ' days'));
                $end = date('Y-m-d 00:00:00', strtotime('+' . (6 - $day) . ' days'));
                break;
        }

        $page = 1;

        if ($request->input('page') != '' && $request->input('page') > 1) {
            $page = $request->input('page');
        }
        $record_per_page = RECORD_PER_PAGE;
        $offset = ($page - 1) * $record_per_page;

        $results = Feedback::select('feedback.*', 'u.name as employee_name')
            ->leftJoin('employees as em', 'em.id', '=', 'feedback.user_id')
            ->leftJoin('users as u', 'u.id', '=', 'feedback.user_id')
            ->where('feedback.feedback', '!=', null)
            ->where('feedback.feedback', '!=', '')
            ->where('feedback.user_id', $request->employee_id)
            ->where('created', '>=', $start)
            ->where('created', '<=', $end)
            ->where('by_link', '=', 0)
            ->offset($offset)
            ->limit($record_per_page)
            ->orderBy('feedback.id', 'desc')
            ->get();

        $totalCount = Feedback::select('feedback.*', 'u.name as employee_name')
            ->leftJoin('employees as em', 'em.id', '=', 'feedback.user_id')
            ->leftJoin('users as u', 'u.id', '=', 'feedback.user_id')
            ->where('feedback.feedback', '!=', null)
            ->where('feedback.feedback', '!=', '')
            ->where('feedback.user_id', $request->employee_id)
            ->where('created', '>=', $start)
            ->where('created', '<=', $end)
            ->where('by_link', '=', 0)
            ->orderBy('feedback.id', 'desc')->count();

        foreach ($results as $key => $value) {
            $feedbacks[$key] = $value;
            $docpath = $docUrl . '/customers/' . $value['id'] . '/' . $value['profile_pic'];
            $webpath = $baseUrl . '/customers/' . $value['id'] . '/' . $value['profile_pic'];

            $docVideo = $docUrl . '/customers/' . $value['id'] . '/' . $value['video'];
            $webVideo = $baseUrl . '/customers/' . $value['id'] . '/' . $value['video'];

            if ($value['profile_pic'] != '' && file_exists($docpath)) {
                $feedbacks[$key]['profile_path'] = $webpath;
            } else {
                $feedbacks[$key]['profile_path'] = $baseUrl . '/default-profile-big.png';
            }
            if ($value['video'] != '' && file_exists($docVideo)) {
                $feedbacks[$key]['video'] = $webVideo;
            } else {
                $feedbacks[$key]['video'] = '';
            }
        }
        return response()->json(['code' => 200, 'total_count' => $totalCount, 'status' => 'success', 'data' => $feedbacks]);
    }

    /**
     * send invitation link by employee
     * @param Request $request
     * updated by jatin
     * 
     * */
    public function sendInvitationLink(Request $request)
    {
        $this->validate($request, [
            'employee_id' => 'required',
            'email' => 'required',
            'feedbackId' => 'required'
        ]);

        $empId = $request->employee_id;
        $email = $request->email;
        $feedbackId = $request->feedbackId;

        $employee = Employee::where('user_id', $empId)->first();
        $branch = Branch::where('id', $employee->branch_id)->first();
        $manager = Manager::where('organization_id', $employee->organization_id)->first();
        $empUserData = User::where('id', $empId)->first();
        $organization = Organization::find($employee->organization_id);

        if (empty($employee) || empty($branch) || empty($manager)) {
            return response()->json(['code' => 400, 'status' => 'fail', 'message' => RECORD_NOT_FOUND]);
        }
        $feedBack = Feedback::where('id', $feedbackId)->first();
        $facebook_link = '-';
        $google_link = '-';

        if ($manager && $manager->review_identifier != '') {
            $facebook_link = "https://www.facebook.com/pg/" . $manager->review_identifier . "/reviews/?ref=page_internal";
        }
        if ($branch->place_value != '') {
            $google_link = "https://search.google.com/local/writereview?placeid=" . $branch->place_value;
        }
        $helperobj = new \App\CommonHelper();

        //$body = EmailTemplate::where('slug', 'SEND_FEEDBACK_INVITATION')->first();
        //Added by JAtin - 13Sept19
        if ($manager->isHippa == '1') {
            $body = EmailTemplate::where('slug', 'SEND_FEEDBACK_INVITATION_MEDICAL')->first();
        } else {
            $body = EmailTemplate::where('slug', 'SEND_FEEDBACK_INVITATION_NONMEDICAL')->first();
        }
        //end


        if (!empty($body)) {
            if ($organization) {
                $docUrl = $helperobj->publicPath();
                $image = $docUrl . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                if (!file_exists($image)) {
                    $image = ANGULARURL . PU_LOGO;
                } else {
                    $image = url() . '/orgLogo/' . $organization->id . '/' . $organization->organization_pic;
                }
            } else {
                $image = ANGULARURL . PU_LOGO;
            }
            $username = $empUserData->name;
            $orgName = $organization->name;
            $custName = $feedBack->customer_name ? $feedBack->customer_name : '';
            $tmp1 = str_replace("##FACEBOOK_LINK##", $facebook_link, $body['description']);
            $tmp2 = str_replace("##GOOGLE_LINK##", $google_link, $tmp1);
            $tmp3 = str_replace("##ORGANIZATION_NAME##", $orgName, $tmp2);
            $tmp4 = str_replace("##LOGO##", $image, $tmp3);
            $tmp5 = str_replace("##USER_NAME##", $custName, $tmp4);
            $tmp6 = str_replace("##YEAR##", date('Y'), $tmp5);
            $data['html'] = str_replace("##SUPPORT_LINK##", SUPPORT_LINK, $tmp6);
            $subject = str_replace("##USER_NAME##", $orgName, $body['subject']);
            //die();
            $emailQueue = new EmailQueue();
            $emailQueue->type = TYPE_SENDLINK;
            $emailQueue->mail_subject = $subject;
            $emailQueue->mail_to = $email;
            $emailQueue->mail_from = FROM_IN_MAIL;
            $emailQueue->mail_body = $data['html'];
            $emailQueue->is_send = 0;
            $date = new \DateTime();
            $ddf = $date->format('Y-m-d H:i:s');
            $emailQueue->created = $ddf;
            $emailQueue->save();

            return response()->json(['code' => 200, 'status' => 'success', 'message' => SENT_FEEDBACK_LINK]);
        }
    }
}
