<?php

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

/**
 * salesloo_insert_product
 *
 * @param  array $data
 * @return mixed
 */
function salesloo_insert_product($data = [])
{
    $data = apply_filters('salesloo/product/insert/data', $data);

    if (empty($data) || !is_array($data)) return false;

    $product_args = [
        'slug'         => salesloo_generate_product_slug(),
        'status'       => isset($data['status']) ? sanitize_text_field($data['status']) : 'draft'
    ];

    $args = $data;

    foreach (Salesloo\Models\Product::get_columns() as $key => $type) {
        if ('ID' == $key || 'slug' == $key || 'status' == $key) continue;

        if (isset($args[$key])) {
            $product_args[$key] = $args[$key];
            unset($args[$key]);
        }
    }

    $product_id = Salesloo\Models\Product::data($product_args)->create();

    if (is_wp_error($product_id)) {
        return $product_id;
    }

    if (isset($args['ID'])) {
        unset($args['ID']);
    }

    if (!isset($args['scheduled_start']) || empty($args['scheduled_start'])) {
        $args['scheduled_start'] = 'NULL';
    }

    if (!isset($args['scheduled_end']) || empty($args['scheduled_end'])) {
        $args['scheduled_end'] = 'NULL';
    }

    foreach ($args as $meta_key => $meta_value) {
        salesloo_add_product_meta($product_id, $meta_key, $meta_value);
    }

    return $product_id;
}

/**
 * salesloo_update_product
 *
 * @param  array $data
 * @return mixed
 */
function salesloo_update_product($data = [])
{
    $data = apply_filters('salesloo/product/update/data', $data);

    if (empty($data) || !is_array($data)) return false;

    $product_id = isset($data['ID']) ? intval($data['ID']) : 0;
    $product = salesloo_get_product($product_id);

    if (false === $product) {
        return salesloo_insert_product($data);
    }

    $product_args = [];

    $args = $data;

    foreach (Salesloo\Models\Product::get_columns() as $key => $type) {
        if (isset($args[$key])) {
            $product_args[$key] = $args[$key];
            unset($args[$key]);
        }
    }

    $product_args['updated_at'] = date('Y-m-d H:i:s');

    $updated = Salesloo\Models\Product::data($product_args)
        ->update([
            'ID' => $product_id
        ]);

    if (is_wp_error($updated)) {
        return $updated;
    }

    unset($data['ID']);

    if (!isset($args['scheduled_start']) || empty($args['scheduled_start'])) {
        $args['scheduled_start'] = 'NULL';
    }

    if (!isset($args['scheduled_end']) || empty($args['scheduled_end'])) {
        $args['scheduled_end'] = 'NULL';
    }

    foreach ($args as $meta_key => $meta_value) {
        salesloo_update_product_meta($product_id, $meta_key, $meta_value);
    }

    return $product_id;
}

function salesloo_update_product_status($product = 0, $new_status = '')
{

    $product = salesloo_get_product($product);

    if (false === $product) return $product;

    $new_status = apply_filters('salesloo/product/update/status', $new_status, $product->status);

    $status = salesloo_get_product_statuses($new_status);

    if (false === $status) {
        return new WP_Error('error', sprintf(__('"%s" is Invalid product statuses', 'salesloo'), $new_status));
    }

    $updated = Salesloo\Models\Product::data(['status' => $new_status, 'updated_at' => date('Y-m-d H:i:s')])
        ->update([
            'ID' => $product->ID,
        ]);

    return $updated;
}


function salesloo_delete_product($product)
{
    global $salesloo_product;

    $product = salesloo_get_product($product);

    if (false === $product) return $product;

    $deleted = Salesloo\Models\Product::delete(['ID' => $product->ID]);

    if ($deleted) {
        Salesloo\Models\Product_Meta::delete(['product_id' => $product->ID]);
        $salesloo_product = '';
    }

    return $deleted;
}


