<?php

namespace Salesloo\Frontend;

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

use \Salesloo\Abstracts\Frontend;
use \Salesloo\Models\Coupon;
use \Salesloo\Models\Coupon_Code;

/**
 * Salesloo Affiliate Product
 */
class Affiliate_Product_Id extends Frontend
{
    public $product_id = 0;

    private $product = null;

    /**
     * construction
     */
    public function __construct()
    {
        $this->id       = 'affiliate/product/id';
        $this->template = 'affiliate-product-id.php';
        $this->target   = 'user';
        $this->title    = __('Affiliate Product', 'salesloo');

        $product_slug = salesloo_get_current_product_slug();
        $this->product = salesloo_get_product_by('slug', $product_slug);

        if (false == $this->product) {
            wp_die('No Product found');
        }

        $this->product_id = $this->product->ID;
    }

    public function process_action($req)
    {
        global $___salesloo;

        $input = file_get_contents("php://input");
        $request = json_decode($input, true);

        $meta_key     = 'custom_url_' . get_current_user_id();

        if (isset($_POST['add_custom_link']) && salesloo_verify_nonce($_POST['add_custom_link'])) {
            $title  = sanitize_text_field($_POST['title']);
            $title = filter_var($title, \FILTER_SANITIZE_ADD_SLASHES);
            $slug   = sanitize_title($_POST['slug']);
            $target = $_POST['target'];

            if (wp_http_validate_url($target)) {
                $custom_links = (array) salesloo_get_product_meta($this->product_id, $meta_key, true);

                $custom_links[$slug] = [
                    'title'  => $title,
                    'target' => esc_url_raw($target)
                ];
                salesloo_update_product_meta($this->product_id, $meta_key, $custom_links);
                $___salesloo['alert'] = [
                    'type'    => 'success',
                    'message' => __('New custom link affiliate added', 'salesloo')
                ];

                $redirect = salesloo_url_affiliate('product/' . $this->product->slug);
                wp_redirect($redirect);
            } else {
                $___salesloo['alert'] = [
                    'type' => 'warning',
                    'message' => __('Please insert a valid url', 'salesloo')
                ];
            }
        }


        if (isset($request['nonce']) && salesloo_verify_nonce($request['nonce'])) {
            if (isset($request['action']) && $request['action'] == 'delete_custom_link') {
                $custom_links = (array) salesloo_get_product_meta($this->product_id, $meta_key, true);
                $slug = sanitize_text_field($request['slug']);
                if (isset($custom_links[$slug])) {
                    unset($custom_links[$slug]);
                }
                salesloo_update_product_meta($this->product_id, $meta_key, $custom_links);
                $custom_links = (array) salesloo_get_product_meta($this->product_id, $meta_key, true);

                $links = [
                    [
                        'title'  => __('Form Order', 'salesloo'),
                        'link'   => esc_url(salesloo_affiliate_link($this->product)),
                        'delete' => false
                    ],
                    [
                        'title'  => __('Salespage', 'salesloo'),
                        'link'   => esc_url(salesloo_affiliate_link($this->product, 'salespage')),
                        'delete' => false
                    ]
                ];

                foreach ($custom_links as $key => $val) {
                    $links[] = [
                        'title'  => $val['title'],
                        'link'   => esc_url(salesloo_affiliate_link($this->product, $key)),
                        'delete' => [
                            'message' => sprintf(__('You want to delete %s link', 'salesloo'), $val['title']),
                            'options' => [
                                'url' => $_SERVER['REQUEST_URI'],
                                'method' => 'post',
                                'data' => [
                                    'slug' => $key,
                                    'nonce' => salesloo_create_nonce(),
                                    'action' => 'delete_custom_link'
                                ],
                            ]
                        ]
                    ];
                }
                $response = [
                    'message' => __('Custom link was deleted', 'salesloo'),
                    'data' => $links
                ];

                echo json_encode($response);
                exit;
            }
        }

        if (isset($request['nonce']) && salesloo_verify_nonce($request['nonce'])) {
            if (isset($request['action']) && $request['action'] == 'edit_coupon_code') {
                $response = new \Salesloo\Response();

                $code      = sanitize_text_field($request['value']);
                $coupon_id = intval($request['id']);
                $user_id   = intval(get_current_user_id());
                $product_id = $this->product_id;

                $check_code = Coupon_Code::query("WHERE code = '$code' AND user_id != $user_id")->first();

                if ($check_code->code_id > 0) {
                    $data = [
                        'message' => sprintf(__('Code %s is already taken, please choose another code', 'salesloo'), $code),
                    ];

                    $response->set_data($data);
                    $response->set_status(400);
                } else {

                    $query = "WHERE products LIKE '%\"$product_id\"%' AND code = '$code' AND user_id = $user_id";

                    $coupon = Coupon::rightJoin('salesloo_coupon_code', ['salesloo_coupon.ID', 'salesloo_coupon_code.coupon_id', '='])
                        ->select(
                            'salesloo_coupon.*',
                            'salesloo_coupon_code.user_id',
                            'salesloo_coupon_code.code'
                        )
                        ->query($query)->first();

                    if ($coupon->ID > 0) {
                        $data = [
                            'message' => __('Code can\'t be same, please choose another code', 'salesloo'),
                        ];

                        $response->set_data($data);
                        $response->set_status(400);
                    } else {
                        $get_code = Coupon_Code::query("WHERE code = '$code' AND coupon_id = $coupon_id AND user_id = $user_id")->first();
                        $code_id = $get_code->code_id;

                        $updated = salesloo_update_coupon_code($code_id, $coupon_id, $code, $user_id);

                        if (is_wp_error($updated)) {
                            $data = [
                                'message' => $updated->get_error_message(),
                            ];

                            $response->set_data($data);
                            $response->set_status(400);
                        } else {
                            $data = [
                                'message' => __('Coupon code has updated', 'salesloo'),
                            ];

                            $response->set_data($data);
                            $response->set_status(200);
                        }
                    }
                }

                $response->json();
                exit;
            }
        }

        if (isset($request['nonce']) && salesloo_verify_nonce($request['nonce'])) {
            if (isset($request['action']) && $request['action'] == 'update_fbpixel') {
                $response = new \Salesloo\Response();

                $pixel = sanitize_text_field($request['value']);

                $meta_key     = 'fbpixel_' . get_current_user_id();
                salesloo_update_product_meta($this->product_id, $meta_key, $pixel);

                $data = [
                    'message' => __('Facebook pixel ids has updated', 'salesloo'),
                    'data' => [
                        'value' => salesloo_get_product_meta($this->product_id, $meta_key, true),
                        'nonce' => salesloo_create_nonce(),
                        'action' => 'update_fbpixel'
                    ]
                ];

                $response->set_data($data);
                $response->set_status(200);

                $response->json();
                exit;
            }
        }

        if (isset($request['nonce']) && salesloo_verify_nonce($request['nonce'])) {
            if (isset($request['action']) && $request['action'] == 'update_tiktokpixel') {
                $response = new \Salesloo\Response();

                $pixel = sanitize_text_field($request['value']);

                $meta_key     = 'tiktokpixel_' . get_current_user_id();
                salesloo_update_product_meta($this->product_id, $meta_key, $pixel);

                $data = [
                    'message' => __('Tiktok pixel ids has updated', 'salesloo'),
                    'data' => [
                        'value' => salesloo_get_product_meta($this->product_id, $meta_key, true),
                        'nonce' => salesloo_create_nonce(),
                        'action' => 'update_tiktokpixel'
                    ]
                ];

                $response->set_data($data);
                $response->set_status(200);

                $response->json();
                exit;
            }
        }
    }

