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

/**
 * Anbaarak | Best Inventory management plugin for WooCommerce.
 * All rights reserved for WP LEGEND team (wplegend.ir)
 */


use \Anbarak\ProductsInfo;
use Anbarak\Tables;
use Anbarak\VersionChecker;


/**
 *  Create consult item in database
 */
function anbarak_register_order()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access();

    global $wpdb;
    $customer = [];
    $name = '';
    $lname = '';
    $email = '';
    $phone = '';

    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Each product field is sanitized below after unslashing the posted array.
    $products_raw = isset($_POST['products']) && is_array($_POST['products']) ? wp_unslash($_POST['products']) : [];
    $products = [];
    foreach ($products_raw as $product) {
        if (!is_array($product)) {
            continue;
        }

        $products[] = [
            'id'        => isset($product['id']) ? (int) $product['id'] : 0,
            'qty'       => isset($product['qty']) ? (int) $product['qty'] : 0,
            'price'     => isset($product['price']) ? anbarak_sanitize_price(sanitize_text_field($product['price'])) : 0,
        ];
    }
    $discount = isset($_POST['discount']) ? sanitize_text_field(wp_unslash($_POST['discount'])) : '';
    $create_user = isset($_POST['create_user']) ? (int) sanitize_text_field(wp_unslash($_POST['create_user'])) : 0;

    if ($name = anbarak_post_param('buyer_name')) {
        $customer['name'] = $name;
    }

    $customer['last_name'] = '';
    if ($lname = anbarak_post_param('buyer_last_name')) {
        $customer['last_name'] = $lname;
    }

    $lname = anbarak_post_param('buyer_last_name');

    $customer['address'] = anbarak_post_param('buyer_address');
    $customer['province'] = anbarak_post_param('buyer_province');
    $customer['country'] = anbarak_post_param('buyer_country');

    if ($email = anbarak_post_param('buyer_email')) {
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $customer['email'] = $email;
        }
    }

    if ($phone = anbarak_post_param('buyer_phone')) {
        $customer['phone'] = anbarak_normalize_phone($phone) ?: $phone;
    }

    $buyer_user_id = isset($_POST['buyer_user_id']) ? (int) sanitize_text_field(wp_unslash($_POST['buyer_user_id'])) : 0;
    if ($buyer_user_id && $phone) {
        $selected_customer = anbarak_get_user_customer_data($buyer_user_id);
        $selected_phone = !empty($selected_customer['phone']) ? anbarak_normalize_phone($selected_customer['phone']) : false;
        $posted_phone = anbarak_normalize_phone($phone);

        if ($selected_customer && $selected_phone && $posted_phone && $selected_phone === $posted_phone) {
            $customer['user_id'] = $buyer_user_id;
        }
    }

    if ($postal = anbarak_post_param('buyer_postal')) {
        $customer['postal'] = $postal;
    }

    if ($customer_notes = anbarak_post_param('customer_notes')) {
        $customer_notes = $customer_notes;
    }

    if ($create_user) {
        setcookie('anbaarak_opt_sell_create_user', 'on', time() + (20 * 365 * 24 * 60 * 60));
    } else {
        setcookie('anbaarak_opt_sell_create_user', '', 0);
    }

    if ($create_user && $phone && empty($customer['user_id'])) {
        $phone = anbarak_normalize_phone($phone);
        if (!$phone) {
            wp_send_json_error([
                'message' => esc_html__('Please enter a valid phone number.', 'anbarak'),
            ], 400);
        }

        $user_id = username_exists($phone);
        if (!$user_id) {
            $userdata = array(
                'user_login'  =>  $phone,
                'user_pass'   =>  wp_generate_password(),
                'user_email'  =>  $email,
                'first_name'  =>  $name,
                'last_name'   =>  $lname,
                'role'        =>  'customer'
            );
            $user_id = wp_insert_user($userdata);
            if (is_wp_error($user_id)) {
                wp_send_json_error([
                    'message' => esc_html__('Could not create customer account.', 'anbarak'),
                ], 500);
            }
        }
        $customer['user_id'] = $user_id;
        $customer['first_name'] = get_user_meta($user_id, 'first_name', true);
        $customer['last_name'] = get_user_meta($user_id, 'last_name', true);
    }

    try {

        $order = anbarak_add_order($products, $customer, $discount, $customer_notes);

        // add order id to the anbarak database
        // seems OK. insert the data.
        $wpdb->insert(
            $wpdb->prefix . Tables::ORDERS,
            array(
                'orderid'     => $order->get_id(),
                'time'        => time(),
            )
        );

        wp_send_json([
            'message' => 'order created.',
        ]);
    } catch (\Throwable $th) {
        wp_send_json_error([
            'message' => esc_html__('An error occurred while creating the order.', 'anbarak'),
        ], 500);
    }
}
add_action('wp_ajax_anbarak_register_order', 'anbarak_register_order');

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

    $q = anbarak_get_param('q');
    $normalized = anbarak_normalize_phone($q);

    if (strlen($q) < 2 && (!$normalized || strlen($normalized) < 2)) {
        wp_send_json_success([]);
    }

    $terms = array_filter(array_unique([$q, $normalized ? $normalized : '']));
    $users = [];

    foreach ($terms as $term) {
        $found_users = get_users([
            'number'     => 10,
            'fields'     => 'all',
            'meta_query' => [
                [
                    'key'     => 'billing_phone',
                    'value'   => $term,
                    'compare' => 'LIKE',
                ],
            ],
        ]);

        foreach ($found_users as $user) {
            $users[$user->ID] = $user;
        }
    }

    $login_users = get_users([
        'number'         => 10,
        'fields'         => 'all',
        'search'         => '*' . esc_attr($q) . '*',
        'search_columns' => ['user_login'],
    ]);

    foreach ($login_users as $user) {
        $users[$user->ID] = $user;
    }

    $results = [];
    foreach ($users as $user) {
        if (count($results) >= 10) {
            break;
        }

        $customer = anbarak_get_user_customer_data($user->ID);
        if (empty($customer['phone'])) {
            continue;
        }

        $display_name = trim($customer['first_name'] . ' ' . $customer['last_name']);
        if ('' === $display_name) {
            $display_name = $user->display_name;
        }

        $label = $customer['phone'];
        if ('' !== $display_name) {
            $label .= ' - ' . $display_name;
        }

        $results[] = [
            'id'         => (int) $customer['user_id'],
            'value'      => $customer['phone'],
            'phone'      => $customer['phone'],
            'label'      => $label,
            'name'       => $display_name,
            'first_name' => $customer['first_name'],
            'last_name'  => $customer['last_name'],
            'email'      => $customer['email'],
            'country'    => $customer['country'],
            'province'   => $customer['province'],
            'address'    => $customer['address'],
            'postal'     => $customer['postal'],
        ];
    }

    wp_send_json_success($results);
}
add_action('wp_ajax_anbarak_search_customers_by_phone', 'anbarak_ajax_search_customers_by_phone');


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

    $id = isset($_GET['id']) ? (int) sanitize_text_field(wp_unslash($_GET['id'])) : 0;
    $_product = wc_get_product($id);
    if (!$_product) {
        wp_send_json_error(['message' => esc_html__('Product not found.', 'anbarak')], 404);
    }
    $vars = anbarak_get_variation_attributes($_product);
    $sku = get_post_meta($_product->get_id(), '_sku', true);

    wp_send_json([
        'id' => $_product->get_id(),
        'sku' => $sku,
        'vars_html' => $vars,
        'title' => $_product->get_title(),
        'unit_price' => $_product->get_price(),
    ]);
}
add_action('wp_ajax_anbarak_get_new_order_product_json', 'anbarak_ajax_get_new_order_product_json');


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

    $loop = anbarak_get_products(
        anbarak_get_param('q'),
        'p-sku' === anbarak_get_param('t') ? 'sku' : 'title'
    );

    if (!$loop->have_posts()) {
        wp_die();
    }

    while ($loop->have_posts()) {
        $loop->the_post();
        $id = get_the_ID();
        $product = wc_get_product($id);
        $sku = get_post_meta($product->get_id(), '_sku', true);
        $vars = anbarak_get_variation_attributes($product);
        $stock = $product->get_stock_quantity();
?>
        <li
            class="product text-sm flex items-center px-5"
            data-id="<?php echo (int) $product->get_id() ?>"
            data-sku="<?php echo esc_attr($sku) ?>"
            data-unit-price="<?php echo esc_attr($product->get_price()) ?>"
            data-qty="1"
            data-stock="<?php echo esc_attr($stock) ?>"
            >
            <div class="img me-2"><?php echo wp_kses_post(woocommerce_get_product_thumbnail()) ?></div>
            <div class="name px-3">
                <span class="title">
                    <?php echo esc_html($product->get_title()) ?>
                </span>
                <?php if ($vars) : ?>
                    <bdi><small class="vars">(<?php echo esc_html($vars) ?> )</small></bdi>
                <?php endif ?>
            </div>
            <div class="stock flex-grow mx-2 text-nowrap">
                <span class="label text-sm p-1">
                    <?php esc_html_e('Stock:', 'anbarak') ?>
                    <?php echo esc_html($stock) ?>
                </span>
            </div>
            <div class="price text-nowrap"><?php echo wp_kses_post(wc_price($product->get_price())) ?></div>
        </li>
    <?php
    }
    wp_reset_postdata();
    wp_die() ?>
    </tbody>
    </table>
