<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://wpgeenie.org
 * @since      1.0.0
 *
 * @package    Spending_Limits_For_Woocommerce
 * @subpackage Spending_Limits_For_Woocommerce/admin
 */
/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Spending_Limits_For_Woocommerce
 * @subpackage Spending_Limits_For_Woocommerce/admin
 * @author     wpgeenie.org <info@wpgeenie.org>
 */
class Spending_Limits_For_Woocommerce_Admin {
    /**
     * The ID of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $plugin_name    The ID of this plugin.
     */
    private $plugin_name;

    /**
     * The version of this plugin.
     *
     * @since    1.0.0
     * @access   private
     * @var      string    $version    The current version of this plugin.
     */
    private $version;

    /**
     * Initialize the class and set its properties.
     *
     * @since    1.0.0
     * @param string $plugin_name The name of this plugin.
     * @param string $version The version of this plugin.
     */
    public function __construct( $plugin_name, $version ) {
        $this->plugin_name = $plugin_name;
        $this->version = $version;
    }

    /**
     * Register the stylesheets for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_styles() {
        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Spending_Limits_For_Woocommerce_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Spending_Limits_For_Woocommerce_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */
        wp_enqueue_style(
            $this->plugin_name,
            plugin_dir_url( __FILE__ ) . 'css/spending-limits-for-woocommerce-admin.css',
            array(),
            $this->version,
            'all'
        );
    }

    /**
     * Register the JavaScript for the admin area.
     *
     * @since    1.0.0
     */
    public function enqueue_scripts() {
        /**
         * This function is provided for demonstration purposes only.
         *
         * An instance of this class should be passed to the run() function
         * defined in Spending_Limits_For_Woocommerce_Loader as all of the hooks are defined
         * in that particular class.
         *
         * The Spending_Limits_For_Woocommerce_Loader will then create the relationship
         * between the defined hooks and the functions defined in this
         * class.
         */
        wp_enqueue_script(
            $this->plugin_name,
            plugin_dir_url( __FILE__ ) . 'js/spending-limits-for-woocommerce-admin.js',
            array('jquery', 'jquery-ui-datepicker'),
            $this->version,
            false
        );
    }

    /**
     * Add plugin row meta
     *
     * @param  mixed $links .
     * @param  mixed $file .
     *
     * @return array
     */
    public function add_plugin_row_meta( $links, $file ) {
        if ( slfw_fs()->get_plugin_basename() === $file ) {
            $row_meta = array(
                'upgrade' => '<a href="' . esc_url( slfw_fs()->get_upgrade_url() ) . '" target="_blank" aria-label="' . esc_attr__( 'Upgrade to pro', 'spending-limits-for-woocommerce' ) . '" style="color:Magenta;font-weight:700;">' . esc_html__( 'Upgrade to pro', 'spending-limits-for-woocommerce' ) . '</a>',
            );
            return array_merge( $links, $row_meta );
        }
        return (array) $links;
    }

    /**
     * Add admin menu
     *
     * @return void
     */
    public function add_admin_menu_free() {
        add_menu_page(
            esc_html__( 'Spending Limits', 'spending-limits-for-woocommerce' ),
            esc_html__( 'Spending Limits', 'spending-limits-for-woocommerce' ),
            'manage_options',
            'spending-limits',
            array($this, 'render_admin_dashboard_page'),
            'dashicons-money',
            56
        );
    }

    /**
     * Add_user_fields_in_admin
     *
     * @param  mixed $user user class.
     * @return void
     */
    public static function add_user_fields_in_admin( $user ) {
        // Only show for admins.
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        include apply_filters( 'spending_limits_for_woocommerce_admin_user_fields_template_file', plugin_dir_path( __DIR__ ) . 'admin/partials/user-profile-fields.php' );
    }

    /**
     * Render_admin_dashboard_page
     *
     * @return void
     */
    public static function render_admin_dashboard_page() {
        // Only show for admins.
        if ( !current_user_can( 'manage_options' ) ) {
            return;
        }
        include plugin_dir_path( __DIR__ ) . 'admin/partials/spending-limits-info.php';
    }

    /**
     * Save_user_profile_fields
     *
     * @param  mixed $user_id user id.
     * @return void
     */
    public static function save_user_profile_fields( $user_id ) {
        if ( empty( $_POST['_wpnonce'] ) || !wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['_wpnonce'] ) ), 'update-user_' . $user_id ) ) {
            return;
        }
        if ( !current_user_can( 'edit_user', $user_id ) ) {
            return;
        }
        // Save or delete the lock until date.
        if ( isset( $_POST['locklength'] ) ) {
            switch ( $_POST['locklength'] ) {
                case '1w':
                    $lock_until = gmdate( 'Y-m-d H:i:s', strtotime( ' + 1 week ' ) );
                    break;
                case '4w':
                    $lock_until = gmdate( 'Y-m-d H:i:s', strtotime( ' + 4 weeks ' ) );
                    break;
                case '12w':
                    $lock_until = gmdate( 'Y-m-d H:i:s', strtotime( ' + 12 weeks ' ) );
                    break;
                case '1y':
                    $lock_until = gmdate( 'Y-m-d H:i:s', strtotime( ' + 1 year ' ) );
                    break;
                case 'permanent':
                    $lock_until = 'permanent';
                    break;
                default:
                    $lock_until = false;
                    break;
            }
            if ( $lock_until ) {
                update_user_meta( $user_id, 'spending_limit_lock_until', $lock_until );
                Spending_Limits_For_Woocommerce::insert_log(
                    $user_id,
                    /* translators: date */
                    sprintf( esc_html__( 'Admin set lock until %s. ', 'spending-limits-for-woocommerce' ), esc_html( $lock_until ) ),
                    1,
                    get_current_user_id()
                );
                do_action( 'spending_limits_for_woocommerce_add_admin_lock', $user_id, $lock_until );
            } elseif ( 'clear' === $_POST['locklength'] ) {
                delete_user_meta( $user_id, 'spending_limit_lock_until' );
                Spending_Limits_For_Woocommerce::insert_log(
                    $user_id,
                    esc_html__( 'Admin removed lock.', 'spending-limits-for-woocommerce' ),
                    2,
                    get_current_user_id()
                );
                do_action( 'spending_limits_for_woocommerce_admin_remove_lock', $user_id, $lock_until );
            }
        } else {
            delete_user_meta( $user_id, 'spending_limit_lock_until' );
        }
        // validate and save spending limit.
        if ( isset( $_POST['spend_limit_amount'] ) ) {
            $spend_limit_amount = intval( $_POST['spend_limit_amount'] );
            $spend_limit_period = ( isset( $_POST['spend_limit_period'] ) ? sanitize_text_field( wp_unslash( $_POST['spend_limit_period'] ) ) : false );
            $spend_limit_period_custom = ( isset( $_POST['spend_limit_period_custom'] ) ? abs( intval( sanitize_text_field( wp_unslash( $_POST['spend_limit_period_custom'] ) ) ) ) : 0 );
            $spend_limit_period_custom_time = ( isset( $_POST['spend_limit_period_custom_time'] ) ? sanitize_text_field( wp_unslash( $_POST['spend_limit_period_custom_time'] ) ) : false );
            $old_spend_limit_amount = intval( get_user_meta( $user_id, 'spend_limit_amount', true ) );
            $old_spend_limit_period = get_user_meta( $user_id, 'spend_limit_period', true );
            $old_spend_limit_period_custom = intval( get_user_meta( $user_id, 'spend_limit_period_custom', true ) );
            $old_spend_limit_period_custom_time = get_user_meta( $user_id, 'spend_limit_period_custom_time', true );
            if ( $spend_limit_amount > 0 && 'clear' !== $spend_limit_period ) {
                update_user_meta( $user_id, 'spend_limit_amount', $spend_limit_amount );
                update_user_meta( $user_id, 'spend_limit_period', $spend_limit_period );
                if ( $old_spend_limit_amount !== $spend_limit_amount || $old_spend_limit_period !== $spend_limit_period || 'custom' === $spend_limit_period && $spend_limit_period_custom !== $old_spend_limit_period_custom || 'custom' === $spend_limit_period && $spend_limit_period_custom_time !== $old_spend_limit_period_custom_time ) {
                    $spend_limit_period_text = $spend_limit_period;
                    $message = sprintf( 
                        /* translators: 1.value 2.period */
                        esc_html__( 'Admin set limit %1$s per %2$s.', 'spending-limits-for-woocommerce' ),
                        wp_strip_all_tags( wc_price( $spend_limit_amount ) ),
                        $spend_limit_period_text
                     );
                    Spending_Limits_For_Woocommerce::insert_log(
                        $user_id,
                        $message,
                        3,
                        get_current_user_id()
                    );
                    do_action(
                        'spending_limits_for_woocommerce_admin_add_limit',
                        $user_id,
                        $spend_limit_amount,
                        $spend_limit_period
                    );
                }
            } else {
                delete_user_meta( $user_id, 'spend_limit_amount' );
                delete_user_meta( $user_id, 'spend_limit_period' );
                $message = esc_html__( 'Admin removed limit. ', 'spending-limits-for-woocommerce' );
                Spending_Limits_For_Woocommerce::insert_log(
                    $user_id,
                    $message,
                    4,
                    get_current_user_id()
                );
                do_action(
                    'spending_limits_for_woocommerce_admin_remove_limit',
                    $user_id,
                    $spend_limit_amount,
                    $spend_limit_period
                );
            }
        }
    }

}
