<?php


/*
 * This class is just a wrapper for what used to be a bunch of views.
 * It was created to make reusing and re-ordering columns easier.
 * It looks a bit hacky and messy, but it seems to be the a quick way of
 * transferirng all the views into methods.
 */

namespace Mtc\Shop\Admin;

use App\Events\OrderRowPrintedEvent;
use Illuminate\Support\Facades\Event;
use Mtc\Core\Permissions;

class ViewHelper
{
    public const HEADER_ROW = 0;
    public const DATA_ROW = 1;

    public static array $flags = [
        1 => 'brown',
        2 => 'black',
    ];

    /* PUBLIC */

    //array of GET or POST keys that the page uses to remember the view state
    public static $view_state_keys = [
        'status',
        'id',
        'coupon',
        'category',
        'name',
        'email',
        'postcode',
        'start_date',
        'end_date',
        'type',
        'orderbydir',
        'orderbyfield',
        'page',
        'order_type',
        'approved',
        'doctor_note',
        'pharmacist_note',
        'shipment_created',
        'approval_status',
        'product_type',
    ];

    public static function getHeaderRow($access_type)
    {
        return self::getRow($access_type, self::HEADER_ROW);
    }

    public static function getDataRow($access_type, $order)
    {
        return self::getRow($access_type, self::DATA_ROW, $order);
    }


    public static function printCheckboxRow()
    {
        ?>
        <tr>
            <td class="center">
                <script type="text/javascript">
                    function toggleChecked(status) {
                        $(".checkbox").each(function () {
                            $(this).prop("checked", status);
                        })
                    }
                </script>
                <input type="checkbox" value="1" onclick="toggleChecked(this.checked)"/>
            </td>
            <td>
                All
            </td>
            <td colspan="10">&nbsp;</td>
        </tr>

        <?php
    }



    /* PRIVATE */

    private static function getRow($access_type, $row_type, $order = null)
    {

        self::print_tr_open($row_type, $order);

        switch ($access_type) {

            case 'doctor':

                self::print_status($row_type, $order, true);
                self::print_doctor_note($row_type, $order);
                self::print_date($row_type, $order);
                self::print_customer_name($row_type, $order);
                self::print_purchased($row_type, $order);
                Event::dispatch(OrderRowPrintedEvent::class, new OrderRowPrintedEvent($row_type, $access_type, $order));
                self::print_actions($row_type, $order);

                break;

            case 'pharmacist':

                self::print_process($row_type, $order);
                self::print_date($row_type, $order);
                self::print_actions($row_type, $order, true);
                self::print_status($row_type, $order);
                self::print_doctor_note($row_type, $order);
                self::print_pharmacy_note($row_type, $order);
                self::print_order($row_type, $order);
                self::print_purchased($row_type, $order);
                self::print_total($row_type, $order);
                Event::dispatch(OrderRowPrintedEvent::class, new OrderRowPrintedEvent($row_type, $access_type, $order));

                break;

            case 'manager':

                self::print_process($row_type, $order);
                self::print_date($row_type, $order);
                self::print_actions($row_type, $order, true);
                self::print_status($row_type, $order);
                self::print_order($row_type, $order);
                self::print_purchased($row_type, $order);
                self::print_shipment_created($row_type, $order);
                self::print_total($row_type, $order);
                Event::dispatch(OrderRowPrintedEvent::class, new OrderRowPrintedEvent($row_type, $access_type, $order));

                break;

        }

        self::print_tr_close($row_type, $order);

    }


