<?php

namespace Salesloo;

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

use \Salesloo\Models\Access;

/**
 * Page
 *
 * @since 1.0.0
 */
class Page
{

    /**
     * Instance.
     *
     * Holds the page 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;
    }

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

        if (!is_singular()) return;

        if (is_page() || 'post' == get_post_type()) {

            /**
             * by pass if current user is administrator
             */
            if (current_user_can('administrator') || current_user_can('editor')) return;

            $products = get_post_meta(get_the_ID(), '__salesloo_protected', false);

            if (empty($products)) return;

            $products = implode(',', $products);

            if (is_user_logged_in()) {

                $user_id = get_current_user_id();
                $item_id = get_the_ID();

                $query = "WHERE user_id = $user_id AND status = 'active' AND item_id = '$item_id' AND product_id IN($products)";

                $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)
                    ->get();

                if ($access->found > 0) {
                    $salesloo_data['access'] = $access;

                    return;
                }
            }

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

    /**
     * Plugin constructor.
     *
     * @since 1.0.0
     * @access private
     */
    private function __construct()
    {
        add_action('wp', [$this, 'load']);
    }
}
