<?php

namespace App\Http\Controllers\Api\v1;

use Illuminate\Http\Request;
use Abraham\TwitterOAuth\TwitterOAuth;
use Facebook\FileUpload\FacebookFile;
use Facebook\FileUpload\FacebookVideo;
use App\Feedback;
use App\Manager;
use App\Organization;
use App\User;
use App\EmailTemplate;
use App\EmailQueue;
use Illuminate\Http\File;
use App\Http;
use Facebook;

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

    public function __construct() {
        //$this->middleware('oauth', ['except' => ['index']]);
        //$this->middleware('auth:api', ['except' => ['index']]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function postOnFB($fid, $fbObj, $manager) {
        $objFeedback = Feedback::find($fid);
        $image = 'customers/' . $fid . '/' . 'watermark_' . $fid . '.jpg';
        $is_media = 0;
        // Upload a video for a user
        if ($objFeedback->video != null && file_exists('customers/' . $fid . '/' . $objFeedback->video)) {
            $is_media = 1;
            $type = 'videos';
            $video = 'customers/' . $fid . '/' . $objFeedback->video;
            $data = [
                'title' => $objFeedback->feedback,
                //'description' => 'Rating : ' . $objFeedback->rating . "\n" . $objFeedback->feedback,
                'description' => $objFeedback->feedback,
                'source' => $fbObj->videoToUpload($video)];
        } elseif ($objFeedback->profile_pic != null && file_exists($image) && filesize($image) > 0) {
            //for image upload
            $is_media = 1;
            $type = 'photos';
            $data = [
                //'message' => "Rating : " . $objFeedback->rating . "\n" . $objFeedback->feedback,
                'message' => $objFeedback->feedback,
                'source' => $fbObj->fileToUpload('customers/' . $fid . '/' . 'watermark_' . $fid . '.jpg'),
            ];
        } else {
            //for text and link post
            $type = 'feed';
            $data = [
                //'link' => 'www.youtube.com',
                //'message' => 'Rating : ' . $objFeedback->rating . "\n" . $objFeedback->feedback
                'message' => $objFeedback->feedback
            ];
        }

        try {
            //for post on page
            $response = $fbObj->post('/' . $manager->fb_page_id . '/' . $type, $data, $manager->fb_page_token);
            $objFeedback->fb_shared = 1;
            $objFeedback->save();
            if ($is_media == 1) {
                /* ---------- send mail to customer with fb post url ---------- */
                /* ---------- fb post url ------------ */
                $decodeBody = $response->getDecodedBody();
                $decodedId = $decodeBody['id'];

                $endPoint = $response->getRequest()->getEndPoint();    // endpoint = /1558657110856125/videos
                $fbPostUrl = 'https://www.facebook.com' . $endPoint . '/' . $decodedId;
//            echo $fbPostUrl;die;

                $this->sendMailOfFbPostToCustomer($fid, $fbPostUrl, $manager);
            }
        } catch (Facebook\Exceptions\FacebookResponseException $e) {
			#echo '<pre>'; print_r($e->getMessage());die;
            return false;
        } catch (Facebook\Exceptions\FacebookSDKException $e) {
            #echo '<pre>'; print_r($e->getMessage());die;
			return false;
        }

        $graphNode = $response->getGraphNode();
        return $graphNode['id'];
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function postOnTwitter($fid, $manager) {
        $objFeedback = Feedback::find($fid);
        $video = 'customers/' . $fid . '/' . $objFeedback->video;
        $connection = new TwitterOAuth($manager->twitter_consumer_key, $manager->twitter_consumer_secret, $manager->twitter_access_token, $manager->twitter_access_token_secret);
        $is_media = 0;
        $image = 'customers/' . $fid . '/' . 'watermark_' . $fid . '.jpg';
        // Upload a video for a user
        if ($objFeedback->video != null && file_exists($video)) {
            $is_media = 1;
            $media1 = $connection->upload('media/upload', ['media' => $video, 'media_type' => 'video/mp4'], true);
            $parameters = [
                'status' => $objFeedback->feedback,
                'media_ids' => implode(',', [$media1->media_id_string])
            ];
        } elseif ($objFeedback->profile_pic != null && file_exists($image) && filesize($image) > 0) {
            $is_media = 1;
            $media1 = $connection->upload('media/upload', ['media' => $image]);
            $parameters = [
                'status' => $objFeedback->feedback,
                'media_ids' => implode(',', [$media1->media_id_string])
            ];
        } else {
            $parameters = [
                'status' => $objFeedback->feedback
            ];
        }

        $connection->post('statuses/update', $parameters);

        if ($connection->getLastHttpCode() == 200) {
            if ($is_media == 1) {
                $twitterPostData = $connection->get('account/verify_credentials');
                $twiPostId = $twitterPostData->status->id;
                $twiUsername = $twitterPostData->screen_name;
                $twitterPostUrl = "https://twitter.com/" . $twiUsername . "/status/" . $twiPostId;

                /* ---------- send mail to customer with twitter post url ---------- */
                $this->sendMailOfTwitterPostToCustomer($fid, $twitterPostUrl, $manager);
            }
            $objFeedback->twitter_shared = 1;
            $objFeedback->save();
        }
        return $connection->getLastHttpCode();
    }

    /**
     * post on fb/twitter.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function postOnSocialMedia(Request $request, \SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fbObj) {
        $this->validate($request, [
            'feedback_id' => 'required',
            'media_type' => 'required',
            'manager_id' => 'required'
        ]);

        $manager = Manager::where('user_id', $request->manager_id)->first();
        $objFeedback = Feedback::find($request->feedback_id);
        $image = 'customers/' . $request->feedback_id . '/' . $objFeedback->profile_pic;
        $video = 'customers/' . $request->feedback_id . '/' . $objFeedback->video;
        if (($objFeedback->video == null || !file_exists($video)) && $objFeedback->profile_pic != null && file_exists($image)) {
            $this->uploadImage($objFeedback);
        }
//        }elseif ($objFeedback->video != null && !file_exists($video)) {
//            $this->compressVideo($objFeedback);
//        }
        if ($request->media_type == 'facebook') {
            if ($manager) {
                if ($manager->client_id == null || $manager->client_secret == null) {
                    return response()->json(['status' => 'fail', 'code' => 400, 'message' => FB_ACCOUNT_DETAIL]);
                }
                $fbObj = new Facebook\Facebook([
                    'app_id' => $manager->client_id,
                    'app_secret' => $manager->client_secret,
                ]);
                $post = $this->postOnFB($request->feedback_id, $fbObj, $manager);
                if ($post) {
                    return response()->json(['status' => 'success', 'code' => 200, 'message' => FEEDBACK_POST_FB]);
                }
            } else {
                return response()->json(['status' => 'fail', 'code' => 400, 'message' => RECORD_NOT_FOUND]);
            }
        } elseif ($request->media_type == 'twitter') {
            if ($manager->twitter_consumer_key == null || $manager->twitter_consumer_secret == null || $manager->twitter_access_token == null || $manager->twitter_access_token_secret == null) {
                return response()->json(['status' => 'fail', 'code' => 400, 'message' => TWITTER_ACCOUNT_DETAIL]);
            }
            $post = $this->postOnTwitter($request->feedback_id, $manager);
            if ($post == 200) {
                return response()->json(['status' => 'success', 'code' => 200, 'message' => FEEDBACK_POST_TWITTER]);
            } elseif ($post == 401) {
                return response()->json(['status' => 'fail', 'code' => 400, 'message' => INVALID_CREDENTIALS]);
            }
        } elseif ($request->media_type == 'instagram') {
            $this->validate($request, [
                'username' => 'required',
                'password' => 'required'
            ]);
            $post = $this->postOnInstagram($request->feedback_id, $request->username, $request->password, $manager);
//            echo '<pre>';print_r($post);die;
            if (is_numeric($post)) {
                return response()->json(['status' => 'success', 'code' => 200, 'message' => FEEDBACK_ON_INSTAGRAM]);
            } else {
                return response()->json(['status' => 'fail', 'code' => 400, 'message' => $post]);
            }
        }
        return response()->json(['status' => 'fail', 'code' => 400, 'message' => SOMETHING_WENT_WRONG]);
    }

    /**
     * Store fb data in db.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function storeFbData(Request $request, \SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fbObj) {
        $this->validate($request, [
            'client_id' => 'required',
            'client_secret' => 'required',
            'manager_id' => 'required',
            'access_token' => 'required'
        ]);
        $fbObj = new Facebook\Facebook([
            'app_id' => $request->client_id,
            'app_secret' => $request->client_secret,
        ]);

        $manager = Manager::where('user_id', $request->manager_id)->first();
        $manager->client_id = $request->client_id;
        $manager->client_secret = $request->client_secret;

        $data = array();
        $nonExpiryTokenLink = 'https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=' . $request->client_id . '&client_secret=' . $request->client_secret . '&fb_exchange_token=' . $request->access_token;
        $hobj = new \App\CommonHelper();
        $nonExpiryToken = $hobj->generateNonExpiryFbToken($nonExpiryTokenLink);

        if ($nonExpiryToken) {
            $manager->facebook_token = $nonExpiryToken;
            $manager->save();
            $response = $fbObj->get('/me/accounts', $nonExpiryToken);
            $pageData = $response->getDecodedBody();
            if (isset($pageData['data'])) {
                foreach ($pageData['data'] as $key => $value) {
                    $data[$key]['id'] = $value['id'];
                    $data[$key]['name'] = $value['name'];
                }
            }
            return response()->json(['status' => 'success', 'message' => STORE_FB_DATA, 'data' => $data]);
        }
        else
        {
         return response()->json(['status' => 'fail', 'message' => FB_ERROR]);   
        }
        return response()->json(['status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
    }

    /**
     * Store fb page data in db.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function storeFbPageData(Request $request, \SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fbObj) {
        $this->validate($request, [
            'page_id' => 'required',
            'manager_id' => 'required'
        ]);
        $manager = Manager::where('user_id', $request->manager_id)->first();
        $fbObj = new Facebook\Facebook([
            'app_id' => $manager->client_id,
            'app_secret' => $manager->client_secret,
        ]);
        $nonExpiryToken = $manager->facebook_token;
        $response = $fbObj->get('/me/accounts', $nonExpiryToken);
        $pageData = $response->getDecodedBody();

        if (isset($pageData['data'])) {
            foreach ($pageData['data'] as $value) {
                if ($value['id'] == $request->page_id) {
                    $manager->fb_page_id = $request->page_id;
                    $manager->fb_page_token = $value['access_token'];
                    $manager->save();
                    return response()->json(['status' => 'success', 'message' => STORE_FB_PAGE_DATA]);
                }
            }
        }
        return response()->json(['status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
    }

    /**
     * Store twitter data in db.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     * 
     */
    public function storeTwitterData(Request $request) {
        $this->validate($request, [
            'twitter_consumer_key' => 'required',
            'twitter_consumer_secret' => 'required',
            'twitter_access_token' => 'required',
            'twitter_access_token_secret' => 'required',
            'manager_id' => 'required',
        ]);
        $manager = Manager::where('user_id', $request->manager_id)->first();
        $manager->twitter_consumer_key = $request->twitter_consumer_key;
        $manager->twitter_consumer_secret = $request->twitter_consumer_secret;
        $manager->twitter_access_token = $request->twitter_access_token;
        $manager->twitter_access_token_secret = $request->twitter_access_token_secret;
        if ($manager->save()) {
            return response()->json(['status' => 'success', 'message' => STORE_TWITTER_DATA]);
        } else {
            return response()->json(['status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
        }
    }

    /**
     * Store fb page data in db.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function getFbPageData(\SammyK\LaravelFacebookSdk\LaravelFacebookSdk $fbObj, $mid) {

        $manager = Manager::where('user_id', $mid)->first();
        $fbObj = new Facebook\Facebook([
            'app_id' => $manager->client_id,
            'app_secret' => $manager->client_secret,
        ]);
        $nonExpiryToken = $manager->facebook_token;
        if ($nonExpiryToken) {
            $response = $fbObj->get('/me/accounts', $nonExpiryToken);
            $pageData = $response->getDecodedBody();
            if (isset($pageData['data'])) {
                foreach ($pageData['data'] as $key => $value) {
                    $data[$key]['id'] = $value['id'];
                    $data[$key]['name'] = $value['name'];
                }
            }
        }
        if ($manager->save()) {
            return response()->json(['status' => 'success', 'data' => $data, 'selected_page' => $manager->fb_page_id]);
        } else {
            return response()->json(['status' => 'fail', 'message' => SOMETHING_WENT_WRONG]);
        }
    }

    /**
     * Post feedback on instagram.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function postOnInstagram($fid, $username, $password, $manager) {
        $debug = false;
        $truncatedDebug = false;
        $objFeedback = Feedback::find($fid);
//        \InstagramAPI\Instagram::$allowDangerousWebUsageAtMyOwnRisk = true;
        $instagram = new \InstagramAPI\Instagram($debug, $truncatedDebug);

        $image = 'customers/' . $fid . '/' . 'watermark_' . $fid . '.jpg';
        try {
//            $instagram->setUser($username, $password);
            $instagram->login($username, $password, true);
        } catch (\Exception $e) {
            if ($e->getMessage() === "InstagramAPI\Response\LoginResponse: The password you entered is incorrect. Please try again.") {
                return 'The password you entered is incorrect. Please try again.';
            } else {
                return $e->getMessage();
            }
        }

        if ($objFeedback->video != null && file_exists('customers/' . $fid . '/' . $objFeedback->video)) {
            $videoFilename = 'customers/' . $fid . '/' . $objFeedback->video;
            //$captionText = 'Rating : ' . $objFeedback->rating . "\n" . $objFeedback->feedback;
            $captionText = $objFeedback->feedback;

            try {
                $intResponse = $instagram->timeline->uploadVideo($videoFilename, ['caption' => $captionText]);
                $instaCode = $intResponse->getMedia()->getCode();
                $instUsername = $intResponse->getMedia()->getUser()->getUsername();
                $instaPostUrl = "https://www.instagram.com/p/" . $instaCode . "/?taken-by=" . $instUsername;

                /* ---------- send mail to customer with insta post url ---------- */
                $this->sendMailOfInstaPostToCustomer($fid, $instaPostUrl, $manager);

                $objFeedback->insta_shared = 1;
                $objFeedback->save();
                return 0;
            } catch (\Exception $e) {
                return $e->getMessage();
            }
        } elseif ($objFeedback->profile_pic != null && file_exists($image) && filesize($image) > 0) {
            $photoFilename = 'customers/' . $fid . '/' . 'watermark_' . $fid . '.jpg';
            //$captionText = 'Rating : ' . $objFeedback->rating . "\n" . $objFeedback->feedback;
            $captionText = $objFeedback->feedback;
            try {
                $intResponse = $instagram->timeline->uploadPhoto($photoFilename, ['caption' => $captionText]);
                $instaCode = $intResponse->getMedia()->getCode();
                $instUsername = $intResponse->getMedia()->getUser()->getUsername();
                $instaPostUrl = "https://www.instagram.com/p/" . $instaCode . "/?taken-by=" . $instUsername;

                /* ---------- send mail to customer with insta post url ---------- */
                $this->sendMailOfInstaPostToCustomer($fid, $instaPostUrl, $manager);

                $objFeedback->insta_shared = 1;
                $objFeedback->save();
                return 0;
            } catch (\Exception $e) {
                return $e->getMessage();
            }
        } else {
            return NO_MEDIA_FOUND;
        }
    }

    /**
     * Image watermark.
     *
     * @return \Illuminate\Http\Response
     */
    public function uploadImage($objFeedback) {
        $hobj = new \App\CommonHelper();
        if (!file_exists('customers/' . $objFeedback->id . '/' . 'watermark_' . $objFeedback->id . '.jpg')) {
            $currentPath = 'customers' . '/' . $objFeedback->id . '/' . $objFeedback->profile_pic;
            $destinationPath = 'customers' . '/' . $objFeedback->id . '/';
            $hobj->processImageUpload($currentPath, $destinationPath, $objFeedback->profile_pic, $objFeedback->id);
        }
        return 0;
    }

    /**
     * Video compression.
     *
     * @return \Illuminate\Http\Response
     */
