<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\EmailTemplate;
use App\Organization;
use App\EmailQueue;
use App\User;

class SycleSendLinkNotification extends Command
{
    protected $signature = 'sycleNotification:sendLink';
    protected $description = 'Sycle Send Link Notification';

    /**
     * Execute the command.
     *
     * @return void
     */
    public function handle()
    {
        $time = date('Y-m-d H:i:s');
        $feedback = DB::select(" SELECT feedback.* , feedback_send_link_log.short_url, feedback_send_link_log.long_url 
                                FROM feedback 
                                LEFT JOIN feedback_send_link_log ON feedback_send_link_log.feedback_id = feedback.id  
                                WHERE DATE_FORMAT(send_sycle_time,'%Y-%m-%d %H:%i:%s') <= '$time'
                                AND is_send_link = 0 
                                AND imported_from = 'Sycle' 
                                AND is_queue = 1
                                AND appointment_status IN ('Confirmed', 'Completed')
                                Limit 50 ");

        foreach ($feedback as $key => $value) {
            $this->sendLinkToPatients($value);
        }

        $this->updateCronLog();
        echo "\n  Procedure done successfully. \n";
    }

    public function updateCronLog()
    {
        $date = date('Y-m-d H:i:s');
        DB::table('cron_log')->where('name', $this->signature)->update(['cron_at' => $date]);
    }

    /* Update Feedback tbl is_send_link to 1/**
     * *
     * @return void
     */
    public function updateSendLinkFlag($id)
    {
        $feedback = DB::table('feedback')->where('id', $id)->update(['is_send_link' => 1]);
    }

    public function updateFeedbackLogDates($id)
    {
        $date = date('Y-m-d');
        $next3daydate = date('Y-m-d', strtotime(date('Y-m-d') . " +3 days"));
        $next6daydate = '';

        $feedback = DB::table('feedback_send_link_log')->where('feedback_id', $id)->update(['next6daydate' => null, 'next3daydate' => $next3daydate, 'created_date' => $date]);
    }

    public function sendLinkToPatients($feedback)
    {
        $link = $feedback->long_url;
        $shortUrl = $feedback->short_url;

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

        if (!empty($body)) {
            $organization = Organization::find($feedback->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;
                $image = DOMAIN_URL . '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##", $shortUrl, $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']);

            if ($feedback->email != '' && filter_var($feedback->email, FILTER_VALIDATE_EMAIL)) {
                $this->sendMail(array('mail_body' => $data['html'], 'mail_subject' => $subject, 'to_email' => $feedback->email));
            }

            $this->updateSendLinkFlag($feedback->id);
            $this->updateFeedbackLogDates($feedback->id);
        }

        if ($feedback->mobile != '') {
            if (!is_numeric($shortUrl)) {
                $link = $shortUrl;
                $orgName = $organization->name ? $organization->name : '-';
                $data['type'] = 'feedback';
                $data['to'] = $feedback->mobile;
                // $data['msgBody'] = $orgName . ' Your feedbacklink is ' . $link;
                $data['msgBody'] = 'Hi,We would like to thank you for choosing ' . $orgName . ' 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;
                $data['media'] = $mobileImg;
    
                $smsResult = $helperobj->sendSMS($data);
            }
        }
    }

    public function sendMail($value)
    {
        $data['html'] = $value['mail_body'];
        $subject = $value['mail_subject'];
        $email = $value['to_email'];
        Mail::send('emails.email', $data, function ($message) use ($subject, $email) {
            $message->from(FROM_IN_MAIL, APP_NAME_IN_MAIL);
            $message->to($email);
            $message->subject($subject);
        });
    }
}
