<?php

namespace Salesloo;

if (!defined('ABSPATH')) {
    exit;
}

use \Salesloo\Models\Access;
use \Salesloo\Models\Access_Meta;
use \Salesloo\AdminTable\File_License;

/**
 * Salesloo File.
 *
 * @since 1.0.0
 */
class Files
{

    /**
     * Instance.
     *
     * Holds the files 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 post type
     */
    public function register_post_type()
    {
        register_post_type(
            'salesloo-file',
            array(
                'labels' => array(
                    'name'               => __('File', 'salesloo'),
                    'singular_name'      => __('File', 'salesloo'),
                    'add_new'            => __('Add New', 'salesloo'),
                    'add_new_item'       => __('Add New File', 'salesloo'),
                    'edit'               => __('Edit', 'salesloo'),
                    'edit_item'          => __('Edit File', 'salesloo'),
                    'new_item'           => __('New File', 'salesloo'),
                    'view'               => __('View File', 'salesloo'),
                    'view_item'          => __('View File', 'salesloo'),
                    'search_items'       => __('Search File', 'salesloo'),
                    'not_found'          => __('No Files found', 'salesloo'),
                    'not_found_in_trash' => __('No Files found in Trash', 'salesloo')
                ),
                'public' => true,
                'hierarchical' => false,
                'has_archive' => false,
                'menu_position' => 5,
                'supports' => array(
                    'title',
                    'editor',
                    'thumbnail',
                    'excerpt'
                ),
                'can_export' => true,
                'menu_icon' => 'dashicons-download',
                'rewrite' =>  array(
                    'slug' => 'file',
                    //'width_front' => false
                ),
            )
        );
        add_rewrite_tag('%__purchase_code%', '([^/]*)');
        add_rewrite_rule(
            '^file/([^/]+)/([^/]+)/?$',
            'index.php?salesloo-file=$matches[1]&__purchase_code=$matches[2]',
            'top'
        );
    }

    /**
     * register metaboxes
     */
    public function metaboxes()
    {
        add_meta_box(
            'metabox_file_upload',
            'Downloadable File',
            [$this, 'metabox_file_upload'],
            'salesloo-file',
            'normal',
            'default'
        );

        add_meta_box(
            'metabox_info',
            'Info',
            [$this, 'metabox_info'],
            'salesloo-file',
            'normal',
            'default'
        );
    }

    /**
     * license setting metabox
     *
     * @return void
     */
    public function metabox_info()
    {
        global $post;

        $license_id = get_post_meta($post->ID, 'license_id', true);

        if (empty($license_id)) {
            $license_id = salesloo_generate_license_item_id();
        }

        wp_nonce_field('salesloo-file', '__nonce');

        \salesloo_field_text([
            'label'       => __('ID', 'salesloo'),
            'description' => __('Change this value, maybe affected to license system', 'salesloo'),
            'name'        => 'license_id',
            'value'       => $license_id,
            // 'conditional' => [
            //     [
            //         'field'   => 'enable_license',
            //         'value'   => '1',
            //         'compare' => '='
            //     ]
            // ],
        ]);

        \salesloo_field_toggle([
            'label' => __('Enable License', 'salesloo'),
            'name'  => 'enable_license',
            'value' => get_post_meta($post->ID, 'enable_license', true),
        ]);

        \salesloo_field_text([
            'label'       => __('Latest Version', 'salesloo'),
            'name'        => 'version',
            'value'       => get_post_meta($post->ID, 'version', true),
            'class' => 'small'
        ]);

        \salesloo_field_file([
            'label'       => __('Latest Version File Download', 'salesloo'),
            'name'        => 'package',
            'value'       => get_post_meta($post->ID, 'package', true),
            'description' => __('You can use an external url file', 'salesloo'),
        ]);

        \salesloo_field_editor([
            'label'       => __('Changelog', 'salesloo'),
            'description' => __('Change this value, maybe affected to license system', 'salesloo'),
            'name'        => 'changelog',
            'value'       => get_post_meta($post->ID, 'changelog', true),
            'options' => [
                'media_buttons' => false
            ]
        ]);
    }


    /**
     * file upload metabox
     *
     * @return void
     */
    public function metabox_file_upload()
    {
        global $post;

        $files = get_post_meta($post->ID, 'downloadable-file', true);

        wp_nonce_field('salesloo-file', '__nonce');
        include SALESLOO_PATH . 'assets/fields/admin/file-upload.php';
    }

