<?php
if ( ! defined( 'ABSPATH' ) ) exit;

use Anbarak\ProductsInfo;
use Anbarak\Tables;
use Shuchkin\SimpleXLSXGen;

use OpenSpout\Writer\XLSX\Writer;
use OpenSpout\Common\Entity\Row;
use OpenSpout\Common\Entity\Style\Style;
use OpenSpout\Writer\Common\Creator\WriterEntityFactory;
use OpenSpout\Common\Entity\Style\CellAlignment;

function anbarak_export_product_search()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access(false);

    global $wpdb;

    $args = [];
    $args['meta_query'] = [];

    if ($q = anbarak_get_param('q')) {

        if ('p-name' === anbarak_get_param('t')) {
            $args['s']  = $q;
        }

        if ('p-sku' === anbarak_get_param('t')) {
            $args['meta_query'] = array(
                array(
                    'key' => '_sku',
                    'value' => $q,
                    'compare' => '='
                    // 'compare' => 'REGEXP'
                )
            );
        }

        if ('p-stock' === anbarak_get_param('t')) {
            $args['meta_query'] = array(
                array(
                    'key' => '_stock',
                    'value' => $q,
                    'compare' => '=',
                    'type' => 'NUMERIC'
                )
            );
        }
    }

    if (anbarak_get_param('group-variables') !== null) {
        if (anbarak_get_param('group-variables')) {
            $args['group_variables'] = true;
            setcookie('anbarak_group_variables', 'true', time() + (20 * 365 * 24 * 60 * 60), '/');
        } else {
            setcookie('anbarak_group_variables', '', time() - 3600, '/');
        }
    } else {
        if (!empty($_COOKIE['anbarak_group_variables']) && $_COOKIE['anbarak_group_variables'] === 'true') {
            $args['group_variables'] = true;
        }
    }

    if ($view = anbarak_get_param('view')) {
        switch ($view) {
            case 'all':
                array_push($args['meta_query'],  [
                    'key'     => '_stock',
                    'type'    => 'numeric',
                ]);

                break;
            case 'low-stock':
                $args['low-stock'] = true;
                break;

            case 'out-of-stock':
                $args['out-of-stock'] = true;
                break;
            case 'in-stock':
                $args['in-stock'] = true;
                break;

            default:
                # code...
                break;
        }
    }


    $productsInfo = ProductsInfo::getInstance();
    $excludedPosts = $productsInfo->getVariablesIds();

    $defaults = array(
        'post_status' => 'publish',
        'post_type'      => ['product', 'product_variation'],
        'post__not_in' => $excludedPosts,
        'posts_per_page' => '-1',
        'orderby' => [
            'post_date_gmt' => 'DESC',
            'parent' => 'DESC'
        ],
        'meta_query'    => []
    );

    $args = wp_parse_args($args, $defaults);

    $meta_query = $args['meta_query'];

    $meta_query[] = [
        'key'     => '_manage_stock',
        'value'   => 'yes',
    ];

    if (isset($args['group_variables'])) {
        $args['orderby'] = [
            'post_parent' => 'DESC',
            'post_date_gmt' => 'DESC'
        ];
    }

    if (isset($args['low-stock'])) {
        $meta_query[] = [
            'key'     => '_stock',
            'value'   => [1, ANBARAK_PRODUCTS_LOW_STOCK_THRESHOLD],
            'compare' => 'BETWEEN',
            'type'      => 'numeric'
        ];
    }

    if (isset($args['out-of-stock'])) {
        $meta_query[] = [
            'key' => '_stock',
            'value' => 0,
            'compare' => '<=',
            'type'      => 'numeric'
        ];
    }


    if (isset($args['in-stock'])) {
        $meta_query[] = [
            'key' => '_stock',
            'value' => 0,
            'compare' => '>',
            'type'      => 'numeric'
        ];
    }


    $args['meta_query'] = $meta_query;

    $loop = new WP_Query($args);

    // headers
    $headers = [
        __('ID', 'anbarak'),
        'SKU',
        __('Title', 'anbarak'),
        __('Last Buy Price', 'anbarak'),
        __('Sale Price', 'anbarak'),
        __('Special Sale Price', 'anbarak'),
        __('Stock', 'anbarak'),
    ];

    $rows = [];
    $rows[] = [__('Report Date:', 'anbarak') . ' ' . wp_strip_all_tags(anbarak_datetime(time()))];
    $rows[] = $headers;

    // data rows
    while ($loop->have_posts()) {
        $loop->the_post();
        $product = wc_get_product(get_the_ID());
        $last_buy = anbarak_get_product_latest_buy_price(get_the_ID());

        $rows[] = [
            $product->get_id(),
            $product->get_sku(),
            $product->get_name(),
            $last_buy,
            $product->get_regular_price(),
            $product->get_sale_price(),
            $product->get_stock_quantity(),
        ];
    }

    $xlsx = SimpleXLSXGen::fromArray($rows);

    $xlsx->mergeCells('A1:H1');

    if (is_rtl()) {
        $xlsx->rightToLeft();
    }

    $xlsx->freezePanes('A3');
    $xlsx->setDefaultFont('iransans')->setDefaultFontSize(11);

    $xlsx->setAuthor('Anbarak');
    // download file
    $xlsx->downloadAs(__('Anbarak Products', 'anbarak') . ' - ' . anbarak_date(time()) . '.xlsx');
    exit;
}
add_action('wp_ajax_anbarak_export_product_search', 'anbarak_export_product_search');
