<?php

use Mtc\Shop\ComparisonSite;
use Mtc\Shop\Item\Size;
use MtcPharmacy\QualifyingAnswers\Classes\QualifyingAnswersHelper;
use App\SizeRestriction;
use Illuminate\Support\Facades\Event;
use MtcPharmacy\Multisite\Classes\MultisiteManager;


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

init_request_values([
    'sizeid' => null,
    'form_id' => null,
    'stock' => null,
    'weight' => null,
]);

$page_meta['title'] = 'Manage Sizes';

$requested_item_id = (int)$_REQUEST['id'];
$requested_item = \Mtc\Shop\Item::find($_REQUEST['id']);
if ($requested_item) {
    $mm = new MultisiteManager($requested_item);
    $mm->ensureTheCorrectAdminPageLoaded();
}

$item = new Item();
$item->Get_Item($_REQUEST['id']);

$size_eloquent = (new \Mtc\Shop\Item\Size())->findOrNew($_REQUEST['sizeid']);

$custom_fields = \Mtc\Shop\Item\SizeCustom::getCustomFields();
$custom_data = (new \Mtc\Shop\Item\SizeCustom())->firstOrNew(['size_id' => $_REQUEST['sizeid']]);

$stock_updated = false;

if ($_REQUEST['action'] === 'update_prices') {
    $sizes = Size::query()
        ->where('item_id', $item->id)
        ->get();
    $total_stock_old = 0;
    $new_stock = 0;
    foreach ($sizes as $size) {
        $data = $size->toArray();
        $total_stock_old += $data['stock'];
        $new_stock += $_REQUEST['stock_' . $data['id']] ?? 0;
        $size = $_POST['sizes'][$data['id']] ?? $data['size'];
        $pack_size = $_POST['pack_size'][$data['id']] ?? $data['pack_size'];
        $label_count = $_POST['label_count'][$data['id']] ?? $data['label_count'];
        $strength = $_POST['strength'][$data['id']] ?? $data['strength'];
        $quantity = $_POST['quantity'][$data['id']] ?? $data['quantity'];
        $price = $_POST['price'][$data['id']] ?? $data['price'];
        if (ITEMS_PRICE_EX_VAT) {
            $price_exvat = $_POST['price'][$data['id']] ?? $data['price'];
            if ($item->vat_deductable) {
                $price = $price_exvat * (1 + $item->vat_rate / 100);
            } else {
                $price = $price_exvat;
            }
        } else {
            $price = $_POST['price'][$data['id']] ?? $data['price'];
            if ($item->vat_deductable) {
                $price_exvat = $price / (1 + $item->vat_rate / 100);
            } else {
                $price_exvat = $price;
            }
        }
        Size::query()
            ->where('id', $data['id'])
            ->update([
                'stock' => $_REQUEST['stock_' . $data['id']] ?? 0,
                'manual' => 1,
                'size' => $size,
                'price' => $price,
                'price_exvat' => $price_exvat,
                'pack_size' => $pack_size,
                'label_count' => $label_count,
                'strength' => $strength,
                'quantity' => $quantity,
            ]);

        $_REQUEST['sizeid'] = '';
        $msg = 'Stock updated';
        if ($size_custom = (new \Mtc\Shop\Item\SizeCustom())->where('size_id', $data['id'])->first()) {
            $size_custom->dosage = $_POST['dosage'][$data['id']];
            $size_custom->save();
        } else {
            (new \Mtc\Shop\Item\SizeCustom())->where('size_id', $data['id'])->create([
                'dosage' => $_POST['dosage'][$data['id']],
                'item_id' => $_REQUEST['id'],
                'size_id' => $data['id'],
            ]);
        }

        if (!empty($_POST['label_data'][$data['id']])) {
            // Clear all labels for this size and re-insert
            \Mtc\Shop\Item\SizeLabel::query()->where('size_id', '=', $data['id'])->delete();
            foreach ($_POST['label_data'][$data['id']] as $label) {
                if (!empty($label['title'])) {
                    $label['item_id'] = $_REQUEST['id'];
                    $label['size_id'] = $data['id'];
                    (new \Mtc\Shop\Item\SizeLabel())->create($label);
                }
            }
        }
    }

    $stock_updated = true;
    \Mtc\Shop\Item::updateSortPrice($item->id);
}

