<?php

namespace Salesloo;

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

use Salesloo\Models\Product;
use Salesloo\AdminTable\Products as Products_Table;

/**
 * Manage Products
 */
class Products
{
    /**
     * Instance.
     *
     * Holds the products 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 salesloo product menu
     */
    public function menu()
    {
        add_menu_page(
            __('Product', 'salesloo'),
            __('Product', 'salesloo'),
            'manage_options',
            'salesloo-product',
            [$this, 'products_page'],
            'dashicons-screenoptions',
            4
        );

        add_submenu_page(
            'salesloo-product',
            'New Product',
            'New Product',
            'manage_options',
            'salesloo-product-new',
            [$this, 'product_edit_page']
        );
    }

    /**
     * product list page
     */
    public function products_page()
    {
        if (isset($_GET['product_id'])) {
            $this->product_edit_page();
        } else {

            $list_table = new Products_Table();
            $list_table->prepare_items();

            include SALESLOO_PATH . 'assets/partials/products-list.php';
        }
    }

    /**
     * new product
     */
    public function product_edit_page()
    {

        $notice = '';
        $class = '';
        $message = '';

        if (isset($_COOKIE['salesloo_product_saved'])) {

            $class = 'notice notice-info inline is-dismissible';
            $message = sanitize_text_field($_COOKIE['salesloo_product_saved']);
        } else if (isset($_COOKIE['salesloo_product_failed'])) {

            $class = 'notice notice-error inline is-dismissible';
            $message = sanitize_text_field($_COOKIE['salesloo_product_failed']);
        }

        if ($message) {
            $notice = sprintf('<div class="%1$s"><p>%2$s</p></div>', esc_attr($class), esc_html($message));
        }

        $productID = isset($_GET['product_id']) ? intval($_GET['product_id']) : 0;

        $product = Product::query('WHERE ID = %d', $productID)->first();

        $tabs = $this->data_edit_tabs();

        include SALESLOO_PATH . 'assets/partials/product.php';
    }

    /**
     * data edit tabs
     */
    public function data_edit_tabs()
    {
        $tabs = [
            [
                'name'       => 'General',
                'content_id' => 'tab-content-general',
                'position'   => 0
            ],
            [
                'name'       => 'Affiliate',
                'content_id' => 'tab-content-affiliate',
                'position'   => 20
            ],
            [
                'name'       => 'License',
                'content_id' => 'tab-content-license',
                'position'   => 40
            ],
            [
                'name'       => 'Autoresponder',
                'content_id' => 'tab-content-autoresponder',
                'position'   => 60
            ]
        ];

        $tabs = apply_filters('salesloo/admin/product/edit/tabs', $tabs);
        $shorted_tabs = [];

        foreach ((array) $tabs as $tab) {

            if (!isset($tab['name']) || !isset($tab['content_id'])) continue;


            $position = isset($tab['position']) ? intval($tab['position']) : 98;

            if (isset($shorted_tabs["$position"])) {
                $position = $position + substr(base_convert(md5($tab['name'] . $tab['content_id']), 16, 10), -5) * 0.00001;
            }
            $shorted_tabs["$position"] = $tab;
        }


        /**
         * short array by position
         */
        ksort($shorted_tabs, SORT_NUMERIC);

        return $shorted_tabs;
    }


    /**
     * ajax get all items
     */
    public function ajax_get_all_items()
    {
        $nonce = isset($_REQUEST['nonce']) ? $_REQUEST['nonce'] : '';
        if (!wp_verify_nonce($nonce, 'salesloo-ajax')) exit;

        $paged = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $search = isset($_GET['search']) ? sanitize_text_field($_GET['search']) : '';

        $args = [
            'post_type'      => apply_filters('salesloo/items/post_type', ['post', 'page', 'salesloo-file']),
            'post_status'    => 'publish',
            'posts_per_page' => 10,
            'paged'          => $paged,
            //'fields' => 'ids',
            'order'   => 'ASC',
            'orderby' => 'ID'
        ];

        if ($search) {
            $args['s'] = $search;
        }

        $query = new \WP_Query($args);
        $items = [];

        foreach ((array)$query->posts as $post) {

            if ($post->post_type == 'salesloo-file') {
                $post_type = 'File';
            } else {
                $post_type = ucfirst($post->post_type);
                $post_type = str_replace('-', ' ', $post_type);
                $post_type = str_replace('_', ' ', $post_type);
            }

            $items[] = [
                'id' => $post->ID,
                'text' => $post_type . ' - ' . $post->post_title,
            ];
        }

        $result = [
            'results' => $items,
            'pagination' => [
                'more' => $query->max_num_pages > $paged ? true : false
            ],
        ];

        echo json_encode($result);
        exit;
    }

