<?php

namespace Salesloo;

if (!defined('ABSPATH')) {
    exit;
}

use \Salesloo\Models\Access;

/**
 * Salesloo webhook.
 *
 * @since 1.0.0
 */
class Webhooks
{

    /**
     * Instance.
     *
     * Holds the webhooks instance.
     *
     * @since 1.0.0
     * @access public
     */
    public static $instance = null;

    /**
     * Init
     *
     * @since 1.0.0
     */
    public static function init()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * register post type
     */
    public function register_post_type()
    {
        register_post_type(
            'salesloo-webhook',
            array(
                'labels' => array(
                    'name'               => __('Webhook', 'salesloo'),
                    'singular_name'      => __('Webhook', 'salesloo'),
                    'add_new'            => __('Add New', 'salesloo'),
                    'add_new_item'       => __('Add New Webhook', 'salesloo'),
                    'edit'               => __('Edit', 'salesloo'),
                    'edit_item'          => __('Edit Webhook', 'salesloo'),
                    'new_item'           => __('New Webhook', 'salesloo'),
                    'view'               => __('View Webhook', 'salesloo'),
                    'view_item'          => __('View Webhook', 'salesloo'),
                    'search_items'       => __('Search Webhook', 'salesloo'),
                    'not_found'          => __('No Webhooks found', 'salesloo'),
                    'not_found_in_trash' => __('No Webhooks found in Trash', 'salesloo')
                ),
                'public' => true,
                'hierarchical' => false,
                'has_archive' => false,
                'menu_position' => 5,
                'supports' => array(
                    'title',
                    'editor',
                ),
                'can_export' => true,
                'menu_icon' => 'dashicons-editor-code',
                'rewrite' =>  array(
                    'slug' => 'webhook',
                    //'width_front' => false
                ),
            )
        );
    }

    /**
     * register metaboxes
     */
    public function metaboxes()
    {
        add_meta_box(
            'metabox_access',
            'Access Link',
            [$this, 'metabox_access'],
            'salesloo-webhook',
            'side',
            'default'
        );

        add_meta_box(
            'metabox_url',
            'Webhook URL',
            [$this, 'metabox_url'],
            'salesloo-webhook',
            'normal',
            'default'
        );
    }

    function metabox_access()
    {
        global $post;

        \salesloo_field_text([
            'label'       => __('Link', 'salesloo'),
            'description' => '',
            'name'        => 'access_link',
            'after'       => 'Link access third party apps',
            'style'       => 'width:100%',
            'value'       => get_post_meta($post->ID, 'access_link', true),
            'placeholder' => 'http://',
            'direction' => 'column',
        ]);
    }

    /**
     * webhook url metabox
     *
     * @return void
     */
    public function metabox_url()
    {
        global $post;

        wp_nonce_field('salesloo-webhook', '__nonce');

        $shortcodes = [
            'customer_id'         => __('Customer ID', 'salesloo'),
            'customer_first_name' => __('Customer First Name', 'salesloo'),
            'customer_last_name'  => __('Customer Last Name', 'salesloo'),
            'customer_email'      => __('Customer Email', 'salesloo'),
            'product_id'          => __('Product ID', 'salesloo'),
            'product_name'        => __('Product Name / Title', 'salesloo'),
            'product_slug'        => __('Product Slug', 'salesloo'),
            'product_duration'    => __('Product Duration', 'salelsoo'),
            'purchase_code'       => __('Purchase Code', 'salesloo'),
            'order_id'            => __('Order ID', 'salesloo'),
            'order_license_limit' => __('Order license Limit', 'salesloo'),
            'order_expired_at'    => __('Order expired date', 'salesloo')
        ];

        $var = '<table class="wp-list-table widefat fixed striped table-view-list posts" cellspacing="0" style="border:none">';
        foreach ($shortcodes as $key => $val) {
            $var .= '<tr><td>[' . $key . ']</td><td>=></td><td> ' . $val . '</td></tr>';
        }
        $var .= '</table>';

        \salesloo_field_heading([
            'label' => __('Variable Shortcode', 'salesloo'),
            'description' => $var,
        ]);

        \salesloo_field_text([
            'label'       => __('Place Order Webhook', 'salesloo'),
            'description' => '',
            'name'        => 'place_order_webhook',
            'after'       => __('This webhook fire on place order event', 'salesloo'),
            'style'       => 'width:100%',
            'value'       => get_post_meta($post->ID, 'place_order_webhook', true),
            'placeholder' => 'ex: https://webhookurl.com/place-order?user_email=[customer_email]&product_id=[product_id]'
        ]);

        \salesloo_field_text([
            'label'       => __('Completed Payment Webhook', 'salesloo'),
            'description' => '',
            'name'        => 'completed_webhook',
            'after'       => __('This webhook fire on completed payment event', 'salesloo'),
            'style'       => 'width:100%',
            'value'       => get_post_meta($post->ID, 'completed_webhook', true),
            'placeholder' => 'ex: https://webhookurl.com/completed-payment?user_email=[customer_email]&product_id=[product_id]'
        ]);

        \salesloo_field_text([
            'label'       => __('Refunded Payment Webhook', 'salesloo'),
            'description' => '',
            'name'        => 'refunded_webhook',
            'after'       => __('This webhook fire on refunded payment event', 'salesloo'),
            'style'       => 'width:100%',
            'value'       => get_post_meta($post->ID, 'refunded_webhook', true),
            'placeholder' => 'ex: https://webhookurl.com/refunded-payment?user_email=[customer_email]&product_id=[product_id]'
        ]);

        \salesloo_field_text([
            'label'       => __('Cancelled Payment Webhook', 'salesloo'),
            'description' => '',
            'name'        => 'cancelled_webhook',
            'after'       => __('This webhook fire on cancelled payment event', 'salesloo'),
            'style'       => 'width:100%',
            'value'       => get_post_meta($post->ID, 'cancelled_webhook', true),
            'placeholder' => 'ex: https://webhookurl.com/cancelled-payment?user_email=[customer_email]&product_id=[product_id]'
        ]);
    }

