<?php
use PHPMailer\PHPMailer\PHPMailer;
use Plivo\RestClient;
use Plivo\Exceptions\PlivoRestException;
//use Plivo\RestAPI;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
class coFunction{

    function sendEmail($isSMTP, $host, $port, $SMTPSecure, $SMTPAuth, $from, $from_name, $password, $to, $cc, $bcc, $subject, $message, $files, $tracking, $random_id, $count, $recipient_type, $id_related, $header, $footer, $strg_pdf, $name_pdf = ""){ //$header, $footer, $strg_pdf (estas 3 ultimas usadas por ahora solo para infinity, se manda header, footer y string de PDF para attachment)
        //var_dump($isSMTP, $host, $port, $SMTPSecure, $SMTPAuth, $from, $from_name, $password, $to, $cc, $bcc, $subject, $message, $files, $tracking, $random_id, $count, $recipient_type, $id_related, $header, $footer, $strg_pdf); //die();
        require '/var/www/html/utilities/cron_hunity/vendor/autoload.php';
        $mail = new PHPMailer;
        //RDS
        $conn = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNOM) or die("Connection failed: " . mysqli_connect_error());
        /* Database connection end */
        $mail->ClearAddresses();
        $mail->ClearCCs();
        $mail->ClearBCCs();

        $addAddress = explode(",", $to);
        $addCC = explode(",", $cc);
        $addBCC = explode(",", $bcc);
        if ($isSMTP == 1) {
            $mail->isSMTP();
        }
        $mail->CharSet = "utf-8";
        //$mail->SMTPDebug = 3;

        $mail->Host = $host;
        $mail->Port = $port;
        if ($SMTPSecure == 1) {
            $mail->SMTPSecure = 'tls';
        } elseif ($SMTPSecure == 2) {
            $mail->SMTPSecure = 'ssl';
        } else {
            $mail->SMTPSecure = false;
        }
        if ($SMTPAuth == 1) {
            $mail->SMTPAuth = true;
        } else {
            $mail->SMTPAuth = false;
        }
        $mail->Username = $from;
        $mail->Password = $password;
        $mail->setFrom($from, $from_name);
        foreach ($addAddress as $email) {
            $mail->addAddress($email);
        }
        foreach ($addCC as $email) {
            $mail->addCC($email);
        }
        foreach ($addBCC as $email) {
            $mail->addBCC($email);
        }
        $mail->Subject = $subject;
        //$mail->Body = $email_plain_message;
        //$mail->AltBody = $email_plain_message;
        //$mail->addAttachment($attachment);

        if (is_array($files)) { // Armado de envio de attachs
            for ($ct = 0; $ct <= $count; $ct++) {
                $mail->AddAttachment($files['files-' . $ct]['tmp_name'], $files['files-' . $ct]['name']);
            }
        }

        if ($strg_pdf != '') { // Caso PDF de DomPDF en correo para agentes
            // var_dump(count($strg_pdf)); die();         
            for ($i = 0; $i < count($strg_pdf); $i++) {
                if($name_pdf != ""){
                    $mail->AddStringAttachment($strg_pdf[$i], ''.$name_pdf[$i].'.pdf', 'base64', 'application/pdf');
                }else{
                    $mail->AddStringAttachment($strg_pdf[$i], ''.$from_name.'.pdf', 'base64', 'application/pdf');
                }                
            }
        }

        // Inicio tracking Pixel (construye el body con el message a enviar)
        if ($tracking == 1) {
            $originalImage = "/var/www/html/v103/img/tracking/LogoPowered.jpg";
            $userImage = "/var/www/html/v103/img/tracking/LogoPowered_" . $random_id . ".jpg";
            $urlImageSource = "https://services.gosmartcrm.com/img/tracking/LogoPowered_" . $random_id . ".jpg";
            copy($originalImage, $userImage);

            if (substr_count($message,'<html>') > 0) {
                $message = str_replace("</html>", "<img src=" . $urlImageSource . "  height='36' width='100'></html>", $message);
            } else {
                $message = "<html>".$message."<img src=" . $urlImageSource . "  height='36' width='100'></html>";
            }
        }
        //Fin tracking pixel