/**
 * salesloo get product
 *
 * @param  mixed $product
 * @return mixed
 */
function salesloo_get_product($product = null)
{
    if (is_object($product) && isset($product->ID)) :
        $product_id = intval($product->ID);
    elseif (is_array($product) && isset($product['ID'])) :
        $product_id = intval($product['ID']);
    elseif (is_int($product) || is_string($product)) :
        $product_id = intval($product);
    else :
        return false;
    endif;

    $product = Salesloo\Models\Product::query('WHERE ID = %d', $product_id)->first();

    if ($product->ID <= 0) return false;

    return $product;
}


function salesloo_get_product_by($key, $value)
{
    $key = sanitize_text_field($key);
    $value = sanitize_text_field($value);

    $product = Salesloo\Models\Product::query("WHERE $key = %s", $value)->first();

    return $product->ID > 0 ? $product : false;
}


function salesloo_get_product_attribute($product, $attribute)
{
    global $salesloo_product;

    if (is_object($product) && isset($product->ID)) :
        $product_id = intval($product->ID);
    elseif (is_array($product) && isset($product['ID'])) :
        $product_id = intval($product['ID']);
    elseif (is_int($product) || is_string($product)) :
        $product_id = intval($product);
    else :
        return false;
    endif;

    if (!isset($salesloo_product->ID) || isset($salesloo_product->ID) && $salesloo_product->ID == $product_id) {
        $salesloo_product = Salesloo\Models\Product::query('WHERE ID = %d', $product_id)->first();
    }

    return $salesloo_product->$attribute;
}

function salesloo_add_product_meta($product_id, $meta_key, $meta_value, $unique = false)
{

    if (!is_numeric($product_id) || !$meta_key || !$meta_value) {
        return false;
    }

    if ($unique == true) {
        $meta = Salesloo\Models\Product_Meta::query('WHERE product_id = %d AND meta_key = %s', $product_id, $meta_key)->get();

        if ($meta->meta_id > 0) {
            return false;
        }
    }

    $args = [
        'product_id' => intval($product_id),
        'meta_key' => wp_unslash($meta_key),
        'meta_value' => wp_unslash($meta_value)
    ];

    $product_meta_id = Salesloo\Models\Product_Meta::data($args)->create();

    return $product_meta_id;
}


function salesloo_update_product_meta($product_id, $meta_key, $meta_value)
{

    if (!is_numeric($product_id) || !$meta_key) {
        return false;
    }

    $args = [
        'product_id' => intval($product_id),
        'meta_key'   => wp_unslash($meta_key),
        'meta_value' => maybe_serialize($meta_value),
    ];

    /**
     * check if meta key is exists
     */
    $check_meta = Salesloo\Models\Product_Meta::query('WHERE product_id = %d AND meta_key = %s', $product_id, $meta_key)->first();

    /**
     * update if meta key exists otherwise insert new one.
     */
    if ($check_meta->meta_id > 0) {

        Salesloo\Models\Product_Meta::data($args)->update([
            'meta_id' => $check_meta->meta_id
        ]);
        $meta_id = $check_meta->meta_id;
    } else {
        $meta_id = Salesloo\Models\Product_Meta::data($args)->create();
    }

    return $meta_id;
}


function salesloo_delete_product_meta($product_id, $meta_key, $meta_value = '')
{

    if (!is_numeric($product_id) || !$meta_key) {
        return false;
    }

    $args = [
        'product_id' => intval($product_id),
        'meta_key' => wp_unslash($meta_key)
    ];

    if ($meta_value) {
        $args['meta_value'] = wp_unslash($meta_value);
    }

    return Salesloo\Models\Product_Meta::delete($args);
}