//    public function compressVideo($objFeedback)
//    {
//        $cvideo = 'customers/' . $objFeedback->id . '/' .'compressed_'.$objFeedback->id.'.mp4';
//        $video = 'customers/' . $objFeedback->id . '/' .$objFeedback->id.'.mp4';
//        if (!file_exists($cvideo)) {
//            echo shell_exec("ffmpeg -i $video -vf scale=600:336.5 $cvideo -hide_banner");
//        }
//        return 0;
//    }

    /**
     * Store instagram data in db.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function storeInstagramData(Request $request) {
        $this->validate($request, [
            'insta_username' => 'required',
            'insta_pwd' => 'required',
            'manager_id' => 'required',
        ]);
        $helperObj = new \App\CommonHelper();
        $manager = Manager::where('user_id', $request->manager_id)->first();
        $manager->insta_username = $request->insta_username;
        $manager->insta_password = $helperObj->encrypt($request->insta_pwd);

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

    /**
     * send mail to customer
     * @param type $fid
     * @updated by jatin parmar
     * @param type $fbPostUrl
     */
    public function sendMailOfFbPostToCustomer($fid, $fbPostUrl, $manager) {
        $helperobj = new \App\CommonHelper();
        $feedback = Feedback::find($fid);
        $user = User::find($feedback->user_id);

        if (!empty($user) && !empty($feedback)) {

            //  $manager = Manager::find($feedback->user_id);

            if ($manager->isHippa == '1') {
                $body = EmailTemplate::where('slug', 'SEND_FB_POST_URL_MEDICAL')->first();
            } else {
                $body = EmailTemplate::where('slug', 'SEND_FB_POST_URL_NONMEDICAL')->first();
            }

            $organization = Organization::find($feedback->organization_id);

            $organization_name = $organization->name;

            if ($organization) {
                $docUrl = $helperobj->publicPath();

                if($organization->organization_pic != "")
                {
                    $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;
                }
                
            } else {
                $image = ANGULARURL . PU_LOGO;
            }
            $tmp1 = str_replace("##FB_POST_LINK##", $fbPostUrl, $body['description']);
            $tmp2 = str_replace("##username##", $user->name, $tmp1);
            $tmp2 = str_replace("##business_name##", $organization_name, $tmp2);
            $tmp3 = str_replace("##LOGO##", $image, $tmp2);
            $tmp4 = str_replace("##YEAR##", date('Y'), $tmp3);
            $data['html'] = str_replace("##SUPPORT_LINK##", SUPPORT_LINK, $tmp4);
            $subject = str_replace("##MANAGER##", ucfirst($organization_name), $body['subject']);

            $emailQueue = new EmailQueue();
            $emailQueue->type = TYPE_SENDLINK;
            $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();
        }
    }

    /**
     * send mail to customer of twitter post link
     * @param type $fid
     * @param type $twitterPostUrl\
     */
    public function sendMailOfTwitterPostToCustomer($fid, $twitterPostUrl, $manager) {
        $helperobj = new \App\CommonHelper();

        $feedback = Feedback::find($fid);
        $user = User::find($feedback->user_id);

        if (!empty($user) && !empty($feedback)) {

            //  $manager = Manager::find($feedback->user_id);

            if ($manager->isHippa == '1') {
                $body = EmailTemplate::where('slug', 'SEND_TWITTER_POST_URL_MEDICAL')->first();
            } else {
                $body = EmailTemplate::where('slug', 'SEND_TWITTER_POST_URL_NONMEDICAL')->first();
            }


            $organization = Organization::find($feedback->organization_id);

            $organization_name = $organization->name;

            if ($organization) {
                $docUrl = $helperobj->publicPath();

                if($organization->organization_pic != "")
                {
                    $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;

                }
                
            } else {
                $image = ANGULARURL . PU_LOGO;
            }
            $tmp1 = str_replace("##TWITTER_POST_LINK##", $twitterPostUrl, $body['description']);
            $tmp2 = str_replace("##username##", $user->name, $tmp1);
            $tmp2 = str_replace("##business_name##", $organization_name, $tmp2);
            $tmp3 = str_replace("##LOGO##", $image, $tmp2);
            $data['html'] = str_replace("##SUPPORT_LINK##", SUPPORT_LINK, $tmp3);
            $subject = str_replace("##MANAGER##", ucfirst($organization_name), $body['subject']);

            $emailQueue = new EmailQueue();
            $emailQueue->type = TYPE_SENDLINK;
            $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();
        }
    }

    /**
     * send mail to customer of instagram post link
     * @param type $fid
     * @param type $instaPostUrl\
     */
    public function sendMailOfInstaPostToCustomer($fid, $instaPostUrl, $manager) {

        $helperobj = new \App\CommonHelper();

        $feedback = Feedback::find($fid);
        $user = User::find($feedback->user_id);

        if (!empty($user) && !empty($feedback)) {

            ///   $manager = Manager::find($feedback->user_id);

            if (!empty($manager)) {

                if ($manager->isHippa == '1') {
                    $body = EmailTemplate::where('slug', 'SEND_INSTAGRAM_POST_URL_MEDICAL')->first();
                } else {
                    $body = EmailTemplate::where('slug', 'SEND_INSTAGRAM_POST_URL_NONMEDICAL')->first();
                }


                $organization = Organization::find($feedback->organization_id);

                $organization_name = $organization->name;

                if ($organization) {
                    $docUrl = $helperobj->publicPath();

                    if($organization->organization_pic != "")
                    {

                        $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;
                    }
                    
                } else {
                    $image = ANGULARURL . PU_LOGO;
                }
                $tmp1 = str_replace("##INSTAGRAM_POST_LINK##", $instaPostUrl, $body['description']);
                $tmp2 = str_replace("##username##", $user->name, $tmp1);
                $tmp2 = str_replace("##business_name##", $organization_name, $tmp2);
                $tmp3 = str_replace("##LOGO##", $image, $tmp2);
                $data['html'] = str_replace("##SUPPORT_LINK##", SUPPORT_LINK, $tmp3);
                $subject = str_replace("##MANAGER##", ucfirst($organization_name), $body['subject']);

                $emailQueue = new EmailQueue();
                $emailQueue->type = TYPE_SENDLINK;
                $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();
            }
        }
    }

}
