<?php

namespace Salesloo;

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

/**
 * Salesloo Admin
 */
class Admin
{
    public $dashboard;

    public $affiliate;

    public $affiliate_leaderboard;

    public $affiliate_commission;

    public $affiliate_payout;

    public $coupon;

    public $invoice;

    /**
     * Instance.
     *
     * Hold salesloo admin instance.
     *
     * @since 1.0.0
     * @access public
     */
    public static $instance = null;

    /**
     * Init
     * 
     * Initialize Salesloo admin
     */
    public static function init()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * construct
     */
    public function __construct()
    {
        $this->load();
        $this->install_hooks();
    }

    /**
     * load dependcies
     *
     * @return void
     */
    private function load()
    {
        require_once SALESLOO_PATH . 'includes/admin/dashboard.php';
        require_once SALESLOO_PATH . 'includes/admin/affiliate.php';
        require_once SALESLOO_PATH . 'includes/admin/affiliate-leaderboard.php';
        require_once SALESLOO_PATH . 'includes/admin/affiliate-commission.php';
        require_once SALESLOO_PATH . 'includes/admin/affiliate-payout.php';
        require_once SALESLOO_PATH . 'includes/admin/coupon.php';
        require_once SALESLOO_PATH . 'includes/admin/invoice.php';

        $this->dashboard = new Admin\Dashboard();
        $this->affiliate = new Admin\Affiliate();
        $this->affiliate_leaderboard = new Admin\Affiliate_Leaderboard();
        $this->affiliate_commission = new Admin\Affiliate_Commission();
        $this->affiliate_payout = new Admin\Affiliate_Payout();
        $this->coupon = new Admin\Coupon();
        $this->invoice = new Admin\Invoice();
    }

    /**
     * get salesloo pages
     *
     * @return array
     */
    public function pages()
    {
        $pages = [
            'salesloo',
            'salesloo-affiliate',
            'salesloo-affiliate-leaderboard',
            'salesloo-affiliate-commission',
            'salesloo-affiliate-payout',
            //'salesloo-coupon'
        ];

        $pages = apply_filters('salesloo/admin/pages', $pages);

        return $pages;
    }


    /**
     * enqueue
     *
     * @return void
     */
    public function enqueue_styles()
    {
        wp_enqueue_style('daterangepicker', 'https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css');
        wp_enqueue_style('salesloo-admin-fields', SALESLOO_ASSETS . 'css/admin-fields.css', array(), strtotime('now'), 'all');
        wp_enqueue_style('salesloo-admin', SALESLOO_ASSETS . 'css/admin.css', array(), strtotime('now'), 'all');


        wp_enqueue_media();
        add_thickbox();

        wp_enqueue_style('wp-color-picker');

        wp_enqueue_script('select2', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js', array('jquery'), '4.0.13', true);
        wp_enqueue_script('daterangepicker', 'https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js', array('jquery', 'moment'), '3.1', true);
        wp_enqueue_script('salesloo-admin-fields', SALESLOO_ASSETS . 'js/admin-fields.js', array('jquery', 'select2', 'jquery-ui-sortable', 'jquery-ui-tabs', 'wp-color-picker'), strtotime('now'), true);
        wp_enqueue_script('salesloo-admin', SALESLOO_ASSETS . 'js/admin.js', array('jquery', 'select2', 'jquery-ui-sortable', 'jquery-ui-tabs'), strtotime('now'), true);

        if ($this->current_is_salesloo_page()) {
            /**
             * styles
             */
            wp_enqueue_style(
                'salesloo-admin-tailwindcss',
                SALESLOO_ASSETS . 'css/style.css',
                array(),
                strtotime('now'),
                'all'
            );

            do_action('salesloo/admin/styles');

            /**
             * scripts
             */

            wp_enqueue_script(
                'salesloo-scripts',
                SALESLOO_ASSETS . 'js/app.js',
                [],
                strtotime('now'),
                true
            );

            do_action('salesloo/admin/script');
        }
    }

    /**
     * is_salesloo_page
     * 
     * check if current page is salesloo page
     *
     * @return void
     */
    public function current_is_salesloo_page()
    {
        $page = isset($_GET['page']) ? sanitize_text_field($_GET['page']) : '';

        $pages = $this->pages();

        if (in_array($page, $pages)) return true;

        return false;
    }

    /**
     * register wp admin menu
     * 
     * register salesloo main menu
     *
     * @return void
     */
    public function menu()
    {
        add_menu_page(
            __('Salesloo', 'salesloo'),
            __('Salesloo', 'salesloo'),
            'manage_options',
            'salesloo',
            [$this->dashboard, 'template'],
            'dashicons-admin-settings',
            3
        );

        $submenu = [
            [
                'page_title' => __('Invoice', 'salesloo'),
                'menu_title' => __('Invoice', 'salesloo'),
                'capability' => 'manage_options',
                'slug'       => 'salesloo-invoice',
                'callback'   => [$this->invoice, 'template'],
                'position'   => 26
            ],
            [
                'page_title' => __('Affiliate', 'salesloo'),
                'menu_title' => __('Affiliate', 'salesloo'),
                'capability' => 'manage_options',
                'slug'       => 'salesloo-affiliate',
                'callback'   => [$this->affiliate, 'template'],
                'position'   => 32
            ],
            [
                'page_title' => __('Aff Leaderboard', 'salesloo'),
                'menu_title' => __('Aff Leaderboard', 'salesloo'),
                'capability' => 'manage_options',
                'slug'       => 'salesloo-affiliate-leaderboard',
                'callback'   => [$this->affiliate_leaderboard, 'template'],
                'position'   => 33
            ],
            [
                'page_title' => __('Aff Commission', 'salesloo'),
                'menu_title' => __('Aff Commission', 'salesloo'),
                'capability' => 'manage_options',
                'slug'       => 'salesloo-affiliate-commission',
                'callback'   => [$this->affiliate_commission, 'template'],
                'position'   => 34
            ],
            [
                'page_title' => __('Aff Payout', 'salesloo'),
                'menu_title' => __('Aff Payout', 'salesloo'),
                'capability' => 'manage_options',
                'slug'       => 'salesloo-affiliate-payout',
                'callback'   => [$this->affiliate_payout, 'template'],
                'position'   => 35
            ],
            [
                'page_title' => __('Coupons', 'salesloo'),
                'menu_title' => __('Coupons', 'salesloo'),
                'capability' => 'manage_options',
                'slug'       => 'salesloo-coupon',
                'callback'   => [$this->coupon, 'template'],
                'position'   => 40
            ]
        ];

        $submenu = apply_filters('salesloo/admin/submenu', $submenu);
        $shorted_submenu = [];

        foreach ((array) $submenu as $sub) {

            if (!isset($sub['menu_title']) || !isset($sub['page_title']) || !isset($sub['slug']) || !isset($sub['callback'])) continue;
            $position = isset($sub['position']) ? intval($sub['position']) : 98;

            if (isset($shorted_submenu["$position"])) {
                $position = $position + substr(base_convert(md5($sub['slug'] . $sub['page_title']), 16, 10), -5) * 0.00001;
            }

            if (!isset($sub['capability'])) {
                $sub['capability'] = 'manage_options';
            }

            $shorted_submenu["$position"] = $sub;
        }


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

        foreach ($shorted_submenu as $sub) {
            add_submenu_page(
                'salesloo',
                $sub['page_title'],
                $sub['menu_title'],
                $sub['capability'],
                $sub['slug'],
                $sub['callback']
            );
        }
    }

    /**
     * add salesloo member admin_bar_item
     *
     * @param  mixed $admin_bar
     * @return void
     */
    public function admin_bar_item(\WP_Admin_Bar $admin_bar)
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        $admin_bar->add_menu(array(
            'id'    => 'salesloo-admin-bar',
            'parent' => null,
            'group'  => null,
            'title' => 'Member Dashboard',
            'href'  => site_url() . '/dashboard',
            'meta' => [
                'title' => __('Member Dashboard', 'salesloo'),
            ]
        ));
    }

