<?php

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

use Mtc\Shop\Item;
use Mtc\Shop\Item\Size;

$page_meta['title'] = 'Trade Pricing';

init_request_values([
    'action' => null,
    'search' => null,
    'page' => 1,
]);

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

// Handle bulk update
if ($_REQUEST['action'] === 'bulk_update' && !empty($_POST['items'])) {
    if (!CSRF::checkToken('b2b_bulk_pricing')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        $updatedCount = 0;

        foreach ($_POST['items'] as $itemId => $data) {
            $tradePrice = isset($data['trade_price']) && $data['trade_price'] !== '' ? (float) $data['trade_price'] : null;
            $tradeSalePrice = isset($data['trade_sale_price']) && $data['trade_sale_price'] !== '' ? (float) $data['trade_sale_price'] : null;

            Item::where('id', $itemId)->update([
                'trade_price' => $tradePrice,
                'trade_price_exvat' => $tradePrice,
                'trade_sale_price' => $tradeSalePrice,
                'trade_sale_price_exvat' => $tradeSalePrice,
            ]);

            // Update size-level prices if provided
            if (!empty($data['sizes'])) {
                foreach ($data['sizes'] as $sizeId => $sizeData) {
                    $sizeTradePrice = isset($sizeData['trade_price']) && $sizeData['trade_price'] !== '' ? (float) $sizeData['trade_price'] : null;
                    $sizeTradeSalePrice = isset($sizeData['trade_sale_price']) && $sizeData['trade_sale_price'] !== '' ? (float) $sizeData['trade_sale_price'] : null;

                    Size::where('id', $sizeId)->where('item_id', $itemId)->update([
                        'trade_price' => $sizeTradePrice,
                        'trade_price_exvat' => $sizeTradePrice,
                        'trade_sale_price' => $sizeTradeSalePrice,
                        'trade_sale_price_exvat' => $sizeTradeSalePrice,
                    ]);
                }
            }

            $updatedCount++;
        }

        $success = "{$updatedCount} product(s) updated successfully";
    }
}

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

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li class="end">Trade Pricing</li>
</ul>

<h1>Trade Pricing — Bulk Edit</h1>

<?php include __DIR__ . '/tabnav.php'; ?>

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

<form method="get" class="style">
    <fieldset class="show">
        <h1><a class="show el">Filter <i class="fa fa-caret-right"></i></a></h1>
        <div class="row">
            <label for="search">Search</label>
            <input type="text" name="search" id="search" class="text" value="<?= clean_page($_REQUEST['search'] ?? '') ?>" placeholder="Product name or SKU...">
        </div>
        <div class="row">
            <input type="submit" value="Search" class="btn">
            <a href="pricing.php" class="btn cancel">Reset</a>
        </div>
    </fieldset>
</form>

<?php
$query = Item::with('sizes')->where('hidden', 0);

if (!empty($_REQUEST['search'])) {
    $search = $_REQUEST['search'];
    $query->where(function ($q) use ($search) {
        $q->where('name', 'like', "%{$search}%")
          ->orWhere('epos_code', 'like', "%{$search}%");
    });
}

$items = $query->orderBy('name', 'asc')->paginate(50);
$items->appends($_GET);
?>

<?php if ($items->total() > 0) { ?>
<form method="post" action="?action=bulk_update">
    <?= CSRF::token('b2b_bulk_pricing') ?>
    <p>
        <button type="submit" class="btn">Update Selected</button>
        <span>All prices are ex. VAT</span>
    </p>

    <table class="manage-items">
        <thead>
            <tr>
                <th><input type="checkbox" id="selectAll"></th>
                <th>Product</th>
                <th>SKU</th>
                <th>Retail Price</th>
                <th>Trade Price (&pound;)</th>
                <th>Trade Sale Price (&pound;)</th>
            </tr>
        </thead>
        <tbody class="tabular">
            <?php foreach ($items as $item) { ?>
            <tr class="product-row">
                <td><input type="checkbox" class="item-checkbox" data-item-id="<?= $item->id ?>"></td>
                <td>
                    <a href="/modules/B2B/admin/item-trade-pricing.php?id=<?= $item->id ?>"><?= clean_page($item->name) ?></a>
                </td>
                <td><?= clean_page($item->epos_code) ?></td>
                <td>&pound;<?= number_format($item->price, 2) ?></td>
                <td>
                    <input type="text" name="items[<?= $item->id ?>][trade_price]" class="short" value="<?= $item->trade_price !== null ? sprintf('%01.2f', $item->trade_price) : '' ?>" placeholder="—" disabled>
                </td>
                <td>
                    <input type="text" name="items[<?= $item->id ?>][trade_sale_price]" class="short" value="<?= $item->trade_sale_price !== null ? sprintf('%01.2f', $item->trade_sale_price) : '' ?>" placeholder="—" disabled>
                </td>
            </tr>
            <?php if ($item->sizes->count() > 0) { ?>
                <?php foreach ($item->sizes as $size) { ?>
                <tr class="size-row">
                    <td></td>
                    <td>↳ <?= clean_page($size->size) ?></td>
                    <td></td>
                    <td>&pound;<?= number_format($size->price, 2) ?></td>
                    <td>
                        <input type="text" name="items[<?= $item->id ?>][sizes][<?= $size->id ?>][trade_price]" class="short" value="<?= $size->trade_price !== null ? sprintf('%01.2f', $size->trade_price) : '' ?>" placeholder="—" disabled>
                    </td>
                    <td>
                        <input type="text" name="items[<?= $item->id ?>][sizes][<?= $size->id ?>][trade_sale_price]" class="short" value="<?= $size->trade_sale_price !== null ? sprintf('%01.2f', $size->trade_sale_price) : '' ?>" placeholder="—" disabled>
                    </td>
                </tr>
                <?php } ?>
            <?php } ?>
            <?php } ?>
        </tbody>
    </table>

    <p>
        <button type="submit" class="btn">Update Selected</button>
    </p>
</form>

<?= $items->render() ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const selectAll = document.getElementById('selectAll');
    const checkboxes = document.querySelectorAll('.item-checkbox');

    selectAll.addEventListener('change', function() {
        checkboxes.forEach(function(cb) {
            cb.checked = selectAll.checked;
            toggleItemInputs(cb);
        });
    });

    checkboxes.forEach(function(cb) {
        cb.addEventListener('change', function() {
            toggleItemInputs(cb);
        });
    });

    function toggleItemInputs(checkbox) {
        const itemId = checkbox.dataset.itemId;
        const row = checkbox.closest('tr');
        const inputs = row.querySelectorAll('input[type="text"]');
        inputs.forEach(function(input) {
            input.disabled = !checkbox.checked;
        });

        // Also toggle size rows for this item
        let nextRow = row.nextElementSibling;
        while (nextRow && nextRow.classList.contains('size-row')) {
            const sizeInputs = nextRow.querySelectorAll('input[type="text"]');
            sizeInputs.forEach(function(input) {
                input.disabled = !checkbox.checked;
            });
            nextRow = nextRow.nextElementSibling;
        }
    }
});
</script>

<?php } else { ?>
    <p>No products found.</p>
<?php } ?>

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