    private static function print_tr_open($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <tr>

    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <?php
        $order_eloquent = $order->eloquent();

        $row_class = '';
        if ($order->flag > 0) {
            $row_class .= ' list-' . self::$flags[$order->flag];
        }
        if ($order->ordered_within_four_weeks > 0) {
            $row_class .= ' recurringOrder';
        }
        if (!empty($order->patient_notes)) {
            $row_class .= ' hasPatientNotes';
        }
        ?>

        <tr
        id="rorder-<?= $order->getId() ?>"
        class="<?= $row_class; ?> sss"
        data-order-id="<?= $order_eloquent->id ?>"
        >

    <?php } ?><?php
    }


    private static function print_tr_close($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        </tr>

    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        </tr>

    <?php } ?><?php
    }



    private static function print_customer_name($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th>
            Customer name
        </th>

    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td>
            <div>
                <b><?= $order->order_ref; ?></b> by
                <?= $order->address['billing']['firstname'] . ' ' . $order->address['billing']['lastname'] . ' (' . $order->address['billing']['gender'] . ')'; ?>
                <?php
                if ($order->id_check_confirmed) {
                    ?>
                    <span class='orderVerified'
                          title="<?= $order->id_check_confirmed == 2 ? 'ID Check confirmed on previous order' : 'ID check confirmed' ?>">
                                                    <i class='fa fa-check-circle<?= $order->id_check_confirmed == 2 ? '-o' : '' ?>'></i>
                                                </span>
                    <?php
                }
                ?>
                <a href="manage.order.doctor.php?id=<?= $order->getId() ?>&tab=2" class="actionsIcon mtcOverlay">
                    <i class="fa fa-list-alt"></i>
                </a>
                <?php
                if (!empty($order->admin_id)) {
                    $adminUser = $order->getAdminUser();
                    ?>
                    <br/><strong>Placed by <?= $adminUser->name ?? '-'; ?></strong>
                    <?php
                }
                ?>
            </div>
        </td>

    <?php } ?><?php
    }


    private static function print_status($row_type, $order, $use_color_coding = false)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th>Status</th>

    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <?php
        $colorCoding = [
            0 => 'rgb(196, 218, 255)',
            1 => 'rgb(37, 127, 124)',
            2 => 'rgb(206, 0, 0)',
            3 => 'rgb(0, 170, 85)',
            11 => 'rgb(37, 127, 124)',
            13 => 'rgb(255, 127, 80)',
            8 => 'rgb(255, 150, 80)',
        ];
        ?>

        <td>
            <?php if ($use_color_coding) { ?>
                <span class="label" style="background-color: <?php echo $colorCoding[$order->status] ?? '#999999'; ?>; color:#fff; padding:5px 10px;">
                        <?= \Mtc\Shop\Order::$statuses[$order->status]; ?>
                    </span>
            <?php } else { ?>
                <?= \Mtc\Shop\Order::$statuses[$order->status]; ?>
            <?php } ?>
        <?php $order_member = $order->getMemberModel(); ?>
            <?= empty($order_member->passed_id_check) && $order->eloquent()->failed_id_check ? '<div><strong>ID Check Failed</strong></div>' : '' ?>
        </td>

    <?php } ?><?php
    }


    private static function print_pharmacy_note($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th>
            Pharmacy Note<br/>
            <div class="row">
                <select name="pharmacist_note" id="pharmacist_note" class="headerFilter">
                    <option value="">Any</option>
                    <option value="not_empty" <?= $_REQUEST['pharmacist_note'] === 'not_empty' ? 'selected' : ''; ?>>Not Empty</option>
                    <option value="empty" <?= $_REQUEST['pharmacist_note'] === 'empty' ? 'selected' : ''; ?>>Empty</option>
                </select>
            </div>
        </th>

    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td class="pharmacistNoteColumn"
            data-order_id="<?= $order->getId(); ?>">
                <span class="pharmacistNoteText"
                      id="pharmacistNoteText-<?= $order->getId(); ?>"><?= clean_page($order->pharmacist_note); ?></span>
            <input class="pharmacistNoteInput hideme" id="pharmacistNoteInput-<?= $order->getId(); ?>"
                   value="<?= clean_page($order->pharmacist_note); ?>" data-order_id="<?= $order->getId(); ?>"/>
        </td>

    <?php } ?><?php
    }


    private static function print_order($row_type, $order, $is_nhs_user = false)
    {

        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th>
            <a href="<?= 'manage.orders.php?' . modifyViewStateQueryString($_REQUEST, self::$view_state_keys, ['orderbyfield' => 'order-id', 'page' => 1]) ?>">
                Order
                <?php
                if ($_REQUEST['orderbyfield'] != 'order-id') {
                    $odorderbydir = 'DESC';
                } else {
                    $odorderbydir = $_REQUEST['orderbydir'] ?? 'ASC';
                }
                ?>
                <img src="/admin/images/<?php if ($odorderbydir == 'DESC') { ?>down.png<?php } else { ?>up.png<?php } ?>"
                     border="0"/>
            </a>
        </th>

    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td>
            <div>
                <b>
                    <a href="manage.order.php?id=<?= $order->getId() ?>"
                       style="color:#004B91;letter-spacing:1px;"><?= $order->order_ref; ?>
                    </a>
                </b> by
                <?php
                $member_url = config('clinic.enabled') ?
                    route('admin-patients-profile', [
                        'id' => $order->member
                    ], false) :
                    'order.contact.php?id=' . $order->getId();
                ?>
                <a href="<?= $member_url; ?>">
                    <?= $order->address['billing']['firstname'] . ' ' . $order->address['billing']['lastname'] . ' (' . $order->address['billing']['gender'] . ')'; ?>
                </a>
                <?php
                $order_member = $order->getMemberModel();
                if (!empty($order_member->passed_id_check)) {
                    ?>
                    <span class="orderVerified" title="">
                            <i class='fa fa-check-circle'></i>
                        </span>
                    <?php
                }
                ?>
                <a href="manage.order.doctor.php?id=<?= $order->getId() ?>&tab=2" class="actionsIcon mtcOverlay">
                    <i class="fa fa-list-alt"></i>
                </a>
                <?php
                if (!empty($order->admin_id)) {
                    $adminUser = $order->getAdminUser();
                    ?>
                    <br/><strong>Placed by <?= $adminUser->name ?? '-' ?></strong>
                    <?php
                }
                if (!empty($order->patient_notes)) {
                    ?>
                    <br/>
                    <a href="manage.order.doctor.php?id=<?= $order->getId() ?>&tab=4" class="actionsIcon mtcOverlay">
                        <strong>Patient Note</strong>
                    </a>
                    <?php
                }
                ?>
            </div>
        </td>

    <?php } ?><?php
    }



    private static function print_purchased($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th>
            <a href="<?= 'manage.orders.php?' . modifyViewStateQueryString($_REQUEST, self::$view_state_keys, ['orderbyfield' => 'item']) ?>">
                Purchased
                <?php
                if ($_REQUEST['orderbyfield'] !== 'item') {
                    $odorderbydir = 'ASC';
                } else {
                    $odorderbydir = $_REQUEST['orderbydir'] ?? 'ASC';
                    ?>
                    <img src="/admin/images/<?php if ($odorderbydir === 'DESC') { ?>down.png<?php } else { ?>up.png<?php } ?>"
                         border="0"
                         alt=""
                    />
                    <?php
                }
                ?>
            </a>

            <div class="row">
                <select name="approval_status" id="approval_status" class="headerFilter">
                    <option value="">All</option>
                    <option value="approved" <?= $_REQUEST['approval_status'] === 'approved' ? 'selected' : ''; ?>>Approved</option>
                    <option value="not_approved" <?= $_REQUEST['approval_status'] === 'not_approved' ? 'selected' : ''; ?>>Not Approved</option>
                </select>
            </div>
        </th>


    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td>

            <div class="items">
                <table>
                    <?php
                    foreach ($order->getItems() as $order_item_id => $line) {
                        // In the Processing view hide all refunded items
                        if ($_REQUEST['order_type'] === 'processing' && $order->isItemRefunded((int)$order_item_id)) {
                            continue;
                        }
                        $itemUrl = $line['item_url'] ?? '#';
                        ?>
                        <tr<?= $line['PLU'] === 'private_prescription' ? ' class="privatePrescriptionItemRow"' : ''; ?>>
                            <td>
                                <?= $line['quantity'] ?>x
                            </td>
                            <td colspan="2">
                                <a href="<?= $itemUrl; ?>" target="_blank">
                                    <?= clean_page($line['item_name']); ?>
                                    <?= $line['PLU'] === 'private_prescription' ? ' <strong>(PP)</strong>' : ''; ?>
                                    <?= !empty($line['has_requested_subscription']) ? ' <i class="fa fa-refresh" style="color:#00aa00;" title="Subscription"></i> <strong style="color:#00aa00;">sRx</strong>' : ''; ?>
                                </a>
                            </td>
                            <td><?= strip_tags($line['size'], '<br>'); ?></td>
                            <td>
                                <?php
                                // If approved, always show green check
                                if ((int)$line['approved'] === \Mtc\Shop\Order\Item::ORDER_ITEM_APROVED) {
                                    ?>
                                    <i class="fa fa-check green" title="Approved"></i>
                                    <?php
                                    // Only show the red block if the order is not in status 'Pending review'
                                    // and the item is not approved
                                } elseif ((int)$line['approved'] === \Mtc\Shop\Order\Item::ORDER_ITEM_REJECTED) {
                                    ?>
                                    <i class="fa fa-ban red" title="Rejected"></i>
                                    <?php
                                } elseif ((int)$order->status === \Mtc\Shop\Order::STATUS_WAITING_FOR_RESPONSE) {
                                    ?>
                                    <i class="fa fa-info-circle" title="Waiting for response" style="color:#e5a553;"></i>
                                    <?php
                                } else {
                                    ?>
                                    <i class="fa fa-hourglass" title="Pending Review" style="color:#e5da51;"></i>
                                    <?php
                                }
                                if ($line['clinic_checked']) {
                                    ?>
                                    <i class="fa fa-check-circle green" title="Clinically Checked"></i>
                                    <?php
                                }
                                ?>
                            </td>
                        </tr>
                        <?php
                    }
                    ?>
                </table>
            </div>

        </td>

    <?php } ?><?php
    }



    private static function print_doctor_note($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th>
            Doctor Note<br/>
            <div class="row">
                <select name="doctor_note" id="doctor_note" class="headerFilter">
                    <option value="">Any</option>
                    <option value="not_empty" <?= $_REQUEST['doctor_note'] === 'not_empty' ? 'selected' : ''; ?>>Not
                        Empty
                    </option>
                    <option value="empty" <?= $_REQUEST['doctor_note'] === 'empty' ? 'selected' : ''; ?>>Empty</option>
                </select>
            </div>
        </th>


    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td class="doctorNoteColumn" data-order_id="<?= $order->getId(); ?>">
                <span class="doctorNoteText"
                      id="doctorNoteText-<?= $order->getId(); ?>"><?= strip_tags($order->doctor_note, ['<br>','<hr>']); ?></span>
            <input class="doctorNoteInput hideme" id="doctorNoteInput-<?= $order->getId(); ?>"
                   value="<?= clean_page($order->doctor_note); ?>" data-order_id="<?= $order->getId(); ?>"/>
        </td>

    <?php } ?><?php
    }



    private static function print_ship_to($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th>
            Ship To
        </th>

    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td>
            <p>
                <?php
                $address = $order->address['shipping'];
                echo $address['address1'] . (empty($address['address2']) ? '' : ' ' . $address['address2']);
                echo ', ' . $address['city'];
                echo empty($address['state']) ? '' : ', ' . $address['state'];
                echo ', ' . $address['country'];
                echo ', ' . $address['postcode'];
                ?>
            </p>
            <p><?= $order->getDelivery()->name ?></p>
        </td>

    <?php } ?><?php
    }



    private static function print_billing_address($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th>
            Billing Address
        </th>

    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td>
            <p>
                <?php
                $address = $order->address['billing'];
                echo $address['address1'] . (empty($address['address2']) ? '' : ' ' . $address['address2']);
                echo ', ' . $address['city'];
                echo empty($address['state']) ? '' : ', ' . $address['state'];
                echo ', ' . $address['country'];
                echo ', ' . $address['postcode'];
                ?>
            </p>
            <p><?= $order->getDelivery()->name ?></p>
        </td>

    <?php } ?><?php
    }



    private static function print_shipment_created($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th>
            Shipment Created<br/>
            <div class="row">
                <select name="shipment_created" id="shipment_created" class="headerFilter">
                    <option value="">Any</option>
                    <option value="yes" <?= $_REQUEST['shipment_created'] === 'yes' ? 'selected' : ''; ?>>Yes</option>
                    <option value="no" <?= $_REQUEST['shipment_created'] === 'no' ? 'selected' : ''; ?>>No</option>
                </select>
            </div>
        </th>


    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td class="center">
            <?= $order->eloquent()->shipments->first()->service ?? '' ?>
        </td>

    <?php } ?><?php
    }


    private static function print_date($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <?php
        if ($_REQUEST['orderbyfield'] != 'order-date') {
            $current_order_dir = 'DESC';
        } else {
            $current_order_dir = request()->input('orderbydir') ?: 'ASC';
        }

        $opposite_order_dir = ($current_order_dir == 'ASC') ? 'DESC' : 'ASC';
        ?>

        <th class="center">
            <a href="<?= 'manage.orders.php?' . modifyViewStateQueryString($_REQUEST, self::$view_state_keys, ['orderbyfield' => 'order-date', 'orderbydir' => $opposite_order_dir, 'page' => 1]) ?>">
                Date
                <img src="/admin/images/<?php if ($current_order_dir == 'DESC') { ?>down.png<?php } else { ?>up.png<?php } ?>"
                     border="0"/>
            </a>
        </th>


    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td class="center">
            <p><?= $order->getOrderDate('d/m/Y H:i:s') ?></p>
            <p><?= $order->eloquent()->info->getSiteOfOrigin() ?></p>
        </td>

    <?php } ?><?php
    }



    private static function print_total($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th width="120">
            <a href="<?= 'manage.orders.php?' . modifyViewStateQueryString($_REQUEST, self::$view_state_keys, ['orderbyfield' => 'order-cost_total', 'page' => 1]) ?>">
                Total
                <?php
                if ($_REQUEST['orderbyfield'] != 'order-cost_total') {
                    $odorderbydir = 'DESC';
                } else {
                    $odorderbydir = $_REQUEST['orderbydir'] ?? 'ASC';
                }
                ?>
                <img src="/admin/images/<?php if ($odorderbydir == 'DESC') { ?>down.png<?php } else { ?>up.png<?php } ?>"
                     border="0"/>
            </a>
        </th>

    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td>
            <p style="text-align:center;">&pound;<?php printf("%.2f", $order->getTotalCost()); ?></p>
            <p style="text-align:center;">
                <?php
                if (($order->payment['VendorTxCode'] ?? '') != '' && $order->payment['VPSTxId'] == '') {
                    ?>
                    <i class="fa fa-phone" aria-hidden="true"></i>
                    <?php
                } else {
                    ?>
                    <img src="<?= clean_page($order->payment_icon ?? '') ?>" border="0" height="15"/>
                    <?php
                }
                ?>
            </p>
        </td>

    <?php } ?><?php
    }



    private static function print_actions($row_type, $order, $edit_enabled = false)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th>Actions</th>


    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td class="nowrap center" style="white-space: nowrap;" nowrap>

            <?php if ($edit_enabled) { ?>
                <a href="manage.order.php?id=<?= $order->getId() ?>" class="edit actionsIcon">
                    <i class="fa fa-pencil"></i>
                </a>
            <?php } ?>

            <a href="manage.order.doctor.php?id=<?= $order->getId() ?>" class="actionsIcon mtcOverlay">
                <i class="fa fa-eye"></i>
            </a>

            <?php if ($order->message_id) { ?>
                <?php $msg_data = $order->eloquent()->getMessageThreadsData() ?>
                <a href="/plugins/MembersMessaging/admin/view_member_thread.php?url=<?= $msg_data['thread']->url ?>" title="View Messages">
                    <i class="fa fa-envelope<?php echo $msg_data['has_unread_messages'] ? '' : '-o'; ?>"></i>
                </a>
            <?php } ?>

        </td>

    <?php } ?><?php
    }



    private static function print_process($row_type, $order)
    {
        ?><?php if ($row_type == self::HEADER_ROW) { ?>

        <th class="center">Process</th>

    <?php } elseif ($row_type == self::DATA_ROW && $order) { ?>

        <td class="center">
            <p>
                <input type="checkbox" name="process_orders[<?= $order->getId() ?>]" value="1" class="checkbox"/>
            </p>
            <p>
                <?php $order_eloquent = $order->eloquent() ?>
                <?php foreach ($order_eloquent->subscriptions as $sub): ?>
                    <?= "<span class='orderLabel' title=''>sub:{$sub->id}" ?>
                    <?= "({$sub->getIssueNumber($order_eloquent)}&nbsp;of&nbsp;" . ($sub->max_number_of_issues ?: '∞') . ")</span>" ?>
                <?php endforeach ?>
            </p>
        </td>

    <?php } ?><?php
    }

}
