<?php

namespace App;

use App\SubscriptionPlans;
use Twilio\Rest\Client;
use Twilio\Exceptions\RestException;
use App\Organization;
use DB;

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

    /**
     * Return the path to public dir
     * @param null $path
     * @return string
     */
    public function publicPath($path = null)
    {
        return rtrim(app()->basePath('public/' . $path), '/');
    }

    // public function routeSortner($longUrl = null)
    // {

    //     //FCM api URL
    //     $url = SHORTEN_AUTH_URL;

    //     //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
    //     $serverKey = URL_AUTH_KEY;

    //     $fields = array();

    //     $fields['longUrl'] = $longUrl;
    //     $fields['API_KEY'] = $serverKey;

    //     //header with content_type api key
    //     $headers = array(
    //         'Content-Type:application/json',
    //     );

    //     $chr = curl_init();
    //     curl_setopt($chr, CURLOPT_URL, $url . '?key=' . $serverKey);
    //     curl_setopt($chr, CURLOPT_POST, true);
    //     curl_setopt($chr, CURLOPT_HTTPHEADER, $headers);
    //     curl_setopt($chr, CURLOPT_RETURNTRANSFER, true);
    //     curl_setopt($chr, CURLOPT_SSL_VERIFYPEER, false);
    //     curl_setopt($chr, CURLOPT_POSTFIELDS, json_encode($fields));
    //     $result = curl_exec($chr);
    //     if (isset(json_decode($result)->id)) {
    //         curl_close($chr);
    //         $shortUrl = json_decode($result)->id;

    //         return $shortUrl;
    //     } else {
    //         return 0;
    //     }
    // }

    public function routeSortner($longUrl = null)
    {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, 'http://tinyurl.com/api-create.php?url='.$longUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    public function routeSortnerNew($longUrl = null, $feedback)
    {
        try {
            $tokenizer=uniqid().'_'.$feedback->id;
            $shortURL=ANGULARURL."feedback-invitation/".$tokenizer;
            $feedback_link_log=array(
                        'token'=>$tokenizer,
                        'long_url'=>$longUrl,
                        'short_url'=>$shortURL,
                        'feedback_id'=>$feedback->id,
                        'is_clicked'=>0,
                        'is_clicked_count'=>0,
                        'created_date'=>date('Y-m-d'),
                        'next3daydate'=>date('Y-m-d', strtotime(date('Y-m-d') . " +3 days")),
                        'next6daydate'=>date('Y-m-d', strtotime(date('Y-m-d') . " +9 days")),
                    );
            $id=DB::table('feedback_send_link_log')->insertGetId($feedback_link_log);
            if ($id) {
                return $shortURL;
            } else {
                return $longUrl;
            }
        } catch (Exception $e) {
            return $longUrl;
        }
    }

    public function decrypt($source = '')
    {
        $sources = base64_decode(base64_decode($source));
        if (isset($sources)) {
            return base64_decode($sources);
        } else {
            return '';
        }
    }

    public function encrypt($source = '')
    {
        $sources = base64_encode(base64_encode($source));
        $sources = str_replace('=', '', $sources);
        return base64_encode($sources);
    }


    public function sendSMS($data = array())
    {
        $sid = TWILIO_SID;
        $token = TWILIO_AUTH_TOKEN;
        $client = new Client($sid, $token);

        if (isset($data['type']) && $data['type'] == 'feedback') {
            $body = $data['msgBody'];
        } elseif (isset($data['type']) && $data['type'] == 'coupon') {
            $body = $data['html'];
        } else {
            $body = 'Welcome to INCITE REVIEWS app';
        }
        
        $to       = isset($data['to']) ? '+1'.$data['to'] : '+918320034252';
        
        $response = [];
        if (SMS_SEND == 1) {
            try {
                     $client->messages->create($to, array(
                    // A Twilio phone number you purchased at twilio.com/console
                    'from' => TWILIO_FROM_CONTACT_NO,
                    'body' => $body ,
                    "mediaUrl" => $data['media']
                         ));
            } catch (RestException $e) {
                if ($e->getStatusCode() == 400) {
                    // $response['message'] = 'We could not send the message to provided number.';
                    $response['message'] = 'We have send the review link to the provided email. Can not able to send the link on the provided mobile number.';
                } else {
                    $response['message'] = SOMETHING_WENT_WRONG;
                }
            }
        }
        return $response;
    }

    public function stripeConfiguration()
    {
        $params = array(
            "testmode" => STRIPE_TESTMODE,
            "private_live_key" => PRIVATE_LIVE_KEY,
            "public_live_key" => PUBLIC_LIVE_KEY,
            "private_test_key" => PRIVATE_TEST_KEY,
            "public_test_key" => PUBLIC_TEST_KEY
        );

        if ($params['testmode'] == "on") {
            \Stripe\Stripe::setApiKey($params['private_test_key']);
            $pubkey = $params['public_test_key'];
        } else {
            \Stripe\Stripe::setApiKey($params['private_live_key']);
            $pubkey = $params['public_live_key'];
        }

        return $pubkey;
    }

    public function getPlanExpiryDate($planId, $mode = 'new', $expiryDate = '')
    {
        $noOfDays = 0;

        if ($expiryDate) {
            if (strtotime($expiryDate) >=strtotime(date('Y-m-d'))) {
                $datediff = strtotime($expiryDate) - strtotime(date('Y-m-d'));
                $noOfDays = round(($datediff / (60 * 60 * 24)));
            } else {
                    $noOfDays =0;
            }

            if ($noOfDays > 7) {
                return $noOfDays;
            }
        }

        if ($planId) {
            $objPlan = SubscriptionPlans::find($planId);
            $validity = $objPlan->validity;
            //$validity = 'year';
            switch ($validity) {
                case "year":
                    $days = $noOfDays + 365;
                    $enddate = date('Y-m-d', strtotime($days . " days", strtotime(date('Y-m-d'))));

                    return $enddate;
                    break;
                    
                case "month":
                    //$days = $noOfDays + 365;
                    $enddate = date('Y-m-d', strtotime($noOfDays . " days", strtotime(date('Y-m-d'))));

                    $enddate = date('Y-m-d', strtotime("+1 months", strtotime($enddate)));

                    return $enddate;
                    break;
//                case "3-month":
//                    $enddate = date('Y-m-d', strtotime($noOfDays . " days", strtotime(date('Y-m-d'))));
//                    $enddate = date('Y-m-d', strtotime("+3 months", strtotime($enddate)));
//
//                    return $enddate;
//                    break;
//                case "6-month":
//                    $enddate = date('Y-m-d', strtotime($noOfDays . " days", strtotime(date('Y-m-d'))));
//                    $enddate = date('Y-m-d', strtotime("+6 months", strtotime($enddate)));
//
//                    return $enddate;
//                    break;
//                case "day":
//                    $days = $noOfDays + 1;
//                    $enddate = date('Y-m-d', strtotime($days . " days", strtotime(date('Y-m-d'))));
//
//                    return $enddate;
//                    break;
                default:
                    return date('Y-m-d', strtotime("+365 days", strtotime(date('Y-m-d'))));
                    break;
            }
        }
    }

    public function renderTextOnGdImage(&$sourceGdImage, $text, $size, $color, $opacity, $rotation, $align)
    {
        $sourceWidth = imagesx($sourceGdImage);
        $sourceHeight = imagesy($sourceGdImage);
        $bbb = $this->imagettfbboxFixed($size, $rotation, $text);
        $x00 = min($bbb[0], $bbb[2], $bbb[4], $bbb[6]) - WATERMARK_MARGIN_ADJUST;
        $x11 = max($bbb[0], $bbb[2], $bbb[4], $bbb[6]) + WATERMARK_MARGIN_ADJUST;
        $y00 = min($bbb[1], $bbb[3], $bbb[5], $bbb[7]) - WATERMARK_MARGIN_ADJUST;
        $y11 = max($bbb[1], $bbb[3], $bbb[5], $bbb[7]) + WATERMARK_MARGIN_ADJUST;
        $bbWidth = abs($x11 - $x00);
        $bbHeight = abs($y11 - $y00);
        switch ($align) {
            case 11:
                $bpy = -$y00;
                $bpx = -$x00;
                break;
            case 12:
                $bpy = -$y00;
                $bpx = $sourceWidth / 2 - $bbWidth / 2 - $x00;
                break;
            case 13:
                $bpy = -$y00;
                $bpx = $sourceWidth - $x11;
                break;
            case 21:
                $bpy = $sourceHeight / 2 - $bbHeight / 2 - $y00;
                $bpx = -$x00;
                break;
            case 22:
                $bpy = $sourceHeight / 2 - $bbHeight / 2 - $y00;
                $bpx = $sourceWidth / 2 - $bbWidth / 2 - $x00;
                break;
            case 23:
                $bpy = $sourceHeight / 2 - $bbHeight / 2 - $y00;
                $bpx = $sourceWidth - $x11;
                break;
            case 31:
                $bpy = $sourceHeight - $y11;
                $bpx = -$x00;
                break;
            case 32:
                $bpy = $sourceHeight - $y11;
                $bpx = $sourceWidth / 2 - $bbWidth / 2 - $x00;
                break;
            case 33:
                $bpy = $sourceHeight - $y11;
                $bpx = $sourceWidth - $x11;
                break;
        }
        $alphaColor = imagecolorallocatealpha($sourceGdImage, hexdec(substr($color, 0, 2)), hexdec(substr($color, 2, 2)), hexdec(substr($color, 4, 2)), 127 * (100 - $opacity) / 100);
        return imagettftext($sourceGdImage, $size, $rotation, $bpx, $bpy, $alphaColor, WATERMARK_FONT_REALPATH, $text);
    }

    /*
     * Fix for the buggy imagettfbbox implementation in gd library
     */

    public function imagettfbboxFixed($size, $rotation, $text)
    {
        $bbb = imagettfbbox($size, 0, WATERMARK_FONT_REALPATH, $text);
        $aaa = deg2rad($rotation);
        $ccc = cos($aaa);
        $sss = sin($aaa);
        $rrr = array();
        for ($i = 0; $i < 7; $i += 2) {
            $rrr[$i + 0] = round($bbb[$i + 0] * $ccc + $bbb[$i + 1] * $sss);
            $rrr[$i + 1] = round($bbb[$i + 1] * $ccc - $bbb[$i + 0] * $sss);
        }
        return $rrr;
    }

    /*
     * Wrapper function for opening file, calling watermark function and saving file
     */

    public function createWatermarkFromString($sourceFilePath, $outputFilePath, $text, $size, $color, $opacity, $rotation, $align)
    {

        list($sourceWidth, $sourceHeight, $sourceType) = getimagesize($sourceFilePath);
        if ($sourceWidth > 1080) {
            $percent = 0.5;
        } elseif ($sourceWidth < 320) {
            $percent = 1.5;
        } else {
            $percent = 1;
        }
        $newwidth = $sourceWidth * $percent;
        $newheight = $sourceHeight * $percent;
        if ($sourceType === null) {
            return false;
        }

        $thumb = imagecreatetruecolor($newwidth, $newheight);
        switch ($sourceType) {
            case IMAGETYPE_GIF:
                $sourceGdImage = imagecreatefromgif($sourceFilePath);
                break;
            case IMAGETYPE_JPEG:
                $sourceGdImage = imagecreatefromjpeg($sourceFilePath);
                break;
            case IMAGETYPE_PNG:
                $sourceGdImage = imagecreatefrompng($sourceFilePath);
                break;
            default:
                return false;
        }
        imagecopyresized($thumb, $sourceGdImage, 0, 0, 0, 0, $newwidth, $newheight, $sourceWidth, $sourceHeight);
        $this->renderTextOnGdImage($sourceGdImage, $text, $size, $color, $opacity, $rotation, $align);
        imagejpeg($thumb, $outputFilePath, WATERMARK_OUTPUT_QUALITY);
        imagedestroy($sourceGdImage);
    }

    /*
     * Uploaded file processing function
     * PARAMETER DESCRIPTION
     * (1) SOURCE FILE PATH
     * (2) OUTPUT FILE PATH
     * (3) THE TEXT TO RENDER
     * (4) FONT NAME -- MUST BE A *FILE* NAME
     * (5) FONT SIZE IN POINTS
     * (6) FONT COLOR AS A HEX STRING
     * (7) OPACITY -- 0 TO 100
     * (8) TEXT ANGLE -- 0 TO 360
     * (9) TEXT ALIGNMENT CODE -- POSSIBLE VALUES ARE 11, 12, 13, 21, 22, 23, 31, 32, 33
     */

    public function generateNonExpiryFbToken($url)
    {

//        //header with content_type api key
//        $headers = array(
//            'Content-Type:application/json',
//        );

        $chr = curl_init();
        curl_setopt($chr, CURLOPT_URL, $url);
        curl_setopt($chr, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($chr, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($chr);

        if (isset(json_decode($result)->access_token)) {
            curl_close($chr);
            $accessToken = json_decode($result)->access_token;

            return $accessToken;
        } else {
            return false;
        }
    }

    public function processImageUpload($currentPath, $uploadedFilePath, $imageName, $rid)
    {
        $tempFileName = $imageName;
        list(,, $tempType) = getimagesize($currentPath);

        if ($tempType === null) {
            return false;
        }

        switch ($tempType) {
            case IMAGETYPE_GIF:
                break;
            case IMAGETYPE_JPEG:
                break;
            case IMAGETYPE_PNG:
                break;
            default:
                return false;
        }

        $processedFilePath = $uploadedFilePath . 'watermark_' . $rid . '.jpg';
        //$image->move($uploadedFilePath, $tempFileName);
        $result = $this->createWatermarkFromString($uploadedFilePath . $tempFileName, $processedFilePath, "© " . date('Y') . " by incitereviews.com", 18, 'CCCCCC', 75, 1, 31);

        if ($result === false) {
            return false;
        } else {
            return true;
        }
    }
    
    public function plaidIntegration($publicKey, $accountId)
    {
        $headers[] = 'Content-Type: application/json';
        $params = array(
                        'client_id' => PLAID_CLIENT_ID,
                        'secret' => PLAID_SECRET_ID,
                        'public_token' => $publicKey,
        );

        $chl = curl_init();
        curl_setopt($chl, CURLOPT_URL, "https://development.plaid.com/item/public_token/exchange");
        curl_setopt($chl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($chl, CURLOPT_POST, 1);
        curl_setopt($chl, CURLOPT_POSTFIELDS, json_encode($params));
        curl_setopt($chl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($chl, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($chl, CURLOPT_TIMEOUT, 80);
        curl_setopt($chl, CURLOPT_SSL_VERIFYPEER, false);

        if (!$result = curl_exec($chl)) {
            trigger_error(curl_error($chl));
            return false;
        }
        curl_close($chl);
        $jsonParsed = json_decode($result);

        $btok_params = array(
        'client_id' => PLAID_CLIENT_ID,
        'secret' => PLAID_SECRET_ID,
        'access_token' => $jsonParsed->access_token,
        'account_id' => $accountId
        );

        $chl = curl_init();
        curl_setopt($chl, CURLOPT_URL, "https://development.plaid.com/processor/stripe/bank_account_token/create");
        curl_setopt($chl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($chl, CURLOPT_POST, 1);
        curl_setopt($chl, CURLOPT_POSTFIELDS, json_encode($btok_params));
        curl_setopt($chl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($chl, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($chl, CURLOPT_TIMEOUT, 80);
        curl_setopt($chl, CURLOPT_SSL_VERIFYPEER, false);

        if (!$result = curl_exec($chl)) {
            trigger_error(curl_error($chl));
            return false;
        }
        curl_close($chl);
        return $result;
    }
    
    public function callCurl($callURL, $params)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $callURL);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
        $curlOutput   = curl_exec($curl);
        $httpCode     = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        
        $outputArray = array('output' => $curlOutput, 'code' => $httpCode);
        return $outputArray;
    }
    public function convertDateByFormat($date, $format = "m-d-Y H:i:s")
    {
        $newDate = date($format, strtotime($date));
        return $newDate ;
    }

    public function getFilesFromFtpToLocal($info)
    {
        $conn = ssh2_connect($info['host'], $info['port']);
        if (!ssh2_auth_password($conn, $info['username'], $info['password'])) {
            return response()->json(['status' => 'fail', 'message' => FTP_CONN_FAIL]);
        }

        $remote_dir = $info['filepath'];
        $localpath = DOMAIN_URL . '/uploads/cyclecsv/' . $info['business_id'] . '/' . $info['filename'];
        // $localpath = '/home/ripal_darji/htdocs/marketing-app/uploads/cyclecsv/' . $info['business_id'] . '/' . $info['filename'];
        $filename = $info['filename'];

        if (ssh2_scp_recv($conn, $remote_dir . '/' . $filename, $localpath . '/' . $filename)) {
            if (!file_exists(DOMAIN_URL.'/uploads/cyclecsv/'.$info['business_id'])) {
                mkdir(DOMAIN_URL.'/uploads/cyclecsv/'.$info['business_id'], 0777, true);
            }
        }
    }

    public function getOrganizationIdByUserId($userId)
    {
        return Organization::where('user_id', $userId)->select('id')->first();
    }
}