if ($_REQUEST['action'] === 'add') {
    if (!empty($_REQUEST['size'])) {
        if (ITEMS_PRICE_EX_VAT) {
            $price_exvat = $_REQUEST['price'];
            $sale_price_exvat = $_REQUEST['sale_price'];
            if ($item->vat_deductable) {
                $price = $price_exvat * (1 + $item->vat_rate / 100);
                $sale_price = $sale_price_exvat * (1 + $item->vat_rate / 100);
            } else {
                $price = $price_exvat;
                $sale_price = $sale_price_exvat;
            }
        } else {
            $price = $_REQUEST['price'];
            $sale_price = $_REQUEST['sale_price'];
            if ($item->vat_deductable) {
                $price_exvat = (float) $price / (1 + (float) $item->vat_rate / 100);
                $sale_price_exvat = (float) $sale_price / (1 + (float) $item->vat_rate / 100);
            } else {
                $price_exvat = $price;
                $sale_price_exvat = $sale_price;
            }
        }

        $size = \Mtc\Shop\Item\Size::query()
            ->updateOrCreate([
                'id' => $_REQUEST['sizeid']
            ], [
                'item_id' => $_REQUEST['id'],
                'size' => $_REQUEST['size'],
                'form_id' => $_REQUEST['form_id'] ?: null,
                'stock' => $_REQUEST['stock'] ?: 0,
                'price' => $price,
                'price_exvat' => $price_exvat,
                'sale_price' => $sale_price,
                'sale_price_exvat' => $sale_price_exvat,
                'weight' => $_REQUEST['weight'],
                'quantity' => $_REQUEST['quantity'],
                'pack_size' => $_REQUEST['pack_size'],
                'label_count' => $_REQUEST['label_count'],
                'strength' => $_REQUEST['strength'],
                'PLU' => $_REQUEST['epos_code'] ?? ''
            ]);

        if ($size !== null) {
            $msg = 'Size Updated';
            if ($size->wasRecentlyCreated) {
                $msg = 'Size Added';
            }

            $size->ingredients()->detach();

            if (!empty($_REQUEST['custom'])) {
                $custom_data->fill($_REQUEST['custom']);
                $custom_data->save();
            }
        }

        foreach ((array)request()->input('restricting_answers') as $q_id => $restricting_answer) {
            $sr = SizeRestriction::query()
                ->where('item_size_id', $size_eloquent->id)
                ->where('question_id', $q_id)
                ->first()
            ;

            if (! $sr) {
                $sr = SizeRestriction::create([
                    'item_size_id' => $size_eloquent->id,
                    'question_id' => $q_id,
                ]);
            }

            if ($sr) {
                $sr->restricting_answer = ($restricting_answer ?: null);
                $sr->save();
            }
        }

        \Mtc\Shop\Item::updateSortPrice($item->id);
        \Mtc\Plugins\SeoSchema\Classes\SchemaItem::buildCache($item);
        header('location: manage.sizes.php?id=' . $_REQUEST['id']);
        exit;
    } else {
        $errors['size'] = 'Size Name is required';
    }
}

if ($_REQUEST['action'] == 'delete' && is_numeric($_REQUEST['delete_id'])) {
    Size::query()
        ->where('id', $_REQUEST['delete_id'])
        ->delete();
    \Mtc\Shop\Item::updateSortPrice($item->id);
}

if ($_REQUEST['action'] == 'hide') {
    Size::query()
        ->where('id', $_REQUEST['hide_id'])
        ->update([
                'hide' => $_REQUEST['value']
        ]);
}

if ($_REQUEST['action'] != '' && empty($errors)) {
    // Request cache update for online doctor category price cache
    header('Location: ?id=' . $item->id);
    exit;
}

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

Event::dispatch('AdminBeforeBreadcrumbs', [ $item->eloquent() ?? null ]);

?>
    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li><a href="/shop/admin/products/manage.products.php">Manage Products</a> /</li>
        <li><a href="item.php?id=<?= clean_page($_REQUEST['id']) ?>"><?= clean_page($item->name) ?></a> /</li>
        <li class="end"><?= clean_page($page_meta['title']) ?></li>
    </ul>

    <h2>Sizes</h2>

<?php
include 'tabnav.php';
if (empty($errors) && isset($_REQUEST['action']) && $msg != '') {
    echo showmsg($msg, "success", $path);
}
$sizes = Size::query()
->where('item_id', $_REQUEST['id'])
    ->orderBy('order')
    ->orderBy('id')
    ->get();