    public function ajax_upload_media()
    {
        \Salesloo\Plugin::instance()->admin_ajax->verify_nonce($_REQUEST['nonce'], 'salesloo_upload_media');

        if (isset($_FILES['media'])) {
            $file = $_FILES['media'];
            $type = $file['type'];
            $extensions = array('image/jpeg', 'image/png', 'image/gif');

            if (in_array($type, $extensions)) {
                $upload = wp_upload_bits($file['name'], null, file_get_contents($file['tmp_name']));

                if (!is_wp_error($upload)) {

                    $filename = $upload['file'];
                    $wp_upload_dir = wp_upload_dir();

                    $attachment = array(
                        'guid'           => $wp_upload_dir['url'] . '/' . basename($filename),
                        'post_mime_type' => $upload['type'],
                        'post_title'     => preg_replace('/\.[^.]+$/', '', basename($filename)),
                        'post_content'   => '',
                        'post_status'    => 'inherit'
                    );

                    // Insert the attachment.
                    $attach_id = wp_insert_attachment($attachment, $filename);

                    // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
                    require_once(ABSPATH . 'wp-admin/includes/image.php');

                    // Generate the metadata for the attachment, and update the database record.
                    $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
                    wp_update_attachment_metadata($attach_id, $attach_data);

                    $respons = [
                        'message' => __('Media uploaded', 'salesloo'),
                        'url' => esc_url_raw($upload['url']),
                        'id' => $attach_id
                    ];
                    $status = 200;
                } else {
                    $respons = [
                        'message' => is_object($upload) ? $upload->get_error_message() : ''
                    ];
                    $status = 500;
                }
            } else {
                $respons = [
                    'message' => __('No media', 'salesloo')
                ];
                $status = 500;
            }

            wp_send_json($respons, $status);
        }
    }

    /**
     * install_hooks
     *
     * @return void
     */
    public function install_hooks()
    {
        add_action('wp_ajax_salesloo_upload_media', [$this, 'ajax_upload_media']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_styles']);
        add_action('admin_bar_menu', [$this, 'admin_bar_item'], 500);
        add_action('admin_menu', [$this, 'menu']);

        $this->dashboard->install_hooks();
        $this->affiliate->install_hooks();
        $this->affiliate_leaderboard->install_hooks();
        $this->affiliate_commission->install_hooks();
        $this->affiliate_payout->install_hooks();
        $this->coupon->install_hooks();
        $this->invoice->install_hooks();
    }
}
