<?php

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

use Mtc\Plugins\Consumables\Models\ItemConsumable;

$page_meta['title'] = 'Item Consumables';

init_request_values([
    'action' => null,
    'id' => null,
]);

if (!is_numeric($_REQUEST['id'])) {
    header('Location: /shop/admin/products/manage.products.php');
    exit;
}

$item = new \Item();
$item->Get_Item($_REQUEST['id']);
if (!$item->id) {
    header('Location: /shop/admin/products/manage.products.php');
    exit;
}

$eloquentItem = \Mtc\Shop\Item::find($_REQUEST['id']);

$errors = [];
$success = '';

// Handle save
if ($_REQUEST['action'] === 'save') {
    $consumableIds = $_POST['consumable_item_id'] ?? [];
    $quantities = $_POST['consumable_quantity'] ?? [];

    \Illuminate\Support\Facades\DB::transaction(function () use ($eloquentItem, $consumableIds, $quantities) {
        // Clear existing consumables for this item
        ItemConsumable::where('item_id', $eloquentItem->id)->delete();

        // Save new consumable assignments
        foreach ($consumableIds as $index => $consumableId) {
            $consumableId = (int) $consumableId;
            $qty = (int) ($quantities[$index] ?? 1);

            if ($consumableId > 0 && $qty > 0) {
                // Prevent self-reference
                if ($consumableId === $eloquentItem->id) {
                    continue;
                }

                // Verify consumable item exists
                if (!\Mtc\Shop\Item::where('id', $consumableId)->exists()) {
                    continue;
                }

                ItemConsumable::updateOrCreate(
                    ['item_id' => $eloquentItem->id, 'consumable_item_id' => $consumableId],
                    ['quantity' => $qty]
                );
            }
        }
    });

    $success = 'Consumables updated successfully';
}

// Handle remove single
if ($_REQUEST['action'] === 'remove' && is_numeric($_REQUEST['consumable_id'])) {
    ItemConsumable::where('item_id', $eloquentItem->id)
        ->where('consumable_item_id', $_REQUEST['consumable_id'])
        ->delete();
    $success = 'Consumable removed';
}

// Load current consumables
$consumables = ItemConsumable::where('item_id', $eloquentItem->id)
    ->with('consumableItem')
    ->get();

require_once $path . 'core/admin/templates/adminheader.html.php';
?>

<?php include $path . 'shop/admin/products/tabnav.php'; ?>

<h1>Consumables for: <?= clean_page($item->name) ?></h1>

<?php
if (!empty($errors)) {
    showerrors($errors);
}
if (!empty($success)) {
    showmsg($success, 'success', $path);
}
?>

<p class="help" style="margin-bottom: 20px; color: #666;">
    Assign non-sellable consumables (e.g. mailer boxes, ice packs) to this product.
    When this product is sold, the linked consumable stock will be automatically decremented.
</p>

<?php if ($consumables->count() > 0) { ?>
<h2>Current Consumables</h2>
<table class="manage-items">
    <thead>
        <tr>
            <th>Consumable</th>
            <th>Stock</th>
            <th>Qty per Order</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody class="tabular">
        <?php foreach ($consumables as $c) { ?>
        <tr>
            <td>
                <?php if ($c->consumableItem) { ?>
                    <?= clean_page($c->consumableItem->name) ?>
                    <?php if ($c->consumableItem->hidden) { ?><span style="color: #999;">(hidden)</span><?php } ?>
                <?php } else { ?>
                    <em>Deleted item #<?= $c->consumable_item_id ?></em>
                <?php } ?>
            </td>
            <td>
                <?php if ($c->consumableItem) { ?>
                    <?= $c->consumableItem->stock ?>
                    <?php if ($c->consumableItem->stock <= ItemConsumable::lowStockThreshold()) { ?>
                        <span style="color: #c00; font-weight: bold;">Low</span>
                    <?php } ?>
                <?php } else { ?>
                    -
                <?php } ?>
            </td>
            <td><?= $c->quantity ?></td>
            <td>
                <a href="?id=<?= $item->id ?>&action=remove&consumable_id=<?= $c->consumable_item_id ?>"
                   class="btn btn-smaller delete"
                   onclick="return confirm('Remove this consumable?')">Remove</a>
            </td>
        </tr>
        <?php } ?>
    </tbody>
</table>
<?php } ?>

<h2>Add / Edit Consumables</h2>

<form action="" method="post" class="style consumablesForm" id="consumablesForm">
    <fieldset class="show">
        <h1><a class="show el">Consumable Assignments <i class="fa fa-caret-right"></i></a></h1>

        <div id="consumableRows">
            <?php
            $maxRows = max($consumables->count() + 3, 5);
            for ($i = 0; $i < $maxRows; $i++) {
                $existing = $consumables[$i] ?? null;
                $consumableId = $existing ? $existing->consumable_item_id : '';
                $consumableName = ($existing && $existing->consumableItem) ? clean_page($existing->consumableItem->name) : '';
                $qty = $existing ? $existing->quantity : 1;
            ?>
            <div class="row">
                <label for="consumable_<?= $i ?>_name">Consumable <?= $i + 1 ?></label>
                <input type="hidden"
                       name="consumable_item_id[<?= $i ?>]"
                       id="consumable_<?= $i ?>"
                       value="<?= $consumableId ?>"
                       class="INPUT1">
                <input type="text"
                       id="consumable_<?= $i ?>_name"
                       value="<?= $consumableName ?>"
                       class="INPUT1 short"
                       readonly>
                <a class="browseConsumable btn" data-id="<?= $i ?>">Browse</a>
                <a class="btn cancel clearConsumable" data-id="<?= $i ?>">Clear</a>
                <label style="margin-left: 10px;">Qty:</label>
                <input type="number"
                       name="consumable_quantity[<?= $i ?>]"
                       value="<?= $qty ?>"
                       min="1"
                       class="text"
                       style="width: 60px;">
            </div>
            <?php } ?>
        </div>
    </fieldset>

    <div class="row">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="id" value="<?= $item->id ?>">
        <button type="submit" class="btn" name="submit">Save Consumables</button>
    </div>
</form>

<script>
$(document).ready(function () {
    $('.consumablesForm').on('click', '.browseConsumable', function () {
        let url = '/shop/admin/products/manage.products.mini.php?';
        url += 'field=consumable_' + $(this).attr('data-id');
        window.open(
            url,
            'productselector',
            'status=yes,scrollbars=yes,resizable=yes,width=500,height=600'
        );
    });
    $('.consumablesForm').on('click', '.clearConsumable', function () {
        let id = $(this).attr('data-id');
        $('#consumable_' + id).val('');
        $('#consumable_' + id + '_name').val('');
    });
});
</script>

<?php require_once $path . 'core/admin/templates/adminfooter.html.php'; ?>
