<?php

namespace Salesloo\Frontend;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

use \Salesloo\Abstracts\Frontend;
use \Salesloo\Libraries\User_Info;

/**
 * Salesloo Aff
 */
class Aff extends Frontend
{

    /**
     * construction
     */
    public function __construct()
    {
        $this->id = 'aff';
        $this->template = '';
        $this->target = 'both';
        $this->title = '';
    }

    public function load()
    {
        global $wp;
        $vars = salesloo_vars();

        $redirect  = esc_url(salesloo_get_option('affiliate_general_redirect'));
        $product   = salesloo_get_product_by('slug', salesloo_get_current_product_slug());
        $affiliate = false;

        $custom_links = [];
        if (isset($vars['__username'])) {
            $username = sanitize_text_field($vars['__username']);
            $affiliate = get_user_by('login', $username);

            if ($affiliate) {
                salesloo_set_affiliate_cookie($affiliate->user_login);

                $meta_key     = 'custom_url_' . $affiliate->ID;
                $custom_links = (array) salesloo_get_product_meta($product->ID, $meta_key, true);
            }
        }

        if (isset($_GET['coupon'])) {
            $coupon_code = sanitize_text_field($_GET['coupon']);
            salesloo_set_current_coupon_cookie($coupon_code);
        } else {
            /**
             * if not use coupon and coupon cookie exists then delete cookie coupon
             */
            if (isset($_COOKIE['SALESLOO_CHECKOUT_COUPON'])) {
                salesloo_delete_current_coupon_cookie();
            }
        }

        if ($product) {
            $redirect = salesloo_url_checkout($product->slug);

            if (isset($_GET['re'])) {
                $slug = sanitize_text_field($_GET['re']);
                $salespage_url = salesloo_get_product_meta($product->ID, 'salespage_url', true);

                if ($slug == 'salespage' && $salespage_url) {
                    $redirect = esc_url($salespage_url);
                } else {
                    if (isset($custom_links[$slug])) {
                        $redirect = esc_url($custom_links[$slug]['target']);
                    }
                }
            }
        }

        $click = [
            'product_id' => $product ? $product->ID : 'NULL',
            'uri'        => isset($_SERVER['REQUEST_URI']) ? sanitize_text_field($_SERVER['REQUEST_URI']) : '',
            'referer'    => esc_url_raw(wp_get_raw_referer()),
            'device'     => User_Info::get_device(),
            'ip'         => User_Info::get_ip(),
            'browser'    => User_Info::get_browser(),
            'platform'   => User_Info::get_platform()
        ];

        if ($affiliate) {
            $click['affiliate_id'] = $affiliate->ID;
        }

        salesloo_insert_affiliate_click($click);

        wp_redirect($redirect);
        exit;
    }
}