    public function load()
    {
        global $___salesloo;

        $___salesloo['product'] = $this->product;

        $current_user_id = get_current_user_id();
        $product_id = $this->product_id;

        $query = "WHERE status = 'active' AND products LIKE '%\"$product_id\"%' AND user_id IS NULL AND is_private != 1";
        $query .= " OR status = 'active' AND products IS NULL AND user_id IS NULL AND is_private != 1";

        $query_coupons = Coupon::rightJoin('salesloo_coupon_code', ['salesloo_coupon.ID', 'salesloo_coupon_code.coupon_id', '='])
            ->select(
                'salesloo_coupon.*',
                'salesloo_coupon_code.user_id',
                'salesloo_coupon_code.code'
            )
            ->query($query)->get();

        $ccustom_links = [
            [
                'title'  => __('Form Order', 'salesloo'),
                'link'   => esc_url(salesloo_affiliate_link(___salesloo('product'))),
                'delete' => false
            ],
            [
                'title'  => __('Salespage', 'salesloo'),
                'link'   => esc_url(salesloo_affiliate_link(___salesloo('product'), 'salespage')),
                'delete' => false
            ]
        ];

        foreach ((array) salesloo_get_product_meta($this->product_id, 'custom_url_' . $current_user_id, true) as $key => $val) {
            $ccustom_links[] = [
                'title'  => $val['title'],
                'link'   => esc_url(salesloo_affiliate_link($this->product, $key)),
                'delete' => [
                    'message' => sprintf(__('You want to delete %s link', 'salesloo'), $val['title']),
                    'data' => [
                        'slug' => $key,
                        'nonce' => salesloo_create_nonce(),
                        'action' => 'delete_custom_link'
                    ],
                ]
            ];
        }

        $coupons = [];
        foreach ($query_coupons as $coupon) {

            $expired = '~';
            $time_expired_date = strtotime($coupon->active_end);

            if (strtotime('now') < $time_expired_date) {
                $expired = date('Y-m-d H:i', $time_expired_date);
            }

            $user_code = salesloo_get_coupon_code($coupon->ID, get_current_user_id());

            if (empty($user_code)) {
                $user_code = '';
            }

            $coupons[] = [
                'rebate' => [
                    'label' => __('Rebate', 'salesloo'),
                    'value' => $coupon->rebate
                ],
                'expired' => [
                    'label' => __('Expired Date', 'salesloo'),
                    'value' => $expired
                ],
                'general' => [
                    'label' => __('General Code', 'salesloo'),
                    'code' => $coupon->code
                ],
                'user' => [
                    'label' => __('Your Code', 'salesloo'),
                    'message' => __('You want to save your code', 'salesloo'),
                    'code' => [
                        'id' => $coupon->ID,
                        'value' => $user_code,
                        'nonce' => salesloo_create_nonce(),
                        'action' => 'edit_coupon_code'
                    ],
                ]
            ];
        }

        $data = [
            'thumbnail_url' => $this->product->get_thumbnail_url(),
            'title'         => $this->product->title,
            'duration'      => [
                'label' => __('Duration', 'salesloo'),
                'value' => sanitize_text_field($this->product->duration),
                'print' => salesloo_translate_product_duration($this->product->duration),
            ],
            'price' => [
                'label' => __('Price', 'salesloo'),
                'value' => salesloo_convert_price($this->product->get_price()),
                'print' => salesloo_convert_money($this->product->get_price())
            ],
            'commission' => [
                'label' => __('Commission', 'salesloo'),
                'print' => salesloo_print_affiliate_commission($this->product->get_raw_affiliate_commission())
            ],
            'license' => [
                'label' => __('License limit', 'salesloo'),
                'value' => sanitize_text_field($this->product->meta('license_limit'))
            ],
            'form'        => [
                'label' => __('Form Order', 'salesloo'),
                'value' => esc_url(salesloo_url_checkout($this->product->slug))
            ],
            'salespage' => [
                'label' => __('See Salespage', 'salesloo'),
                'link'  => esc_url($this->product->meta('salespage_url'))
            ],
            'custom_links' => $ccustom_links,
            'coupons'      => $coupons,
            'fbpixel' => [
                'value' => salesloo_get_product_meta($this->product_id, 'fbpixel_' . get_current_user_id(), true),
                'nonce' => salesloo_create_nonce(),
                'action' => 'update_fbpixel'
            ],
            'tiktokpixel' => [
                'value' => salesloo_get_product_meta($this->product_id, 'tiktokpixel_' . get_current_user_id(), true),
                'nonce' => salesloo_create_nonce(),
                'action' => 'update_tiktokpixel'
            ]
        ];

        $___salesloo['data'] = $data;

        do_action('salesloo/affiliate/product/id/load', $this);
    }
}