        // Inicio verificacion merge fields (construye el body con campos genericos)
        if ($recipient_type == 1) { //caso contact
            $sql = "SELECT * FROM contacts WHERE id = $id_related";
            $query = mysqli_query($conn, $sql) or die($sql);
            $data = mysqli_fetch_assoc($query);

        } elseif ($recipient_type == 2) { //caso lead
            $sql = "SELECT * FROM leads WHERE id = $id_related";
            $query = mysqli_query($conn, $sql) or die($sql);
            $data = mysqli_fetch_assoc($query);

        } elseif ($recipient_type == 3) { //caso user_crm
            $sql = "SELECT * FROM user_crm WHERE id = $id_related";
            $query = mysqli_query($conn, $sql) or die($sql);
            $data = mysqli_fetch_assoc($query);
        }

        $sql = "SELECT name, value, type_merge_field FROM merge_field WHERE status = 1";
        $query = mysqli_query($conn, $sql) or die($sql);
        extract(mysqli_fetch_array($query));

        foreach ($query as $row) {

            $merge_field_name = $row['name'];
            $merge_field_value = $row['value'];

            if (strpos($message, $merge_field_name) == true) {
                $value_data = $data["$merge_field_value"];
                $message = str_replace($merge_field_name, $value_data, $message);
            }
        }
        //Fin verificacion merge fields ---------------------------------------------------------------------------------------------------

        $mail->Body = $message;
        $mail->isHTML(true);

        // Inicio Caso Formularios Infinity, toca estandarizar procedimiento para otros clientes (tablas, disposicion de imagenes para otros header/footer, etc) DJ
        if ($header == 1) {
        $mail->AddEmbeddedImage('../../assets/media/img/images/header.png', 'header');
        }
        if ($footer == 1 ) {
        $mail->AddEmbeddedImage('../../assets/media/img/images/footer.png', 'footer');
        }
        // Fin Caso Formularios Infinity
        // print_r($mail->ErrorInfo);dies();
        //$mail->send();
        $mail->SMTPOptions = array(
        'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
            )
        );
        if (!$mail->send()) {
            //echo "Mailer Error: " . $mail->ErrorInfo;
            return 'Email Error'. $mail->ErrorInfo;
        } else {
            //echo "Message sent!";
            return 'Email Sent';
        }
    }

    function sendSms($params){
        //PLIVO
        include './general.php';
        require '../../vendor/autoload.php';

        $conn = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNOM) or die("Connection failed: " . mysqli_connect_error()); /* Database connection end */
        $from = $params['src'];
        $to = $params['dst'];
        $message = $params['text'];

        $sql = "SELECT auth_id, auth_token FROM provides_number WHERE number_phone LIKE '%$from%'";
        $query = mysqli_query($conn, $sql) or die($sql);
        extract(mysqli_fetch_array($query));

       $restClient = new RestClient($auth_id, $auth_token);//20/082020 - jc puse las $auth_id, $auth_token

        try
        {
            $response = $restClient->messages->create(
                        $from, #src
                        [$to], #dst
                        $message, #text
                        ["url"=>"https://cash.gosmartcrm.com/app/ws/delivery_report.php"]
            );

            //$calluuid = $response->getmessageUuid(0)[0];
            $statusCode = $response->statusCode;

        }
        catch(PlivoRestException $ex)
        {
            //print_r($ex);
            $statusCode = $ex->getstatusCode();
            $statusMessage = $ex->getmessage();
            $error_message = date('d/m/Y h:i:s a', time()) . " || Error Sending SMS || Status Code: " . $statusCode . " || Error Message: " . $statusMessage . "\n";
        }

        if ($statusCode == 200 || $statusCode == 201 || $statusCode == 202) {

            return 'successful';

        } else {

            error_log($error_message, 3, '/var/www/html/v103/app/ws/plivoErrorLog');

            return array ('error', $statusMessage);
        }

        // $response = $restClient->messages->create(
        //     $from, #src
        //     [$to], #dst
        //     $message #text
        // );
        // // var_dump($response);
        // // var_dump("from ==$from to ==$to message ==$message");
        // // die();
        // // if ($response['statusCode'] != '202') {
        // //     return $response['response']['error'];
        // //     //var_dump($response['status']);die();
        // // }else{
        // //     return 'succeful';
        // //     //var_dump($response['status']);die();
        // // }
        // return 'succeful';

    }

    function curlSetOpt($url, $jsonData){

        $ch = curl_init($url);//The JSON data.
        $jsonData = json_encode($jsonData);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_POST, 1);//Attach our encoded JSON string to the POST fields.
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);//Set the content type to application/json
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $curl = json_decode($result, true);
        curl_close($ch);
        return $curl;
    }

}

if (isset($_POST['method'])){
    if( $_POST['method']=='setToken'){
        $t = new coFunction();
        $t->setToken($_POST['token']);
    }
}