<?php

namespace Yajny\Member\Models;

use Illuminate\Support\Facades\Session;
use Yajny\Member\Traits\MemberScopes;
use Yajny\Models\BaseClick;
use Yajny\Models\Store;

class Click extends BaseClick
{
    // use Notifiable;
    use MemberScopes;

    /**
     * @var string
     */
    protected $table = 'clicks';
    /**
     * @var string
     */
    protected $primaryKey = 'id';
    /**
     * @var string
     */
    public $dateColumn = 'click_time';
    /**
     * @var string
     */
    public $directTable = 'clicks';

    /**
     * @var string[]
     */
    protected $guarded = ['id'];
    /**
     * @var bool
     */
    public $timestamps = false;

    // protected $hidden = [
    //     'password', 'remember_token',
    // ];

    /**
     * @return mixed
     */
    public function store()
    {
        return $this->belongsTo('Yajny\Models\Store', 'store_id', 'id')->withoutGlobalScopes();
    }

    /**
     * @param $q
     * @return mixed
     */
    public function scopeOrderByClick($q)
    {

        return  $q->orderBy($this->primaryKey, 'DESC');
    }

    /**
     * @param $q
     * @return mixed
     */
    public function scopeOrderByClickTime($q)
    {

        return  $q->orderBy($this->dateColumn, 'DESC');
    }

    /**
     * @param $object_type
     * @param $object_id
     * @param $store
     * @param $user_id
     * @param null $custom_link
     * @param null $platform
     * @return array|null
     */
    public static function outClick($object_type, $object_id, $store, $user_id, $custom_link=null, $platform = null)
    {
        $mediaBuyers=[398943,398991,399000,399004,399017,399024,399037,399039,399040,399071,399075,399095,399096,399104,399105,399106,399107,399108,399138,399183,399432,399433,400527,400528,400529,400530,402658,402713,402689];
        $object_type = $object_type == 'sectioned_banner' ? 'ad' : $object_type;
        // initilize the return object with store
        $retObject = $store;

        // share and earn module
        if ($object_type == 'share') {

            // find the link and return null if no link found
            $retObject = UserLink::where('code', $object_id)->first();
            if (!$retObject) return null;

            // find the store associated with the link and return null if no store found
            $store  = Store::withoutGlobalScopes()->find($retObject->store_id);
            if (!$store) return null;

            // set user_id to the link creators user id, so he/she earns cashback on sale
            $user_id = $retObject->user_id;
            // set url for redirect
            $redirectUrl = $retObject->offer_link;
            $appRedirectUrl = '';
        }
        else if ($object_type != 'store') {
            // get the object being monetized
            $retObject = self::getRedirectUrlByObject($object_type, $object_id);

            if ($retObject) {
                if (strlen($retObject->link) > 10)
                    $redirectUrl = $retObject->link;  // if object found, and has a link
                else
                    $redirectUrl = $store->homepage; // otherwise, set store homepagea as link, so that user is not sent to a broken link
                if (strlen($retObject->app_deep_link) > 1)
                    $appRedirectUrl = $retObject->app_deep_link;  // if object found, and has a link
                else
                    $appRedirectUrl = $store->app_homepage; // otherwise, set store homepagea as link, so that user is not sent to a broken link
            } else {
                $redirectUrl = $store->homepage; // otherwise, set store homepagea as link, so that user is not sent to a broken link
                $appRedirectUrl = $store->app_homepage; // otherwise, set store homepagea as link, so that user is not sent to a broken link
            }
        }
        else {
            $redirectUrl = $store->homepage; // default setting for store
            $appRedirectUrl = $store->app_homepage; // default setting for store
        }


		if($custom_link)
			$redirectUrl = $custom_link;
		

        if ($store && $redirectUrl) {

            // url builder for store , replace link dynamically
            $dl_url = $store->dl_url_build && $store->cb_status ? $store->dl_url_build : $redirectUrl;
            if ($dl_url != $redirectUrl && strpos($redirectUrl, '?')
                && strpos($dl_url, '?') && strpos($dl_url, '#URL'))
                $dl_url = str_replace('?', '&', $dl_url);
            $dl_url = str_replace(['#URL', '#EURL'], [$redirectUrl, urlencode($redirectUrl)], $dl_url);
            $dl_url=  self::str_replace_nth_skip('?', '&', $dl_url, 1);
            $app_dl_url = $store->dl_app_url_build && $store->cb_status ? $store->dl_app_url_build : $appRedirectUrl;
            $app_dl_url = str_replace(['#URL', '#EURL'], [$appRedirectUrl, urlencode($appRedirectUrl)], $app_dl_url);
            // new click isntacce
            $click = new self;
            $click->store_id = $store->id;
            $click->user_id = $user_id;

            // record current cashback status and %
            $click->cashback_enabled = $store->cb_status;
            $click->cashback_percent = $store->cashback_percent;

            if ($object_type == 'share') {
                $click->link_id = $retObject->id; // for share and earn
                if(Member::find($user_id)->type == 'affiliate')
                    $click->cashback_percent = 100;
            }

            $click->ip_address = request()->ip();
            $click->source_type = $object_type;
            $click->source_id = $object_id;

            $click->cb_deal_type = $store->cb_deal_type;
            $click->cb_deal_value = $store->cb_deal_value;

            $click->network_id = $store->network_id;
            $click->http_referrer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
            
            // record links for future debugging
            $click->redirect_link = $dl_url;
            $click->original_link = $redirectUrl;

            $click->platform = $platform;

            if (Session::has('utm')) {
                $click->utm = json_encode(Session::get('utm'));
            }
            if ($user_id==352817) $click->cashback_percent = 100;
            if (in_array($user_id,$mediaBuyers) ){
                $click->cashback_percent = 100;
            }
            // generate the link
            $click->save();

            //increment clicks count
            $store->increment('clicks');
            if ($object_type == 'coupon' && $retObject)
                $retObject->increment('clicks');
            if ($user_id) {
                $userClickCount = UserStoreClickCount::firstOrNew([
                    'user_id' => $user_id,
                    'store_id' => $store->id
                ]);
                $userClickCount->click_count = ($userClickCount->click_count ?? 0) + 1;
                $userClickCount->save();
            }

            // replace click id and return the url
            return [
                'url' => [
                    'web' => str_replace('CBCLKID', $click->id, $dl_url),
                    'app' => $appRedirectUrl ? str_replace('CBCLKID', $click->id, $app_dl_url) : null
                ],
                'click_id' => $click->id
            ];
        } else {
            return ['url'=> url(),'click_id' => 0 ];  // invalid store or no link found , send null
        }
    }

    /**
     * @param $srch
     * @param $replace
     * @param $subject
     * @param int $skip
     * @return string
     */
    static public function str_replace_nth_skip($srch, $replace, $subject, $skip=1){
        $subject = explode($srch, $subject.' ', $skip+1);
        if(isset($subject[$skip])){
            $subject[$skip] = str_replace($srch, $replace, $subject[$skip]);
            while (($tmp = array_pop($subject)) == '');
            $subject[]=$tmp;
        }
        return implode($srch, $subject);
    }
}
