<?php

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

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

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

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

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

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

$item = Item::with('sizes')->find($_REQUEST['id']);

if (!$item) {
    header('Location: /shop/admin/products/manage.products.php');
    exit;
}

// Handle save
if ($_REQUEST['action'] === 'save') {
    // Save item-level trade prices
    $tradePrice = $_POST['trade_price'] !== '' ? (float) $_POST['trade_price'] : null;
    $tradeSalePrice = $_POST['trade_sale_price'] !== '' ? (float) $_POST['trade_sale_price'] : null;

    // Trade prices are stored ex-VAT (B2B convention)
    $tradePriceExvat = $tradePrice;
    $tradeSalePriceExvat = $tradeSalePrice;

    $item->update([
        'trade_price' => $tradePrice,
        'trade_price_exvat' => $tradePriceExvat,
        'trade_sale_price' => $tradeSalePrice,
        'trade_sale_price_exvat' => $tradeSalePriceExvat,
    ]);

    // Save size-level trade prices
    if (!empty($_POST['size_trade_price'])) {
        foreach ($_POST['size_trade_price'] as $sizeId => $price) {
            $sizeTradePrice = $price !== '' ? (float) $price : null;
            $sizeTradeSalePrice = isset($_POST['size_trade_sale_price'][$sizeId]) && $_POST['size_trade_sale_price'][$sizeId] !== ''
                ? (float) $_POST['size_trade_sale_price'][$sizeId]
                : null;

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

    $success = 'Trade pricing updated successfully';
    $item->refresh();
    $item->load('sizes');
}

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

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

<h1>Trade Pricing: <?= clean_page($item->name) ?></h1>

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

<form method="post" action="?action=save&id=<?= $item->id ?>" class="style">
    <h2>Product-Level Trade Prices (ex. VAT)</h2>
    <div class="el msg alert">These prices apply when the product has no size variants, or as a fallback for sizes without their own trade price. <i class="fa fa-info-circle"></i></div>

    <div class="row">
        <label for="trade_price">Trade Price (&pound; ex. VAT)</label>
        <input type="text" id="trade_price" name="trade_price" class="short" value="<?= $item->trade_price !== null ? sprintf('%01.2f', $item->trade_price) : '' ?>" placeholder="Leave blank for retail only">
    </div>

    <div class="row">
        <label for="trade_sale_price">Trade Sale Price (&pound; ex. VAT)</label>
        <input type="text" id="trade_sale_price" name="trade_sale_price" class="short" value="<?= $item->trade_sale_price !== null ? sprintf('%01.2f', $item->trade_sale_price) : '' ?>" placeholder="Optional promotional price">
    </div>

    <?php if ($item->sizes->count() > 0) { ?>
        <h2>Size-Level Trade Prices (ex. VAT)</h2>
        <div class="el msg alert">Set trade prices per size variant. Sizes without a trade price will fall back to the product-level trade price above. <i class="fa fa-info-circle"></i></div>

        <table class="manage-items">
            <thead>
                <tr>
                    <th>Size / Variant</th>
                    <th>Retail Price</th>
                    <th>Trade Price (&pound; ex. VAT)</th>
                    <th>Trade Sale Price (&pound; ex. VAT)</th>
                </tr>
            </thead>
            <tbody class="tabular">
                <?php foreach ($item->sizes as $size) { ?>
                <tr>
                    <td><?= clean_page($size->size) ?></td>
                    <td>&pound;<?= number_format($size->price, 2) ?></td>
                    <td>
                        <input type="text" name="size_trade_price[<?= $size->id ?>]" class="short" value="<?= $size->trade_price !== null ? sprintf('%01.2f', $size->trade_price) : '' ?>" placeholder="Blank = use product price">
                    </td>
                    <td>
                        <input type="text" name="size_trade_sale_price[<?= $size->id ?>]" class="short" value="<?= $size->trade_sale_price !== null ? sprintf('%01.2f', $size->trade_sale_price) : '' ?>" placeholder="Optional">
                    </td>
                </tr>
                <?php } ?>
            </tbody>
        </table>
    <?php } ?>

    <div class="row">
        <button type="submit" class="btn">Save Trade Pricing</button>
    </div>
</form>

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