    /**
     * Save metabox
     * 
     * handle metabox save
     */
    public function metabox_save($post_id, $post)
    {

        if (!current_user_can('edit_post', $post_id)) {
            return $post_id;
        }

        if (!isset($_POST['__nonce'])) return $post_id;

        if (!wp_verify_nonce($_POST['__nonce'], 'salesloo-file')) {
            return $post_id;
        }

        $files = isset($_POST['file']) ? $_POST['file'] : [];

        if ($files) {
            $new_files = [];
            foreach ((array)$files['filename'] as $key => $val) {
                $new_files[$key] = [
                    'name' => $val,
                    'file' => $files['fileurl'][$key]
                ];
            }

            update_post_meta($post_id, 'downloadable-file', $new_files);
        }

        $enable_license = isset($_POST['enable_license']) ? sanitize_text_field($_POST['enable_license']) : 0;
        update_post_meta($post_id, 'enable_license', $enable_license);

        $license_id = isset($_POST['license_id']) ? sanitize_text_field($_POST['license_id']) : salesloo_generate_license_item_id();
        update_post_meta($post_id, 'license_id', $license_id);

        $version = isset($_POST['version']) ? sanitize_text_field($_POST['version']) : '1.0.0';
        update_post_meta($post_id, 'version', $version);

        $package = isset($_POST['package']) ? esc_url($_POST['package']) : '';
        update_post_meta($post_id, 'package', $package);

        $changelog = isset($_POST['changelog']) ? wp_kses_post(wpautop($_POST['changelog'])) : '';
        update_post_meta($post_id, 'changelog', $changelog);
    }


    /**
     * single file template
     *
     * @param  mixed $template
     * @return string
     */
    public function template($template)
    {
        global $wp;

        if (!is_singular('salesloo-file')) return $template;

        $template = \salesloo_get_template('single-file.php');

        return $template;
    }

    /**
     * load protected file page
     *
     * @return void
     */
    public function file_load()
    {
        global $___salesloo;

        if (!is_singular('salesloo-file')) return;

        $purchase_code = get_query_var('__purchase_code');

        if ($purchase_code && is_user_logged_in()) {

            $user_id = get_current_user_id();
            $query = "WHERE user_id = $user_id AND status = 'active' AND code = '$purchase_code'";

            $access = Access::join('LEFT', 'salesloo_order', ['order_id', 'ID', '='])
                ->select(
                    ['salesloo_access.*'],
                    ['salesloo_order.code'],
                    ['salesloo_order.user_id'],
                    ['salesloo_order.product_id'],
                    ['salesloo_order.status'],
                    ['salesloo_order.expired_at'],
                )
                ->query($query)
                ->first();

            if ($access->ID > 0) {

                if (isset($_GET['download'])) {
                    $encrypted_file = sanitize_text_field($_GET['download']);
                    if ($encrypted_file) {
                        salesloo_local_download_now($encrypted_file);
                    }
                }

                $order = salesloo_get_order($access->order_id);

                $active_hosts = [];
                $number = 1;
                foreach ((array)$access->meta('license') as $host) {
                    $data = salesloo_get_access_meta($access->ID, 'license_' . $host, true);
                    if (isset($data['activate_at']) && isset($data['last_checked'])) {
                        $active_hosts[] = [
                            'number' => $number,
                            'host' => $host,
                            'activate_at' => 'Activate at : ' . $data['activate_at'],
                            'last_checked' => 'Last Checked Request : ' . $data['last_checked'],
                            'delete' => [
                                'host' => $host,
                                'nonce' => salesloo_create_nonce(),
                                'action' => 'deactivate_license'
                            ]
                        ];
                    }

                    $number++;
                }

                $___salesloo['purchase_code'] = $purchase_code;
                $___salesloo['access']        = $access;
                $___salesloo['target']        = 'user';
                $___salesloo['title']         = 'Access File';
                $___salesloo['active_hosts']  = $active_hosts;
                $___salesloo['license']       = (object)[
                    'limit' => $order->get_license_limit(),
                    'used'  => $access->meta('license') ? count((array)$access->meta('license')) : 0,
                    'expired' => $access->expired_at ? date('M d, Y', strtotime($access->expired_at)) : 'Lifetime',
                ];

                $files = get_post_meta(get_the_ID(), 'downloadable-file', true);

                $downloads = [];
                foreach ($files as $file) {
                    $code = salesloo_encrypt($file['file']);
                    $downloads[] = [
                        'name' => $file['name'],
                        'link' => get_the_permalink(get_the_ID()) . $access->code . '/?download=' . $code
                    ];
                }

                $___salesloo['files'] = $downloads;

                $input = file_get_contents("php://input");
                $request = json_decode($input, true);

                if (isset($request['nonce']) && salesloo_verify_nonce($request['nonce'])) {
                    if (isset($request['action']) && $request['action'] == 'deactivate_license') {

                        $license_host = sanitize_text_field($request['host']);

                        Access_Meta::delete([
                            'access_id'  => $access->ID,
                            'meta_key'   => 'license',
                            'meta_value' => $license_host,
                        ]);

                        Access_Meta::delete([
                            'access_id'  => $access->ID,
                            'meta_key'   => 'license_' . $license_host,
                        ]);

                        $response = [
                            'message' => sprintf(__('Host "%s" has been deactivated', 'salesloo'), $license_host),
                        ];

                        echo json_encode($response);
                        exit;
                    }
                }

                return;
            }
        }

        if (current_user_can('administrator') || current_user_can('editor')) {
            $___salesloo['target']   = 'user';
            return;
        }

        wp_die(__('Sorry, you don\'t have acces to this page', 'salesloo'));
    }