if (!empty($errors)) {
    showerrors($errors);
}?>



<?php
if ($_REQUEST["sizeid"] == '') {
    if ($sizes->count() > 0) {
        ?>
        <form method="post">
            <?php
            if ($stock_updated) echo '<p>The stock has been updated</p>';
            ?>
            <table class="manage-items">
                <tr>
                    <th class="center">Order</th>
                    <th>EPOS Code</th>
                    <th>Dosage</th>
                    <th>Size Name</th>
                    <th>Pack size</th>
                    <th>No of labels</th>
                    <th>Quantity</th>
                    <th>Strength</th>
                    <?php if (ITEMS_SIZES_PRICES) { ?>
                        <th>Price</th>
                    <?php } ?>
                    <th>Stock</th>
                    <th class="center">Disabled</th>
                    <th class="center">Edit</th>
                    <th class="center">Delete</th>
                </tr>
                <tbody class="tabular ui-sortable">
                <?php
                foreach ($sizes as $size) {
                    $data = $size->toArray();
                    $custom_data = (new \Mtc\Shop\Item\SizeCustom())->where('size_id', $data['id'])->first();
                    ?>
                    <tr id="rorder-<?= $data['id'] ?>">
                        <td class="center order"><i class="fa fa-arrows"></i></td>
                        <td>
                            <input type="text"
                                   name="epos[<?= $data['id'] ?>]"
                                   value="<?= clean_page($data['PLU'] ?: ''); ?>" style="width:200px;" disabled="disabled" />
                        </td>
                        <td>
                            <input type="text"
                                   name="dosage[<?= $data['id'] ?>]"
                                   value="<?= clean_page($custom_data !== null ? $custom_data->dosage : ''); ?>" style="width:200px;"/>
                        </td>
                        <td>
                            <input type="text"
                                   name="sizes[<?= $data['id'] ?>]"
                                   value="<?= clean_page($data['size']); ?>" style="width:150px;"/>
                        </td>
                        <td>
                            <input type="text"
                                   name="pack_size[<?= $data['id'] ?>]"
                                   value="<?= clean_page($data['pack_size']); ?>"/>
                        </td>
                        <td>
                            <input type="text"
                                   name="label_count[<?= $data['id'] ?>]"
                                   value="<?= clean_page($data['label_count']); ?>"/>
                            <?php
                            if ($data['label_count'] > 1) {
                                ?>
                                <div class="sizeLabelsContainer">
                                    <i class="fa fa-bars labelListOpen" data-size_id="<?= $data['id'] ?>"></i>
                                    <div class="labelList hideme" id="labelList-<?= $data['id'] ?>">
                                        <div class="relative">
                                            <?php
                                            $size_labels = \Mtc\Shop\Item\SizeLabel::query()
                                                ->where('size_id', '=', $data['id'])
                                                ->orderBy('id')
                                                ->get()
                                                ->toArray();
                                            for ($i = 0; $i < $data['label_count']; $i++ ) {

                                                if(!empty($size_labels[$i])) {
                                                    ?>
                                                    <h4>Label <?= $i + 1; ?> data</h4>
                                                    <div class="row">
                                                        <input name="label_data[<?= $data['id']; ?>][<?= $i; ?>][title]" value="<?= $size_labels[$i]['title'] ?>" placeholder="Label Title">
                                                    </div>
                                                    <?php
                                                    if (false) {
                                                        ?>
                                                        <div class="row">
                                                            <input name="label_data[<?= $data['id']; ?>][<?= $i; ?>][strength]"
                                                                   value="<?= $size_labels[$i]['strength'] ?>"
                                                                   placeholder="Strength">
                                                        </div>
                                                        <div class="row">
                                                            <input name="label_data[<?= $data['id']; ?>][<?= $i; ?>][pack_size]"
                                                                   value="<?= $size_labels[$i]['pack_size'] ?>"
                                                                   placeholder="Pack Size">
                                                        </div>
                                                        <?php
                                                    }
                                                    ?>
                                                    <div class="row">
                                                        <input name="label_data[<?= $data['id']; ?>][<?= $i; ?>][dosage]" value="<?= $size_labels[$i]['dosage']?>" placeholder="Dosage">
                                                    </div>
                                                    <div class="row">
                                                        <input name="label_data[<?= $data['id']; ?>][<?= $i; ?>][warnings]" value="<?= $size_labels[$i]['warnings']?>" placeholder="Label Warnings">
                                                    </div>
                                                    <?php

                                                }
                                            }
                                            ?>
                                            <div class="labelListClose" data-size_id="<?= $data['id'] ?>">x</div>
                                        </div>
                                    </div>
                                </div>
                                <?php
                            }
                            ?>
                        </td>
                        <td>
                            <input type="text"
                                   name="quantity[<?= $data['id'] ?>]"
                                   value="<?= clean_page($data['quantity']); ?>"/>
                        </td>
                        <td>
                            <input type="text"
                                   name="strength[<?= $data['id'] ?>]"
                                   value="<?= clean_page($data['strength']); ?>"/>
                        </td>
                        <?php
                        if (ITEMS_SIZES_PRICES) {
                            ?>
                            <td>
                                <input type="text"
                                       name="price[<?= $data['id'] ?>]"
                                       value="<?= clean_page($data['price']); ?>"/>
                            </td>
                            <?php
                        }
                        ?>
                        <td>
                            <input type="text" name="stock_<?= $data['id']; ?>" value="<?= $data['stock']; ?>"/>
                        </td>
                        <td class="center">
                            <a href="<?= $_SERVER['PHP_SELF']; ?>?id=<?= $_REQUEST['id']; ?>&action=hide&hide_id=<?= $data['id']; ?>&value=<?= $data['hide'] == 1 ? '0' : '1'; ?>"><?= $data['hide'] == 1 ? 'Yes' : 'No'; ?></a>
                        </td>
                        <td class="center">
                            <a href="<?= $_SERVER['PHP_SELF']; ?>?id=<?= $_REQUEST['id']; ?>&sizeid=<?= $data['id'] ?>"
                               class="edit picto"><i class="fa fa-pencil"></i></a>
                        </td>
                        <td class="center"><a
                                    href="<?= $_SERVER['PHP_SELF']; ?>?id=<?= $_REQUEST['id']; ?>&action=delete&delete_id=<?= $data['id']; ?>"
                                    class="alert error picto" title="Are you sure you want to delete this size?"><i
                                        class="fa fa-times-circle"></i></a></td>
                    </tr>
                    <?php
                }
                ?>
                </tbody>
            </table>
            <p>
                <input type="hidden" name="id" value="<?= $_REQUEST['id']; ?>"/>
                <input type="hidden" name="action" value="update_prices"/>
                <input type="submit" value="Update"/>
            </p>
            <input type="hidden" id="orderbytable" value="items_sizes"/>
            <input type="hidden" id="orderbyfield" value="order"/>
        </form>
        <?php

    } else {
        ?>
        <p>There are currently no sizes for this item</p>
        <?php
    }

}
?>

    <form action="" class="style" method="post">
        <?php


        if ($_REQUEST['sizeid'] != '') {
            $data = Size::query()
                ->find($_REQUEST['sizeid'])
                ->toArray();
            $size = $data['size'];
            $quantity = $data['quantity'];
            $pack_size = $data['pack_size'];
            $label_count = $data['label_count'];
            $epos_code = $data['PLU'];
            $strength = $data['strength'];
            $stock = $data['stock'];

            if (ITEMS_PRICE_EX_VAT) {
                $price = $data['price_exvat'];
                $sale_price = $data['sale_price_exvat'];
            } else {
                $price = $data['price'];
                $sale_price = $data['sale_price'];
            }
        } else {
            $size = null;
            $pack_size = null;
            $label_count = null;
            $quantity = null;
            $strength = null;
            $epos_code = '';

            if (ITEMS_PRICE_EX_VAT) {
                $price = $item->price_exvat;
                $sale_price = $item->sale_price_exvat;
            } else {
                $price = $item->price;
                $sale_price = $item->sale_price;
            }
        }
        ?>

        <fieldset class="show">
            <h1><?= (isset($_REQUEST["sizeid"])) ? "Edit" : "Add"; ?> Size</h1>
            <div class="row">
                <label for="">Size name*</label><input type="text" name="size" value="<?= $size; ?>" class="short"/>
            </div>
            <div class="row">
                <label for="">Pack size</label><input type="text" name="pack_size" value="<?= $pack_size; ?>"
                                                      class="short"/>
            </div>
            <div class="row">
                <label for="">EPOS Code</label><input type="text" name="epos_code" value="<?= $epos_code; ?>"
                                                      class="short"/>
            </div>
            <div class="row">
                <label for="">No. of labels</label><input type="text" name="label_count" value="<?= $label_count; ?>"
                                                          class="short"/>
            </div>
            <div class="row">
                <label for="">Quantity</label><input type="text" name="quantity" value="<?= $quantity; ?>"
                                                     class="short"/>
            </div>
            <div class="row">
                <label for="">Strength</label><input type="text" name="strength" value="<?= $strength; ?>"
                                                     class="short"/>
            </div>

            <?php if (ITEMS_SIZES_PRICES) { ?>
                <div class="row">
                    <label for="">Price</label><input type="text" name="price" value="<?= $price; ?>" class="short"/>
                </div>
                <?php if (ITEMS_SALE) { ?>
                    <div class="row">
                        <label for="">Sale Price</label><input type="text" name="sale_price" value="<?= $sale_price; ?>"
                                                               class="short"/>
                    </div>
                <?php } ?>
            <?php } ?>

            <div class="row">
                <label for="">Stock</label><input type="text" name="stock" value="<?= $stock ?? 0 ?>" class="short" />
            </div>


            <?php if (isset($_REQUEST["sizeid"])): ?>
                <h1>Custom fields</h1>
                <?php foreach ($custom_fields as $custom_field) { ?>
                    <div class="row">
                        <label for="custom_<?= $custom_field->database_field; ?>">
                            <?=$custom_field->name; ?>
                        </label>
                        <?php if ($custom_field->type === 'textarea') { ?>
                            <textarea
                                    id="custom_<?= $custom_field->database_field; ?>"
                                    name="custom[<?= $custom_field->database_field; ?>]"
                                    class="tinymce"
                            ><?= $custom_data->{$custom_field->database_field}; ?></textarea>
                        <?php } else { ?>
                            <input type="text"
                                   id="custom_<?= $custom_field->database_field; ?>"
                                   name="custom[<?= $custom_field->database_field; ?>]"
                                   value="<?= $custom_data->{$custom_field->database_field}; ?>"
                            />
                        <?php } ?>
                    </div>
                <?php } ?>
            <?php endif ?>


            <?php if (false && $size_eloquent->id): ?>
                <h1>Restrictions</h1>

                <?php
                $form = $item->eloquent()->findAssessmentForm();
                $questions = QualifyingAnswersHelper::downloadTemplates($form);
                array_shift($questions);
                foreach ($questions as $key => $question) {
                    $questions[$key]['possible_answers_array'] = QualifyingAnswersHelper::getPossibleAnswersArray($question['Question Possible Answers']);
                }

                $size_restrictions = SizeRestriction::getForItemSize($size_eloquent);
                ?>

                <div class="row">
                    <table border="0" class="manage-items">
                        <thead>
                        <tr>
                            <th width="70%">Question</th>
                            <th>Restrict If</th>
                        </tr>
                        </thead>
                        <tbody class="tabular">
                        <?php foreach ($questions as $question): ?>
                            <?php $q_id = $question['Question ID'] ?>
                            <tr>
                                <td>
                                    <?= $q_id ?>
                                    <?= $question['Question'] ?>
                                </td>
                                <td>
                                    <?php if ($question['possible_answers_array']): ?>
                                        <select name="restricting_answers[<?= $q_id ?>]">
                                            <option value="">--- select ---</option>
                                            <?php foreach ($question['possible_answers_array'] as $answer): ?>
                                                <option <?= ($size_restrictions && $size_restrictions[$q_id] == $answer) ? 'selected' : '' ?>>
                                                    <?= $answer ?>
                                                </option>
                                            <?php endforeach ?>
                                        </select>
                                    <?php else: ?>

                                        <input
                                                type="text"
                                                name="answer[<?= $question['Question ID'] ?>]"
                                        />
                                    <?php endif ?>
                                </td>
                            </tr>
                        <?php endforeach ?>
                        </tbody>
                    </table>
                </div>
            <?php endif ?>

            <input type="hidden" name="id" value="<?= $_REQUEST['id']; ?>"/>
            <input type="hidden" name="sizeid" value="<?= $_REQUEST['sizeid']; ?>"/>
            <input type="hidden" name="action" value="add"/>

        </fieldset>

        <div class="row"><input type="submit"
                                value="<?php if ($_REQUEST['sizeid'] > 0) { ?>Update<?php } else { ?>Add<?php } ?> Size"/>
        </div>
    </form>

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