<?php
}
add_action('wp_ajax_anbarak_new_order_product_search', 'anbarak_ajax_new_order_product_search');


function anbarak_ajax_get_page_content()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access(false);
    $page = isset($_GET['page']) ? sanitize_text_field(wp_unslash($_GET['page'])) : '';
    $page = $page ?: 'inventory';
    if (!anbarak_user_can_access_tab($page)) {
        wp_die('', '', array('response' => 403));
    }

    anbarak_render_page_content($page);
    exit;
}
add_action('wp_ajax_anbarak_get_page_content', 'anbarak_ajax_get_page_content');


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

    $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'
                )
            );
        }
    }

    // Category filter
    $category_id = anbarak_get_param('category');
    if (!empty($category_id) && is_numeric($category_id)) {
        $args['tax_query'][] = array(
            'taxonomy' => 'product_cat',
            'field' => 'term_id',
            'terms' => intval($category_id),
            'include_children' => true
        );
    }

    if (isset($_GET['group-variables'])) {
        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']) && 'true' === sanitize_text_field(wp_unslash($_COOKIE['anbarak_group_variables']))) {
            $args['group_variables'] = true;
        }
    }

    if ($ipp = anbarak_get_param('ipp')) {
        $args['posts_per_page']  = $ipp;
        setcookie('anbarak_ipp', $ipp, time() + (20 * 365 * 24 * 60 * 60));
    }

    if ($page = anbarak_get_param('paged')) {
        $args['paged']  = $page;
    }

    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;
        }
    }

    anbarak_render_products_table_items($args);
    exit;
}
add_action('wp_ajax_anbarak_product_search', 'anbarak_product_search');