    /**
     * query current product
     */
    public function handle_action()
    {
        global $salesloo_product;

        $product_id = 0;

        if (!isset($_GET['page'])) return;

        $pages = [
            'salesloo-product',
            'salesloo-product-new'
        ];

        if (in_array($_GET['page'], $pages)) {

            if (isset($_POST['_wpnonce'])) {
                if (check_admin_referer('salesloo-product', '_wpnonce') && wp_verify_nonce($_POST['_wpnonce'], 'salesloo-product')) :
                    $post = $_POST;

                    /**
                     * remove unwanted data
                     */
                    unset($post['_wpnonce']);
                    unset($post['_wp_http_referer']);

                    /**
                     * save product data
                     */
                    if (isset($post['ID']) && intval($post['ID']) > 0) {

                        if (isset($post['autoresponder_service_provider']) && $post['autoresponder_service_provider'] == 'custom') {
                            if (isset($post['autoresponder_on_place_order_custom']) && $post['autoresponder_on_place_order_custom']) {
                                $form = \Salesloo\Libraries\Form_Parser::process(str_replace('\"', '', $post['autoresponder_on_place_order_custom']));
                                $post['autoresponder_on_place_order_custom'] = $form;
                            }

                            if (isset($post['autoresponder_on_invoice_completed_custom']) && $post['autoresponder_on_invoice_completed_custom']) {
                                $form = \Salesloo\Libraries\Form_Parser::process(str_replace('\"', '', $post['autoresponder_on_invoice_completed_custom']));
                                $post['autoresponder_on_invoice_completed_custom'] = $form;
                            }
                        }

                        $product_id = salesloo_update_product($post);
                        do_action('salesloo/product/update');
                    } else {
                        $product_id = salesloo_insert_product($post);
                        do_action('salesloo/product/create');
                    }

                    salesloo_set_product_protected_page($product_id, $post['items']);

                    /**
                     * show error notice if failed saved product otherwise redirect to product page
                     */
                    if (is_wp_error($product_id)) {
                        $message = $product_id->get_error_message();
                        setcookie('salesloo_product_failed', $message, time() + 60);

                        if (isset($post['ID']) && intval($post['ID']) > 0) {
                            $page = 'salesloo-product&product_id=' . intval($post['ID']);
                        } else {
                            $page = 'salesloo-product-new';
                        }
                    } else {
                        $message = 'Product Saved';
                        setcookie('salesloo_product_saved', $message, time() + 60);
                        $page = 'salesloo-product&product_id=' . $product_id;

                        do_action('salesloo/product/saved');
                    }

                    $redirect = admin_url('admin.php?page=' . $page);
                    wp_redirect($redirect);
                endif;
            }
        }
    }

    /**
     * deactivate scheduled active product
     */
    public function product_active_status_processing()
    {
        $active_products = Product::select(
            ['salesloo_product.ID'],
            ['salesloo_product.status'],
            ['salesloo_productmeta.meta_key'],
            ['salesloo_productmeta.meta_value']
        )->join(
            'left',
            'salesloo_productmeta',
            ['ID', 'product_id', '=']
        )->query(
            'WHERE status = "active" AND meta_key = "scheduled_end" AND meta_value IS NOT NULL AND meta_value <= "' . date('Y-m-d H:i:s') . '"'
        )->get();

        if ($active_products->found() > 0) {
            foreach ($active_products as $product) {
                \salesloo_update_product_status($product->ID, 'inactive');
            }
        }
    }

    /**
     * activate scheduled inactive product
     */
    public function product_inactive_status_processing()
    {

        $inactive_products = Product::select(
            ['salesloo_product.ID'],
            ['salesloo_product.status'],
            ['salesloo_productmeta.meta_key'],
            ['salesloo_productmeta.meta_value']
        )->join(
            'left',
            'salesloo_productmeta',
            ['ID', 'product_id', '=']
        )->query(
            'WHERE status = "inactive" AND meta_key = "scheduled_end" AND meta_value IS NOT NULL AND meta_value >= "' . date('Y-m-d H:i:s') . '"'
        )->get();

        if ($inactive_products->found() > 0) {
            foreach ($inactive_products as $product) {
                $must_active = false;
                $scheduled_start_datetime = salesloo_get_product_meta($product->ID, 'scheduled_start', true);
                if (empty($scheduled_start_datetime)) {
                    $must_active = true;
                } else {
                    $scheduled_start = strtotime($scheduled_start_datetime);
                    if ($scheduled_start <= strtotime('now')) {
                        $must_active = true;
                    }
                }

                if (true === $must_active) {
                    \salesloo_update_product_status($product->ID, 'active');
                }
            }
        }
    }


    /**
     * Product constructor
     */
    public function __construct()
    {
        add_action('admin_menu', [$this, 'menu']);
        add_action('wp_ajax_get_all_items', [$this, 'ajax_get_all_items']);

        add_action('admin_init', [$this, 'handle_action']);

        add_action('salesloo/cron/hourly', [$this, 'product_active_status_processing']);
        add_action('salesloo/cron/hourly', [$this, 'product_inactive_status_processing']);
    }
}
