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

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


use Anbarak\Tables;

/**
 * Calculate total buy cost for given quantity using FIFO
 * 
 * @param int $product_id
 * @param int $requested_qty
 * @return float Total cost
 */
function anbarak_get_expenses_for_product_qty_fifo(int $product_id, int $requested_qty)
{
    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.
    $purchases = $wpdb->get_results(
        $wpdb->prepare(
            "SELECT 
                id, 
                qty, 
                price, 
                (price/qty) AS unit_price,
                GREATEST(0, qty - IFNULL(consumed_qty, 0)) AS available_qty
             FROM {$expenses_table}
             WHERE product_id = %d 
               AND deleted_at IS NULL
               AND qty > IFNULL(consumed_qty, 0)
             ORDER BY timestamp ASC",
            $product_id
        )
    );
    // phpcs:enable

    $remaining_qty = $requested_qty;
    $total_cost = 0;

    $affected_purchases = [];

    foreach ($purchases as $purchase) {
        if ($remaining_qty <= 0) break;
        $qty_used = min($purchase->available_qty, $remaining_qty);
        $total_cost += $qty_used * $purchase->unit_price;
        $remaining_qty -= $qty_used;
        $affected_purchases[$purchase->id] = [
            'id' => $purchase->id,
            'qty' => $purchase->qty,
            'unit_price' => $purchase->unit_price,
            'avail_qty' => $qty_used,
            'total_avail_price' => $qty_used * $purchase->unit_price
        ];
    }

    return [
        'total_cost' => $total_cost,
        'used_expenses' => $affected_purchases,
        'remaining_qty' => $remaining_qty
    ];
}

/**
 * Calculate total buy cost for given quantity using FIFO
 * 
 * @param int $product_id
 * @param int $requested_qty
 * @return float Total cost
 */
function anbarak_get_total_buy_cost($product_id, $requested_qty)
{
    $expenses = anbarak_get_expenses_for_product_qty_fifo($product_id, $requested_qty);
    if (is_array($expenses)) {
        return $expenses['total_cost'];
    }
    return false;
}


function anbarak_get_expense_details($id)
{
    global $wpdb;
    $expenses_table = $wpdb->prefix . Tables::EXPENSES;
    $tags_table = $wpdb->prefix . Tables::EXPENSES_TAGS;
    // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter -- Custom table names are fixed from $wpdb->prefix and Tables.
    $expense = $wpdb->get_row($wpdb->prepare("
        SELECT 
            ex.*, 
            t.name as tag_name,
            t.color as tag_color
        FROM {$expenses_table} ex
        LEFT JOIN {$tags_table} t ON ex.tag_id = t.id
        WHERE ex.deleted_at IS NULL AND ex.id=%d
    ", (int) $id));
    // phpcs:enable

    return $expense ?: false;
}

function anbarak_render_expense_table_item($expense, $includeTr = false)
{
    $product = null;
    $thumbnail_url = null;
    if ($expense->product_id) {
        $product = wc_get_product($expense->product_id);
        if ($product) {
            $thumbnail_url = get_the_post_thumbnail_url($product->get_id(), 'thumbnail');

            if (!$thumbnail_url && $product->get_parent_id()) {
                $product = wc_get_product($product->get_parent_id());
                $thumbnail_url = get_the_post_thumbnail_url($product->get_id(), 'thumbnail');
            }
        }
    }

?>
    <?php if ($includeTr): ?>
        <tr id="expense-<?php echo (int) $expense->id ?>">
        <?php endif ?>
        <td class="note min-w-90">
            <?php if ($expense->product_id && $product) : ?>
                <img width="40px" class="inline rounded me-2 align-middle" src="<?php echo  esc_url($thumbnail_url) ?>">
                <a href="<?php echo esc_url(get_permalink($product->get_id())) ?>">
                    <?php echo esc_html($expense->notes) ?>
                </a>
            <?php else : ?>
                <?php echo esc_html($expense->notes) ?>
            <?php endif ?>
            <?php if ($expense->product_id && !$product) : ?>
                <div class="label"><?php esc_html_e('Product not found!', 'anbarak') ?></div>
            <?php endif ?>

        </td>
        <td class="sku"><?php echo $product ? (mb_strlen($product->get_sku()) ? esc_html($product->get_sku()) : '-') : '-' ?></td>
        <td class="product"><?php echo $product ? (int) $product->get_id() : '-' ?></td>
        <td>
            <span class="tag text-white pt-1 pb-1 ps-2 pe-2 rounded-2xl inline-block whitespace-nowrap" style="background-color: <?php echo esc_attr($expense->tag_color ?? '#777') ?>">
                <?php echo esc_html($expense->tag_name ?? esc_html__('No tag', 'anbarak')) ?>
            </span>
        </td>
        <td class="date whitespace-nowrap">
            <?php echo esc_html(anbarak_datetime($expense->timestamp)) ?>
        </td>
        <td class="price"><?php echo wp_kses_post(wc_price($expense->price)) ?></td>
        <td class="actions flex">
            <button class="button btn-edit-expense me-2" data-expense-id="<?php echo (int) $expense->id ?>"><i class="icon icon-edit me-1"></i><?php esc_html_e('Edit', 'anbarak'); ?></button>
            <form action="" method="POST">
                <?php anbarak_nonce() ?>
                <input type="hidden" name="action" value="anbarak_delete_expense">
                <input type="hidden" name="eid" value="<?php echo (int) $expense->id ?>">
                <button class="button button--danger-outline btn-delete-expense"><i class="icon icon-bin1"></i> <?php esc_html_e('Delete', 'anbarak'); ?></button>
            </form>
        </td>
        <?php if ($includeTr): ?>
        </tr>
    <?php endif ?>
<?php
}
