<?php

namespace App;
use LaravelQRCode\Facades\QRCode as LQRCode;
use QR_Code\QR_Code;
use Shivella\Bitly\Facade\Bitly;


class QRCode{

    public function __construct($merchant){

    }

    public static function getQRCode($id){
        $merchant = Merchant::find($id);
        LQRCode::url(static::getReferralLink($merchant))->setSize(5)->svg();
    }

    private static function getReferralLink($merchant){
        $code = isset($merchant->code) ? strtoupper($merchant->code) : '';
        $referral_link_base = "https://play.google.com/store/apps/details?id=com.consumer.creditfair&referrer=";
        $utm_medium = urlencode("partner");
        $referee = urlencode($code);
        $utm_campaign = urlencode(str_replace(' ','_',$merchant->merchant_name));
        $referral_link = 'utm_source='.$referee.'&utm_medium='.$utm_medium.'&utm_campaign='.$utm_campaign;
        $referral_link = urlencode($referral_link);
        $referral_link = urlencode($referral_link_base.$referral_link);
        try {
            return Bitly::getUrl($referral_link);
        }catch (\Exception $e){
            return urldecode($referral_link);
        }
    }

    public static function getQRCodeFile($id){
        $merchant = Merchant::find($id);
        $file_path = '/qr/merchant_'.$id.'.png';
        $path = public_path().$file_path;
        QR_Code::png(static::getReferralLink($merchant), $path , 0, 19);
        return $file_path;
    }
}
