<?php
/**
 * Upsells manage page
 *
 * Configure the manual upsell products offered for a given product in the
 * assessment "Complete your basket" overlay. Assessment-required products are
 * rejected on save (they can never be upsells) and flagged if a previously
 * saved upsell has since become assessment-required.
 */
namespace Mtc\Plugins\Upsells\Classes;

use Item;
use Util;
use Illuminate\Support\Facades\DB;

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

$page_meta['title'] = 'Upsells';

$upsells_max = (int) config('upsells.max_rows');

if (empty($_REQUEST['id']) || !config('upsells.enabled') || $upsells_max < 1) {
    header('Location: /shop/admin/products/');
    exit();
}

$item_id = (int)$_REQUEST['id'];
$item = new Item($item_id);

$rejected = [];

// ------------------------ POST-BACK --------------------------
if (!empty($_POST['action'])
    && $_POST['action'] == 'update_upsells'
    && !empty($_POST['upsells'])
) {
    $update_items = array_filter($_POST['upsells'], function ($id) {
        return !empty($id);
    });

    // Assessment-required products can never be upsells — drop them and report.
    $ineligible_ids = Upsells::assessmentRequiredIds($update_items);
    $accepted = [];
    foreach ($update_items as $order => $update_item) {
        if (in_array((int)$update_item, $ineligible_ids, true)) {
            $rejected[] = item_name($update_item);
            continue;
        }
        $accepted[$order] = $update_item;
    }

    // Replace the full set atomically so a mid-loop failure cannot wipe the
    // existing upsells without recreating them.
    DB::transaction(function () use ($item_id, $accepted) {
        Upsells::where('item_id', $item_id)
            ->delete();

        foreach ($accepted as $order => $update_item) {
            Upsells::create([
                'item_id' => $item_id,
                'upsell_item_id' => $update_item,
                'order' => $order
            ]);
        }
    });
    $success = true;
}

// --------------------- END OF POST-BACK ----------------------

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

<ul class="breadcrumbs el">
    <li>
        <a href="/admin/">
            Home
        </a> /
    </li>
    <li>
        <a href="/shop/admin/products/admin/">
            Manage Products
        </a> /
    </li>
    <li>
        <a href="/shop/admin/products/admin/item.php?id=<?= $item_id ?>">
            Edit Item
        </a> /
    </li>
    <li class="end">
        Manage Upsells
    </li>
</ul>
<h1>Manage Upsells</h1>
<?php
require $path . 'shop/admin/products/tabnav.php';
if (!empty($success)) {
    echo showmsg('Upsells updated', 'success', $path);
}
if (!empty($rejected)) {
    echo showmsg(
        'These products require an assessment and cannot be upsells, so were not saved: '
            . clean_page(implode(', ', $rejected)),
        'error',
        $path
    );
}
?>
<form action="<?= Util::add_query_arg(['id' => $item_id]) ?>"
      method="post"
      class="style upsells">
    <?php
    $upsells = Upsells::orderBy('order', 'ASC')
        ->where('item_id', $item_id)
        ->get();

    // Flag stored upsells that have since become assessment-required — they are
    // dropped from the live overlay until reconfigured. Resolved in one query.
    $ineligible_stored = Upsells::assessmentRequiredIds(
        $upsells->pluck('upsell_item_id')->all()
    );

    for ($i = 0; $i < $upsells_max; $i++) {
        $upsell_item_id = $upsells[$i]->upsell_item_id ?? null;
        $ineligible = !empty($upsell_item_id)
            && in_array((int)$upsell_item_id, $ineligible_stored, true);
        ?>
        <div class="row">
            <label for="upsell_<?= $i ?>_name">
                Item <?= $i + 1 ?>
            </label>
            <input type="hidden"
                   name="upsells[<?= $i ?>]"
                   id="upsell_<?= $i ?>"
                   value="<?= $upsell_item_id ?? '' ?>"
                   class="INPUT1"/>
            <input type="text"
                   id="upsell_<?= $i ?>_name"
                   value="<?= clean_page(item_name($upsell_item_id)) ?>"
                   class="INPUT1 short"/>
            <a class="browseUpsell btn" data-id="<?= $i ?>">
                Browse
            </a>
            <a class="btn cancel cancelUpsell" data-id="<?= $i ?>">
                Clear
            </a>
            <?php if ($ineligible) { ?>
                <span class="errorMsg">
                    Requires assessment — hidden from overlay
                </span>
            <?php } ?>
        </div>
        <?php
    }
    ?>
    <div class="row">
        <input type="hidden"
               name="action"
               value="update_upsells"/>
        <button type="submit"
                class="btn"
                name="submit">
            Save
        </button>
    </div>
</form>
<?php
require_once $path . 'core/admin/templates/adminfooter.html.php';