    /**
     * license_menu
     *
     * @return void
     */
    public function license_menu()
    {
        add_submenu_page(
            'edit.php?post_type=salesloo-file',
            'License',
            'License',
            'manage_options',
            'license',
            [$this, 'license_page']
        );
    }


    /**
     * license_page
     *
     * @return void
     */
    public function license_page()
    {
        $single = false;

        if (isset($_GET['code'])) {
            $purchase_code = sanitize_text_field($_GET['code']);

            $query = "WHERE code = '$purchase_code'";

            $access = Access::join('LEFT', 'salesloo_order', ['order_id', 'ID', '='])
                ->select(
                    ['salesloo_access.*'],
                    ['salesloo_order.code'],
                    ['salesloo_order.user_id'],
                    ['salesloo_order.product_id'],
                    ['salesloo_order.status'],
                    ['salesloo_order.expired_at'],
                    ['salesloo_order.created_at'],
                )
                ->query($query)
                ->first();

            if ($access->ID > 0) {
                $single = true;

                $product = salesloo_get_product($access->product_id);
                $order   = salesloo_get_order($access->order_id);

                $current_license       = $access->meta('license');
                $count_current_license = $current_license ? count((array)$current_license) : 0;
                $customer = get_userdata($access->user_id);

                $licenses = [];
                foreach ((array)$access->meta('license') as $license) {
                    $data = salesloo_get_access_meta($access->ID, 'license_' . $license, true);
                    if ($data) {
                        $licenses[] = [
                            'host' => $license,
                            'activate_at' => $data['activate_at'],
                            'last_checked' => $data['last_checked'],
                        ];
                    }
                }

                $nonce = wp_create_nonce('salesloo-delete-access-license-host');

?>
                <div class="wrap">
                    <h2><?php _e('License Details', 'salesloo'); ?></h2>
                    <div class="salesloo-item-has-tabs salesloo-clearfix">

                        <div class="salesloo-sl-license-card">
                            <div class="info-wrapper item-section">
                                <div class="item-info">
                                    <table class="widefat striped">
                                        <tbody>
                                            <tr>
                                                <td class="row-title">
                                                    <label for="tablecell"><?php _e('License Key:', 'salesloo'); ?></label>
                                                </td>
                                                <td style="word-wrap: break-word">
                                                    <?php echo $access->code; ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td class="row-title">
                                                    <label for="tablecell"><?php _e('Purchase Date:', 'salesloo'); ?></label>
                                                </td>
                                                <td>
                                                    <a target="__blank" href="<?php echo admin_url('admin.php?page=salesloo-order&order_id=' . $access->order_id); ?>"><?php echo date('d M, Y - H:i', strtotime($access->created_at)) ?></a>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td class="row-title">
                                                    <label for="tablecell"><?php _e('Expiration Date:', 'salesloo'); ?></label>
                                                </td>
                                                <td>
                                                    <?php echo $access->expired_at ? date('d M, Y - H:i', strtotime($access->expired_at)) : 'Lifetime'; ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td class="row-title">
                                                    <label for="tablecell"><?php _e('Product:', 'salesloo'); ?></label>
                                                </td>
                                                <td>
                                                    <a href="<?php echo admin_url('admin.php?page=salesloo-product&product_id=' . $product->ID); ?>"><?php echo $product->title; ?></a>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td class="row-title">
                                                    <label for="tablecell"><?php _e('Activation Limit:', 'salesloo'); ?></label>
                                                </td>
                                                <td>
                                                    <span class="salesloo-sl-limit-wrap"><?php echo $count_current_license; ?> / <span id="salesloo-sl-1-limit"><?php echo $order->get_license_limit(); ?></span>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td class="row-title">
                                                    <label for="tablecell"><?php _e('Status:', 'salesloo'); ?></label>
                                                </td>
                                                <td>
                                                    <?php echo salesloo_get_order_statuses($order->status); ?>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td class="row-title">
                                                    <label for="tablecell"><?php _e('Customer:', 'salesloo'); ?></label>
                                                </td>
                                                <td>
                                                    <a target="_blank" href="<?php echo admin_url('user-edit.php?user_id=' . $customer->ID); ?>"><?php echo salesloo_user_get_name($customer); ?> (<?php echo $customer->user_email; ?>)</a>
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>


                            <div id="salesloo-item-tables-wrapper" class="item-section">
                                <h3><?php _e('Licensed Host', 'salesloo'); ?></h3>
                                <table class="wp-list-table widefat striped licensed-urls">
                                    <thead>
                                        <tr>
                                            <th><?php _e('Host', 'salesloo') ?></th>
                                            <th><?php _e('Activate date', 'salesloo') ?></th>
                                            <th><?php _e('Last checked', 'salesloo') ?></th>
                                            <th>&nbsp;</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($licenses as $license) : ?>
                                            <tr class="row alternate">
                                                <td><?php echo $license['host']; ?></td>
                                                <td><?php echo $license['activate_at']; ?></td>
                                                <td><?php echo $license['last_checked']; ?></td>
                                                <td style="text-align:right"><span class="salesloo-delete-access-license-host" style="cursor:pointer;color:#2271b1;" data-host="<?php echo $license['host']; ?>" data-access-id="<?php echo $access->ID; ?>" data-nonce="<?php echo $nonce; ?>">Deactivate Site</span></td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>

                        </div>

                    </div>
                </div>
            <?php
            }
        }

        if ($single == false) {
            $list_table = new File_License();
            $list_table->prepare_items();

            ob_start();
            ?>
            <div class="wrap">
                <h1 class="wp-heading-inline"><?php echo esc_html(__('Manage License', 'salesloo')); ?></h1>

                <hr class="wp-header-end">
                <form method="get" action="">
                    <?php $list_table->views(); ?>
                    <?php $list_table->search_box(__('Search License', 'salesloo'), 'salesloo-button');
                    ?>
                    <?php $list_table->display();
                    ?>
                </form>
            </div>
<?php

        }

        $content = ob_get_clean();

        echo $content;
    }


    public function ajax_delete_access_license_host()
    {
        $nonce = $_REQUEST['nonce'];
        if (!wp_verify_nonce($nonce, 'salesloo-delete-access-license-host')) {
            echo 'Nonce failed';
        } else {
            $access_id = intval($_POST['access_id']);
            $host = sanitize_text_field($_POST['host']);

            $ss = Access_Meta::delete([
                'access_id'  => $access_id,
                'meta_key'   => 'license',
                'meta_value' => $host,
            ]);

            Access_Meta::delete([
                'access_id'  => $access_id,
                'meta_key'   => 'license_' . $host,
            ]);

            echo 1;
        }
        exit;
    }

    /**
     * constructor.
     */
    public function __construct()
    {
        add_action('wp', [$this, 'file_load']);
        add_action('init', [$this, 'register_post_type']);
        add_action('add_meta_boxes', [$this, 'metaboxes']);
        add_action('save_post', [$this, 'metabox_save'], 1, 2);

        add_action('admin_menu', [$this, 'license_menu']);

        add_filter('single_template', [$this, 'template']);

        add_action('wp_ajax_delete-access-license-host', [$this, 'ajax_delete_access_license_host']);
    }
}
