<?php
/**
 * Created by PhpStorm.
 * User: Moldedcraft 1
 * Date: 20 Sep 2019
 * Time: 10:01 AM
 */

namespace RxConnexionBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SendSmsReminderCommand extends ContainerAwareCommand
{
    const NUMBER_PREFIX = ""; // 1 = (+1)Canada , 639 = (+639)PHIL

    /**
     * Configure a new Command Line
     */
    protected function configure()
    {
        $this
            ->setName('rxconexion:send-sms-reminder')
            ->setDescription('Send Sms Reminder.');
    }


    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $dt = new \DateTime();
        $em = $this->getContainer()->get('doctrine.orm.entity_manager');

        $nexmoKey = $this->getContainer()->getParameter('nexmo_key');
        $nexmoSecret = $this->getContainer()->getParameter('nexmo_secret');
        $nexmoCanadianVirtualNumber = $this->getContainer()->getParameter('nexmo_canadian_virtual_number');

        $basic  = new \Nexmo\Client\Credentials\Basic($nexmoKey, $nexmoSecret);
        $client = new \Nexmo\Client($basic);

        $interval = $em->getRepository('RxConnexionBundle:SystemParameterEntity')->getValueByDesc('SMS Appointment Reminder');
        $date = $dt->modify(intval($interval)." days")->format("Y-m-d 00:00:00");

        $schedules = $em->getRepository('RxConnexionBundle:ScheduleEntity')->command_getPatientsWithAppointment($date);

        foreach($schedules as $schedule){
            $patient_firstName = preg_replace("/[^A-Z a-z -]/", "", $schedule['patient_firstName'] ) ;
            $healthFacility_desc = $schedule['healthFacility_desc'];
            $patientNum = (!empty($schedule['patientMobile'] && !is_null($schedule['patientMobile'])) ? $schedule['patientMobile'] : $schedule['patientPhone']);

            if(!empty($patientNum) && !is_null($patientNum)){
                
                $patientNumber = preg_replace("/[^0-9]/", "", $patientNum );
                $scheduleDate = $schedule['scheduleDate'];
                $startTime = $schedule['startTime'];
                $endTime = $schedule['endTime'];
                $chartType = $schedule['chartType'];

                $msg  = "Hello $patient_firstName. ";
                $msg .= "This is a reminder that you have $chartType appointment on $scheduleDate, at $startTime - $endTime, with $healthFacility_desc.";

                $smsData = array(
                    'to' => strlen($patientNumber) == 11 ? $patientNumber : self::NUMBER_PREFIX . $patientNumber,
                    'from' => $nexmoCanadianVirtualNumber,
                    'text' => $msg
                );
                # print_r($smsData);
                try {
                    $message = $client->message()->send($smsData);
                    $response = $message->getResponseData();

                    if($response['messages'][0]['status'] == 0) {
                        echo "The message was sent successfully\n";
                    } else {
                        echo "The message failed with status: " . $response['messages'][0]['status'] . "\n";
                    }
                } catch (Exception $e) {
                    echo "The message was not sent. Error: " . $e->getMessage() . "\n";
                }

                sleep(1.2);

            }






        }


    }



}