<?php

namespace Salesloo;

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

use Form_Parser;
use \Salesloo\AdminTable\Orders as Orders_Table;
use \Salesloo\Models\Order as Model_Order;

/**
 * Order Classes
 */
class Orders
{

    /**
     * Instance.
     *
     * Holds the affiliates 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 Menu
     * 
     * register system info menu
     */
    public function register_menu($submenu)
    {
        $submenu[] = [
            'page_title' => __('Orders', 'salesloo'),
            'menu_title' => __('Orders', 'salesloo'),
            'capability' => 'manage_options',
            'slug'       => 'salesloo-order',
            'callback'   => [$this, 'page'],
            'position'   => 25
        ];

        return $submenu;
    }

    /**
     * show menu page
     */
    public function page()
    {

        if (isset($_GET['order_id']) && $order = salesloo_get_order(intval($_GET['order_id']))) {
?>
            <div class="wrap">
                <h1 class="wp-heading-inline">Order #<?php echo $order->ID; ?></h1>
                <hr class="wp-header-end">
                <form name="post" action="" method="post" class="salesloo-form">
                    <?php wp_nonce_field('salesloo-order'); ?>
                    <div id="poststuff">
                        <div id="post-body" class="metabox-holder columns-2">
                            <div id="post-body-content" style="position: relative;">

                                <?php
                                \salesloo_field_hidden([
                                    'name' => 'ID',
                                    'value' => $order->ID
                                ]);

                                \salesloo_field_title([
                                    'label' => 'Purchase Code',
                                    'name' => 'code',
                                    'value' => sanitize_text_field($order->code),
                                    'readonly' => true
                                ]);

                                $product = salesloo_get_product($order->product_id);

                                \salesloo_field_heading([
                                    'label' => __('Product', 'salesloo'),
                                    'description' => sprintf('<h4>%s<?h4>', $product->title),
                                ]);

                                \salesloo_field_heading([
                                    'label' => __('Customer', 'salesloo'),
                                    'description' => '',
                                ]);

                                do_action('salesloo/admin/order/field/before', $order);

                                $customer = get_userdata($order->user_id);

                                \salesloo_field_text([
                                    'label' => 'Name',
                                    'name' => 'customer[name]',
                                    'value' => salesloo_user_get_name($customer),
                                    'readonly' => true
                                ]);

                                \salesloo_field_text([
                                    'label' => 'Username',
                                    'name' => 'customer[username]',
                                    'value' => $customer->user_login,
                                    'readonly' => true
                                ]);

                                \salesloo_field_text([
                                    'label' => 'Email',
                                    'name' => 'customer[email]',
                                    'value' => $customer->user_email,
                                    'readonly' => true
                                ]);

                                \salesloo_field_text([
                                    'label' => 'Phone',
                                    'name' => 'customer[phone]',
                                    'value' => get_user_meta($customer->ID, 'phone', true),
                                    'readonly' => true
                                ]);

                                do_action('salesloo/admin/order/field/after/customer', $order);

                                $affiliate = get_userdata($order->get_affiliate_id());

                                if (!empty($affiliate)) {
                                    \salesloo_field_heading([
                                        'label' => __('Affiliated By', 'salesloo'),
                                        'description' => '',
                                    ]);

                                    \salesloo_field_text([
                                        'label' => 'Name',
                                        'name' => 'affiliate[name]',
                                        'value' => salesloo_user_get_name($affiliate),
                                        'readonly' => true
                                    ]);

                                    \salesloo_field_text([
                                        'label' => 'Username',
                                        'name' => 'affiliate[username]',
                                        'value' => $affiliate->user_login,
                                        'readonly' => true
                                    ]);

                                    \salesloo_field_text([
                                        'label' => 'Email',
                                        'name' => 'affiliate[email]',
                                        'value' => $affiliate->user_email,
                                        'readonly' => true
                                    ]);

                                    \salesloo_field_text([
                                        'label' => 'Phone',
                                        'name' => 'affiliate[phone]',
                                        'value' => get_user_meta($affiliate->ID, 'phone', true),
                                        'readonly' => true
                                    ]);
                                }

                                do_action('salesloo/admin/order/field/before/detail', $order);

                                \salesloo_field_heading([
                                    'label' => __('Detail', 'salesloo'),
                                    'description' => '',
                                ]);

                                \salesloo_field_text([
                                    'label' => 'License Limit',
                                    'name' => 'license_limit',
                                    'value' => $order->get_license_limit(),
                                ]);

                                \salesloo_field_text([
                                    'label' => 'Renew Price',
                                    'name' => 'renew_price',
                                    'value' => $order->get_renew_price(),
                                ]);

                                \salesloo_field_datepicker([
                                    'label' => 'Expired Date',
                                    'name' => 'expired_at',
                                    'value' => $order->expired_at,
                                ]);

                                \salesloo_field_select([
                                    'label' => 'Status',
                                    'name' => 'status',
                                    'value' => $order->status,
                                    'options' => salesloo_get_order_statuses()
                                ]);

                                do_action('salesloo/admin/order/field/before/submit', $order);

                                \salesloo_field_submit();

                                do_action('salesloo/admin/order/field/after/submit', $order);

                                ?>

                            </div>
                        </div>
                        <div class="clear"></div>
                    </div>

                </form>
            </div>
<?php
        } else {
            $list_table = new Orders_Table();
            $list_table->prepare_items();
            include SALESLOO_PATH . 'assets/partials/orders-list.php';
        }
    }