    /**
     * Save metabox
     * 
     * handle metabox save
     */
    public function metabox_save($post_id, $post)
    {

        if (!current_user_can('edit_post', $post_id)) {
            return $post_id;
        }

        if (!isset($_POST['__nonce'])) return $post_id;

        if (!wp_verify_nonce($_POST['__nonce'], 'salesloo-webhook')) {
            return $post_id;
        }

        $webhooks = isset($_POST['webhook']) ? $_POST['webhook'] : [];

        if ($webhooks) {
            $new_webhooks = [];
            foreach ((array)$webhooks['webhookname'] as $key => $val) {
                $new_webhooks[$key] = [
                    'name' => $val,
                    'webhook' => $webhooks['webhookurl'][$key]
                ];
            }

            update_post_meta($post_id, 'downloadable-webhook', $new_webhooks);
        }

        if (isset($_POST['enable_webhook'])) {
            $id = sanitize_text_field($_POST['enable_webhook']);
            update_post_meta($post_id, 'enable_webhook', $id);
        }

        if (isset($_POST['webhook_id'])) {
            $webhook_id = sanitize_text_field($_POST['webhook_id']);
            update_post_meta($post_id, 'webhook_id', $webhook_id);
        }
    }


    public function load()
    {

        if (!is_singular('salesloo-webhook')) return;

        $access_link = get_post_meta(get_the_ID(), 'access_link', true);

        wp_redirect($access_link);
        exit;
    }

    public function action($invoice, $order, $item, $product)
    {
        if ('salesloo-webhook' == $item->post_type) {
            $customer = get_userdata($order->user_id);

            $replacers = [
                'customer_id'         => $order->user_id,
                'customer_first_name' => $customer->first_name,
                'customer_last_name'  => $customer->last_name,
                'customer_email'      => $customer->user_email,
                'product_id'          => $product->ID,
                'product_name'        => $product->title,
                'product_slug'        => $product->slug,
                'product_duration'    => $product->duration,
                'purchase_code'       => $order->code,
                'order_id'            => $order->ID,
                'order_license_limit' => $order->license_limit,
                'order_expired_at'    => $order->expired_at
            ];


            $completed_webhook = get_post_meta($item->ID, 'completed_webhook', true);
            if ($completed_webhook && $invoice->status == 'completed') {
                $url = salesloo_webhook_replace_shortcode($completed_webhook, $replacers);
                wp_remote_get($url);
            }

            $refunded_webhook = get_post_meta($item->ID, 'refunded_webhook', true);
            if ($refunded_webhook && $invoice->status == 'refunded') {
                $url = salesloo_webhook_replace_shortcode($refunded_webhook, $replacers);
                wp_remote_get($url);
            }

            $cancelled_webhook = get_post_meta($item->ID, 'cancelled_webhook', true);
            if ($cancelled_webhook && $invoice->status == 'cancelled') {
                $url = salesloo_webhook_replace_shortcode($cancelled_webhook, $replacers);
                wp_remote_get($url);
            }
        }
    }


    /**
     * constructor.
     */
    public function __construct()
    {
        add_action('wp', [$this, 'load']);
        add_action('init', [$this, 'register_post_type']);
        add_action('add_meta_boxes', [$this, 'metaboxes']);
        add_action('save_post', [$this, 'metabox_save'], 1, 2);

        add_action('salesloo/invoice/order/item', [$this, 'action'], 10, 4);
    }
}