function anbarak_columns_save()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_app_access(false);

    // Define all available columns with their default state (true = active, false = inactive)
    $available_columns = [
        'sku'           => true,
        'weight'        => false,
        'online_sell'   => true,
        'backorders'    => false,
        'last_buy_price' => true,
        'sale_price'    => true,
        'submit_buy'    => false,
        'submit_sell'   => false,
    ];

    // Get posted column states and merge with defaults
    $column_states = [];
    foreach ($available_columns as $col => $default) {
        // Check if column was posted (checkbox is checked) - adjust based on your input naming
        $is_active = isset($_POST['col_' . $col]) && 'on' === sanitize_text_field(wp_unslash($_POST['col_' . $col]));
        $column_states[$col] = $is_active;
    }

    // Encode to JSON and save in single cookie
    $cookie_value = wp_json_encode($column_states);
    setcookie('anbarak_columns', $cookie_value, time() + (20 * 365 * 24 * 60 * 60), '/');

    exit;
}
add_action('wp_ajax_anbarak_columns_save', 'anbarak_columns_save');

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

    $pid = isset($_POST['pid']) ? (int) sanitize_text_field(wp_unslash($_POST['pid'])) : 0;
    echo esc_html(anbarak_get_product_latest_buy_price($pid) ?? 'N/A');
    exit;
}
add_action('wp_ajax_anbarak_get_product_latest_buy_price', 'anbarak_ajax_get_product_latest_buy_price');