    /**
     * change order status to expired when expired date is reached
     *
     * @return void
     */
    public function make_expired_order()
    {
        $active_orders = Model_Order::select(['salesloo_order.ID', 'salesloo_order.expired_at'])->query(
            'WHERE status = "active" AND expired_at IS NOT NULL AND expired_at <= "' . date('Y-m-d H:i:s') . '"'
        )->get();

        if ($active_orders->found() > 0) {
            foreach ($active_orders as $order) {
                if (date('Y-m-d', strtotime($order->expired_at)) == '1970-01-01') {
                    continue;
                }
                $old_order_status = $order->status;
                $new_order_status = 'expired';

                $updated = salesloo_update_order_status($order->ID, $new_order_status);
                if (!is_wp_error($updated)) {
                    salesloo_insert_order_log($order->ID, __('Order Expired', 'salesloo'));
                    do_action('salesloo/update/order/status', $order->ID, $new_order_status, $old_order_status);

                    $data = [
                        'order_id' => $order->ID,
                    ];
                    salesloo_add_notification('order_expired', $data);
                    salesloo_add_event('order_expired', $data);
                }
            }
        }
    }

    public function generate_expired_order_reminder_notification()
    {
        $checked_date = get_option('salesloo_order_expired_generate_reminder_date');
        if ($checked_date != date('y-m-d')) {
            update_option('salesloo_order_expired_generate_reminder_date', date('y-m-d'));
            update_option('salesloo_order_expired_generate_reminder_paged', 1);
        }

        $checked_paged = intval(get_option('salesloo_order_expired_generate_reminder_paged'));
        if (!$checked_paged) {
            $checked_paged = 1;
        }

        $days = [7, 1];

        foreach ($days as $key => $day) {

            $is_enable = salesloo_get_option('notification_email_order_expired_reminder_' . $day . '_before');

            if (!$is_enable) continue;

            $active_orders = Model_Order::select('ID')->query(
                'WHERE status = %s AND expired_at IS NOT NULL AND DATE(DATE_ADD(expired_at, INTERVAL -%d DAY)) = %s',
                'active',
                $day,
                date('Y-m-d')
            )->paginate(100, $checked_paged)->get();

            if ($active_orders->found() > 0) {
                foreach ($active_orders as $order) {
                    $data = [
                        'order_id' => $order->ID,
                        'days_before' => $day
                    ];
                    salesloo_add_notification('order_expired_reminder', $data);
                    salesloo_add_event('order_expired_reminder', $data);
                }
            }
        }

        $checked_paged = $checked_paged + 1;
        update_option('salesloo_order_expired_generate_reminder_paged', $checked_paged);
    }

    public function ajax_update_access()
    {
        $nonce = $_REQUEST['nonce'];
        if (!wp_verify_nonce($nonce, 'salesloo-update-order-access')) {
            $message = 'Nonce failed';
        } else {
            $order_id = intval($_POST['order_id']);
            $order = salesloo_update_order_access($order_id);
            if (is_wp_error($order)) {
                $message = $order->get_error_message();
            } else {
                $message = __('Access for order ' . $order->code . ' has Updated', 'salesloo');
            }
        }

        echo $message;
        exit;
    }

    public function order_update()
    {
        if (!isset($_GET['order_id'])) return;

        if (isset($_POST['save']) && isset($_POST['_wpnonce'])) :
            if (wp_verify_nonce($_POST['_wpnonce'], 'salesloo-order')) :

                unset($_POST['save']);
                unset($_POST['_wpnonce']);
                unset($_POST['_wp_http_referer']);

                $order_id = intval($_GET['order_id']);
                if ($order_id != intval($_POST['ID'])) return;

                if ($_POST['license_limit']) {
                    salesloo_update_order_meta($order_id, 'license_limit', intval($_POST['license_limit']));
                }

                salesloo_update_order_meta($order_id, 'renew_price', intval($_POST['renew_price']));

                $args = [
                    'ID' => $order_id,
                    'expired_at' => $_POST['expired_at'] ? date('Y-m-d H:i:s', strtotime($_POST['expired_at'])) : 'NULL',
                    'status' => sanitize_text_field($_POST['status'])
                ];

                salesloo_update_order($args);

                /**
                 * save order meta
                 */
                $metas = $_POST;

                /**
                 * skip is not meta
                 */

                unset($metas['ID']);
                unset($metas['code']);
                unset($metas['customer']);
                unset($metas['status']);
                unset($metas['license_limit']);
                unset($metas['renew_price']);
                unset($metas['expired_at']);

                if ($metas) {
                    foreach ($metas as $key => $val) {
                        salesloo_update_order_meta($order_id, $key, sanitize_text_field($val));
                    }
                }

                do_action('salesloo/admin/order/update', $order_id, $_POST);

                add_action('admin_notices', function () {
                    echo '<div id="message" class="updated notice notice-success"><p><strong>' . __('Your order have been updated.', 'salesloo') . '</strong></p></div>';
                });
            endif;
        endif;
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        add_action('admin_init', [$this, 'order_update']);
        add_filter('salesloo/admin/submenu', [$this, 'register_menu'], 1, 10);

        add_action('salesloo/cron/hourly', [$this, 'make_expired_order']);
        add_action('salesloo/cron/hourly', [$this, 'generate_expired_order_reminder_notification']);

        add_action('wp_ajax_update-order-access', [$this, 'ajax_update_access']);
    }
}
