<?php

namespace Salesloo\Admin;

use \Salesloo\Admin_Ajax;
use \Salesloo\Models\Product;
use Salesloo\Models\Coupon as Model_Coupon;
use Salesloo\AdminTable\Coupons as Coupons_Table;

/**
 * Admin coupon Page classes
 */
class Coupon
{
    private $admin_ajax;

    /**
     * __construct
     *
     * @return void
     */
    public function __construct()
    {

        $this->admin_ajax = new Admin_Ajax;
    }

    /**
     * return dashboard template
     *
     * @return void
     */
    public function template()
    {
        salesloo_hidding_wp_admin_notices();

        if (isset($_GET['action'])) {

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

            $couponID = isset($_GET['coupon_id']) ? intval($_GET['coupon_id']) : 0;

            if (isset($_COOKIE['salesloo_coupon_saved_' . $couponID])) {
                $class = 'notice notice-info inline is-dismissible';
                $message = sanitize_text_field($_COOKIE['salesloo_coupon_saved_' . $couponID]);
            } else if (isset($_COOKIE['salesloo_coupon_failed'])) {
                $class = 'notice notice-error inline is-dismissible';
                $message = sanitize_text_field($_COOKIE['salesloo_coupon_failed']);
            }

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

            $coupon = Model_Coupon::query('WHERE ID = %d', $couponID)->first();

            include SALESLOO_PATH . 'assets/partials/coupon.php';
        } else {

            $list_table = new Coupons_Table();
            $list_table->prepare_items();
            include SALESLOO_PATH . 'assets/partials/coupons-list.php';
        }
    }

    /**
     * ajax get all coupons
     */
    public function ajax_get_all_products()
    {
        $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']) ? intval($_GET['search']) : '';

        $product_query = Product::paginate(20, $paged)->order('ID', 'DESC');
        $sql = '';

        if ($search) {
            $sql .= sprintf('title LIKE %s OR description LIKE %s', "'%$search%'", "'%$search%'");
        }

        if ($sql) {
            $product_query->query("WHERE $sql");
        }

        $products = $product_query->get();

        $items = [];

        if ($products->found() > 0) {
            foreach ($products as $product) {

                $items[] = [
                    'id' => $product->ID,
                    'text' => $product->title,
                ];
            }
        }

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

        echo json_encode($result);
        exit;
    }

    /**
     * handle coupon indert and update
     */
    public function handle_action()
    {
        $coupon_id = 0;

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

        $pages = [
            'salesloo-coupon'
        ];

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

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

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

                    /**
                     * save coupon data
                     */
                    if (isset($post['ID']) && intval($post['ID']) > 0) {
                        $coupon_id = salesloo_update_coupon($post);
                    } else {
                        $coupon_id = salesloo_insert_coupon($post);
                    }

                    /**
                     * show error notice if failed inserted coupon data otherwise redirect to coupon page
                     */
                    if (is_wp_error($coupon_id)) {
                        $message = $coupon_id->get_error_message();
                        setcookie('salesloo_coupon_failed', $message, time() + 60, COOKIEPATH, COOKIE_DOMAIN);

                        if (isset($post['ID']) && intval($post['ID']) > 0) {
                            $page = 'salesloo-coupon&action=edit&coupon_id=' . intval($post['ID']);
                        } else {
                            $page = 'salesloo-coupon&action=new';
                        }
                    } else {
                        $message = 'Coupon Saved';
                        setcookie('salesloo_coupon_saved_' . $coupon_id, $message, time() + 60, COOKIEPATH, COOKIE_DOMAIN);
                        $page = 'salesloo-coupon&action=edit&coupon_id=' . $coupon_id;
                    }

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

    /**
     * deactivate scheduled active coupon
     */
    public function coupon_active_status_processing()
    {
        $active_coupons = Model_Coupon::select('salesloo_coupon.ID')->query(
            'WHERE status = "active" AND active_end IS NOT NULL AND active_end <= "' . date('Y-m-d H:i:s') . '"'
        )->get();

        if ($active_coupons->found() > 0) {
            foreach ($active_coupons as $coupon) {
                \salesloo_update_coupon_status($coupon->ID, 'inactive');
            }
        }
    }

    /**
     * activate scheduled inactive coupon
     */
    public function coupon_inactive_status_processing()
    {

        $inactive_coupons = Model_Coupon::select('salesloo_coupon.ID')->query(
            'WHERE status = "active" AND active_start IS NOT NULL AND active_end IS NOT NULL AND active_start <= "' . date('Y-m-d H:i:s') . '" AND active_end >= "' . date('Y-m-d H:i:s') . '"'
        )->get();

        if ($inactive_coupons->found() > 0) {
            foreach ($inactive_coupons as $coupon) {
                \salesloo_update_coupon_status($coupon->ID, 'active');
            }
        }
    }

    public function install_hooks()
    {
        add_action('wp_ajax_get_all_products', [$this, 'ajax_get_all_products']);

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

        add_action('salesloo/cron/hourly', [$this, 'coupon_active_status_processing']);
        add_action('salesloo/cron/hourly', [$this, 'coupon_inactive_status_processing']);
    }
}