// tags
function anbarak_ajax_get_expenses_tags()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access(false);

    echo wp_kses_post(anbarak_render_expenses_tags());
    exit;
}
add_action('wp_ajax_anbarak_get_expenses_tags', 'anbarak_ajax_get_expenses_tags');

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

    $name  = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
    $color = isset($_POST['color']) ? (sanitize_hex_color(wp_unslash($_POST['color'])) ?: '#202020') : '#202020';

    if (!$name) {
        wp_send_json_error(['message' => esc_html__('Tag name is required.', 'anbarak')]);
    }

    $id = anbarak_define_expenses_tag($name, $color);
    if ($id) {
        wp_send_json_success([
            'id'    => $id,
            'name'  => $name,
            'color' => $color,
        ]);
    }
    wp_send_json_error(['message' => esc_html__('Failed to create tag.', 'anbarak')]);
}
add_action('wp_ajax_anbarak_define_expenses_tag', 'anbarak_ajax_define_expenses_tag');

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

    $id  = isset($_POST['id']) ? (int) sanitize_text_field(wp_unslash($_POST['id'])) : 0;
    if (!$id) {
        wp_send_json_error(['message' => esc_html__('Invalid tag ID.', 'anbarak')]);
    }
    $result = anbarak_remove_expense_tag($id);
    if ($result === false) {
        wp_send_json_error(['message' => esc_html__('Cannot delete the system purchase tag.', 'anbarak')]);
    }
    wp_send_json_success();
}
add_action('wp_ajax_anbarak_remove_expenses_tag', 'anbarak_ajax_remove_expenses_tag');

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

    $id    = isset($_POST['id']) ? (int) sanitize_text_field(wp_unslash($_POST['id'])) : 0;
    $name  = isset($_POST['name']) ? sanitize_text_field(wp_unslash($_POST['name'])) : '';
    $color = isset($_POST['color']) ? (sanitize_hex_color(wp_unslash($_POST['color'])) ?: '#202020') : '#202020';

    if (!$id || !$name) {
        wp_send_json_error(['message' => esc_html__('Invalid data.', 'anbarak')]);
    }

    $result = anbarak_update_expenses_tag($id, $name, $color);
    if ($result) {
        wp_send_json_success([
            'id'    => $id,
            'name'  => $name,
            'color' => $color,
        ]);
    }
    wp_send_json_error(['message' => esc_html__('Failed to update tag.', 'anbarak')]);
}
add_action('wp_ajax_anbarak_edit_expenses_tag', 'anbarak_ajax_edit_expenses_tag');

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

    $id  = isset($_GET['id']) ? (int) sanitize_text_field(wp_unslash($_GET['id'])) : 0;
    if (!$id) return false;

    global $wpdb;
    $expenses_table = $wpdb->prefix . Tables::EXPENSES;
    // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table name is fixed from $wpdb->prefix and Tables.
    $data =  $wpdb->get_row($wpdb->prepare("
        SELECT * 
        FROM {$expenses_table} 
        WHERE id=%d
        ORDER BY ID DESC
    ", (int) $id));
    // phpcs:enable

    $data->price = anbarak_format_price($data->price);
    $data->buy_discount = anbarak_format_price($data->buy_discount);
    $data->tax_rate = anbarak_format_price($data->tax_rate);


    return wp_send_json($data);
}
add_action('wp_ajax_anbarak_get_expense_json', 'anbarak_ajax_get_expense_json');


function anbarak_ajax_register_expense()
{

    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access();

    global $wpdb;

    $notes          = isset($_POST['notes']) ? sanitize_textarea_field(wp_unslash($_POST['notes'])) : '';
    $tag_id         = isset($_POST['tag']) ? (int) sanitize_text_field(wp_unslash($_POST['tag'])) : 0;
    $price          = isset($_POST['price']) ? anbarak_sanitize_price(sanitize_text_field(wp_unslash($_POST['price']))) : 0;
    $buy_tax        = isset($_POST['buy_tax']) ? anbarak_sanitize_price(sanitize_text_field(wp_unslash($_POST['buy_tax']))) : 0;
    $buy_discount   = isset($_POST['buy_discount']) ? anbarak_sanitize_price(sanitize_text_field(wp_unslash($_POST['buy_discount']))) : 0;
    $invoice_number = isset($_POST['invoice_number']) ? sanitize_text_field(wp_unslash($_POST['invoice_number'])) : '';
    $party_raw      = isset($_POST['party']) ? sanitize_text_field(wp_unslash($_POST['party'])) : '';
    $party          = $party_raw ? (int) $party_raw : null;
    $payment_method = isset($_POST['payment_method']) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '';
    $date           = anbarak_timestamp_param('date', time(), 'post');

    if (!$price || !$notes) {
        return false;
    }

    if (!$tag_id) {
        wp_send_json_error([
            'message' => esc_html__('Please select an expense tag.', 'anbarak'),
        ], 400);
    }

    // add purchase details to expense
    $wpdb->insert(
        $wpdb->prefix . Tables::EXPENSES,
        array(
            'price'          => $price,
            'notes'          => $notes,
            'timestamp'      => $date,
            'tag_id'         => $tag_id,
            'tax_rate'       => $buy_tax,
            'buy_discount'   => $buy_discount,
            'invoice_number' => $invoice_number,
            'payment_method' => $payment_method,
            'party_id'          => $party,
        )
    );

    $expense = anbarak_get_expense_details($wpdb->insert_id);
    anbarak_render_expense_table_item($expense, true);
    exit;
}
add_action('wp_ajax_anbarak_register_expense', 'anbarak_ajax_register_expense');


function anbarak_ajax_delete_expense()
{

    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access();

    $eid = isset($_POST['eid']) ? (int) sanitize_text_field(wp_unslash($_POST['eid'])) : 0;
    if (!$eid) return;
    global $wpdb;

    $result = $wpdb->delete(
        $wpdb->prefix . Tables::EXPENSES,
        array('id' => $eid),
        array('%d')
    );

    if ($result) {
        wp_send_json_success();
    } else {
        wp_send_json_error();
    }
}
add_action('wp_ajax_anbarak_delete_expense', 'anbarak_ajax_delete_expense');


function anbarak_ajax_edit_expense()
{

    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access();

    $id = isset($_POST['id']) ? (int) sanitize_text_field(wp_unslash($_POST['id'])) : 0;
    if (!$id) return;
    global $wpdb;

    $notes          = isset($_POST['notes']) ? sanitize_textarea_field(wp_unslash($_POST['notes'])) : '';
    $tag_id         = isset($_POST['tag']) ? (int) sanitize_text_field(wp_unslash($_POST['tag'])) : 0;
    $price          = isset($_POST['price']) ? anbarak_sanitize_price(sanitize_text_field(wp_unslash($_POST['price']))) : 0;
    $buy_tax        = isset($_POST['buy_tax']) ? anbarak_sanitize_price(sanitize_text_field(wp_unslash($_POST['buy_tax']))) : 0;
    $buy_discount   = isset($_POST['buy_discount']) ? anbarak_sanitize_price(sanitize_text_field(wp_unslash($_POST['buy_discount']))) : 0;
    $invoice_number = isset($_POST['invoice_number']) ? sanitize_text_field(wp_unslash($_POST['invoice_number'])) : '';
    $payment_method = isset($_POST['payment_method']) ? sanitize_text_field(wp_unslash($_POST['payment_method'])) : '';
    $timestamp      = anbarak_timestamp_param('date', time(), 'post');

    $buy_tax = $buy_tax > 0 ? $buy_tax : NULL;
    $buy_discount = $buy_discount > 0 ? $buy_discount : NULL;

    $data = [
        'price'          => $price,
        'notes'          => $notes,
        'tag_id'         => $tag_id,
        'timestamp'      => $timestamp,
        'tax_rate'       => $buy_tax,
        'buy_discount'   => $buy_discount,
        'invoice_number' => $invoice_number,
        'payment_method' => $payment_method,
    ];

    $wpdb->update(
        $wpdb->prefix . Tables::EXPENSES,
        $data,
        ['id' => $id]
    );

    $expense = anbarak_get_expense_details($id);
    anbarak_render_expense_table_item($expense);
    exit;
}
add_action('wp_ajax_anbarak_edit_expense', 'anbarak_ajax_edit_expense');


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

    $date_from = anbarak_timestamp_param('date-from', strtotime('-1 month'), 'get');
    $date_to = anbarak_timestamp_param('date-to', time(), 'get');

    anbarak_render_expenses_distribution_stats($date_from, $date_to);
    wp_die();
}
add_action('wp_ajax_anbarak_get_expenses_stats', 'anbarak_ajax_get_expenses_stats');



function anbarak_ajax_get_report_stats()
{
    check_ajax_referer('anbarak-ajax-nonce', 'security');
    anbarak_require_ajax_admin_access(false);
    $date_from = anbarak_timestamp_param('date-from', strtotime('-1 month'), 'get');
    $date_to   = anbarak_timestamp_param('date-to', time(), 'get');

    anbarak_render_filtered_stats($date_from, $date_to);
    wp_die();
}
add_action('wp_ajax_anbarak_get_report_stats', 'anbarak_ajax_get_report_stats');