function salesloo_get_product_meta($product_id, $meta_key, $single = false)
{
    if (!is_numeric($product_id) || !$meta_key) {
        return false;
    }


    /**
     * check if meta key is exists
     */
    $query = Salesloo\Models\Product_Meta::query('WHERE product_id = %d AND meta_key = %s', $product_id, $meta_key);

    if ($single === false) {
        $meta = [];

        $all_meta = $query->get();
        if ($all_meta) {
            foreach ($all_meta as $key => $value) {
                $meta[] = maybe_unserialize($value->meta_value);
            }
        }

        return $meta;
    } else {

        $single_meta = $query->first();

        if ($single_meta)
            return maybe_unserialize($single_meta->meta_value);
    }

    return false;
}



/**
 * generate product slug
 *
 * @return string
 */
function salesloo_generate_product_slug()
{
    $slug = '';
    $loop = true;

    while ($loop == true) {
        $slug = substr(base_convert(sha1(uniqid(microtime(true))), 16, 36), 0, 7);
        $check = Salesloo\Models\Product::query('WHERE slug = %s', $slug)->first();

        if ($check->ID <= 0) {
            $loop = false;
        }
    }

    return $slug;
}

/**
 * produc duration
 *
 * @return array
 */
function salesloo_product_duration()
{
    $durations = [
        'onetime' => __('One Time', 'salesloo'),
        '1 year'  => __('Yearly', 'salesloo'),
        '6 month' => __('Per 6 Months', 'salesloo'),
        '4 month' => __('Per 4 Months', 'salesloo'),
        '3 month' => __('Per 3 Months', 'salesloo'),
        '1 month' => __('Per 1 Month', 'salesloo'),
        '1 week'  => __('Weekly', 'salesloo')
    ];

    return apply_filters('salesloo/product/durations', $durations);
}

/**
 * translate product duration
 *
 * @param  string $duration
 * @return string
 */
function salesloo_translate_product_duration($duration = null)
{
    $translate_duration = __('One Time', 'salesloo');
    $durations = salesloo_product_duration();

    if ($duration && isset($durations[$duration])) {
        $translate_duration = $durations[$duration];
    } else {
        $translate_duration = isset($durations['onetime']) ? $durations['onetime'] : false;
    }

    return apply_filters('salesloo/product/duration/translate', $translate_duration);
}

/**
 * get product statuses
 *
 * @param  string $status
 * @return mixed
 */
function salesloo_get_product_statuses($status = false)
{
    $statuses = [
        'draft'     => __('Draft', 'salesloo'),
        'active'    => __('Active', 'salesloo'),
        'inactive'  => __('Inactive', 'salesloo'),
    ];

    $statuses = apply_filters('salesloo/product/statuses', $statuses, $status);

    if ($status) {
        return isset($statuses[$status]) ? $statuses[$status] : false;
    }

    return $statuses;
}


/**
 * get product price by product id
 *
 * @param  int $product_id
 * @return string
 */
function salesloo_get_product_price($product_id)
{
    $price = salesloo_get_product_meta(intval($product_id), 'sale_price', true);

    if (false === $price || empty($price)) {
        $price = salesloo_get_product_meta(intval($product_id), 'regular_price', true);
    }

    return floatval($price);
}

/**
 * set protected page
 *
 * @return void
 */
function salesloo_set_product_protected_page($product_id, $items)
{
    global $wpdb;

    $results = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT * FROM $wpdb->postmeta WHERE meta_key = %s AND meta_value = %d",
            '__salesloo_protected',
            intval($product_id)
        )
    );

    if ($results) {
        foreach ($results as $result) {
            delete_post_meta($result->post_id, $result->meta_key, $result->meta_value);
        }
    }

    foreach ($items as $item_id) {
        add_post_meta(intval($item_id), '__salesloo_protected', intval($product_id));
    }

    do_action('salesloo/product/set/protected/page', $product_id, $items);
}

/**
 * get current product slug
 *
 * @return string
 */
function salesloo_get_current_product_slug()
{

    $vars = salesloo_vars();

    if (!isset($vars['__product'])) {
        return false;
    }

    return sanitize_text_field($vars['__product']);
}
