<?php

use Carbon\Carbon;
use Mtc\Core\Permissions;
use Mtc\Modules\Members\Models\Member;
use Mtc\Modules\Members\Models\MemberNote;

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

init_request_values([
    'tab' => null,
    'load_all_items' => null,
]);

$email_templates = \Mtc\Shop\EmailTemplate::all();
$page_meta['title'] = 'Order Details';

if (!$order = Order::getById($_REQUEST['id'])) {
    throw new Exception('No order ID provided');
}

$current_order_id = $order->getId();

// Orders within last 30 days
$has_past_orders = \Mtc\Shop\Order::query()
                                  ->where('paid', '=', '1')
                                  ->where('member', '=', $order->member)
                                  ->where('id', '<', $order->getId())
                                  ->where('date', '>', (new \Carbon\Carbon($order->getOrderDate('Y-m-d H:i:s')))->subDays(30)->format('Y-m-d H:i:s'))
                                  ->count() > 0;

$timestamp = time();

// load admin eloquent user and its allowed categories
$admin = \Mtc\Core\Admin\User::find($adminuser->user['id']);

$tab = $_REQUEST['tab'] ?: '1';
?>
<div class="tabs js_tabs" id="tabsOne">

    <nav class="tabsNav">
        <ul class="tabsnavAlt el">
            <li<?= $tab === '1' ? ' class="active"' : ''; ?>>
                <a href="#tab_0">
                    Assessment Form
                </a>
            </li>
            <li<?= $tab === '2' ? ' class="active"' : ''; ?>>
                <a href="#tab_1">
                    <?php $previous_orders_count = $order->eloquent()->customer->orders()->successful()->count() ?>
                    User History (<?= $previous_orders_count ?>)
                </a>
            </li>
            <li<?= $tab === '3' ? ' class="active"' : ''; ?>>
                <a href="#tab_2">
                    Health Profile
                </a>
            </li>
            <li<?= $tab === '4' ? ' class="active"' : ''; ?>>
                <a href="#tab_3">
                    Patient Notes
                </a>
            </li>
        </ul>
    </nav>


    <div class="tabsContentWrap">
        <div class="tabContent open" data-tab-id="#tab_0">
            <div class="tabTitle">
            </div>
            <?php
            $order_item_approval_mode = !$_REQUEST['load_all_items'] && (
                    Permissions::can(Permissions::REVIEW_DOCTOR_ORDERS) ||
                    Permissions::can(Permissions::REVIEW_PHARMACY_ORDERS)
                );
            if ($order_item_approval_mode) {
                $order_member = (new Member())->find($order->member);
                ?>
                <div class="row">
                    Patient name: <strong><?= clean_page($order->address['billing']['firstname'] . ' ' . $order->address['billing']['lastname'] . ' (' . $order->address['billing']['gender'] . ')'); ?></strong><br />
                    DOB: <?php try { echo !empty($order_member->dob) ? Carbon::parse($order_member->dob)->format('d/m/Y') : '-'; } catch (\Throwable $e) { echo '-'; } ?>
                </div>
                <?php
                if ($has_past_orders) {
                    ?>
                    <div class="row">
                        <strong style="background-color: #FFEE99;">&nbsp;RECURRING ORDER&nbsp;</strong>
                    </div>
                    <?php
                }
                ?>
                <div class="row">
                    <table class="manage-items">
                        <tr>
                            <th>Name</th>
                            <th>Strength</th>
                            <th>Size Quantity</th>
                            <th>Status</th>
                        </tr>
                        <?php
                        foreach ($order->getItems() as $order_item_id => $order_item) {
                            $size = \Mtc\Shop\Item\Size::query()->find($order_item['sizeid']);
                            $classes = [
                                0 => '',
                                1 => 'approved',
                                2 => 'rejected',
                            ];
                            $statuses = [
                                0 => 'Awaiting',
                                1 => 'Approved',
                                2 => 'Rejected',
                            ];
                            ?>
                            <tr id="orderItemRow-<?= $order_item_id; ?>" class="orderItemRow">
                                <td><?= $order_item['quantity'] ?>x &nbsp; <?= clean_page($order_item['item_name']); ?></td>
                                <td><?= clean_page($size->strength ?? '-'); ?></td>
                                <td><?= clean_page($size->quantity ?? '-'); ?></td>
                                <td id="orderItemStatus-<?= $order_item_id; ?>" class="orderItemStatus <?= $classes[$order_item['approved']]; ?>">
                                    <?= $statuses[$order_item['approved']]; ?>
                                </td>
                            </tr>
                            <?php
                        }
                        ?>
                    </table>
                </div>
                <?php
            }
            ?>
            <div class="el customerdetails" id="orderItemDoctor">
                <?php
                if (!$order_item_approval_mode) {
                    $show_totals = false;
                    $order_preview_popup = true;
                    include $path . 'shop/admin/orders/templates/order.basket.view.php';
                    if ($order->eloquent()->hasMagentoAssessment()) {
                        require_once $path . 'shop/admin/orders/templates/order.assessment.magento.php';
                    }
                }
                ?>
            </div>
        </div>
        <div class="tabContent" data-tab-id="#tab_1">
            <div class="tabTitle">
            </div>

            <table class="tabular">
                <?php
                $historical_orders = \Mtc\Shop\Order::query()
                                                    ->where('member', '=', $order->member)
                                                    ->where('paid', '=', '1')
                                                    ->where('failed', '=', '0')
                                                    ->get();

                $included = true;
                $order_bak = $order;
                foreach ($historical_orders as $historical_order) {
                    $order = new Order($historical_order->id);
                    $load_all_items = true;

                    include __DIR__ . '/manage.orders.doctor.php';
                }
                $order = $order_bak;
                ?>
            </table>
        </div>
        <div class="tabContent" data-tab-id="#tab_2">
            <div class="tabTitle">

            </div>
            <div class="el customerdetails">
                <h2>Health Profile</h2>
                <table class="manage-items">
                    <tr>
                        <td>Medications</td>
                        <td><?= $order->eloquent()->customer->getMedicationsString('<br />') ?></td>
                    </tr>
                    <tr>
                        <td>Medications (from Order)</td>
                        <td><?= (empty($order->info['member_medications'])) ? '-' : implode('<br />', json_decode($order->info['member_medications'])); ?></td>
                    </tr>
                    <tr>
                        <td>Medical Conditions</td>
                        <td><?= $order->eloquent()->customer->getConditionsString('<br />') ?></td>
                    </tr>
                    <tr>
                        <td>Medical Conditions (from Order)</td>
                        <td><?= (empty($order->info['member_conditions'])) ? '-' : implode('<br />', json_decode($order->info['member_conditions'])); ?></td>
                    </tr>
                    <tr>
                        <td>Allergies</td>
                        <td><?= $order->eloquent()->customer->getAllergiesString('<br />') ?></td>
                    </tr>
                    <tr>
                        <td>Allergies (from Order)</td>
                        <td><?= (empty($order->info['member_allergies'])) ? '-' : implode('<br />', json_decode($order->info['member_allergies'])); ?></td>
                    </tr>

                    <tr>
                        <td>Name</td>
                        <td><?= clean_page($order->address['billing']['firstname'] . ' ' . $order->address['billing']['lastname'] . ' (' . $order->address['billing']['gender'] . ')'); ?></td>
                    </tr>

                    <tr>
                        <td>Phone</td>
                        <td><?= clean_page($order->info['contact_no']); ?></td>
                    </tr>
                    <tr>
                        <td>Email</td>
                        <td><?= clean_page($order->info['email']); ?></td>
                    </tr>
                    <?php

                    $order_member = (new Member())->find($order->member);
                    $doctor_surgery = !empty($order_member->doctor_surgery) ?
                        json_decode($order_member->doctor_surgery) :
                        null;
                    ?>

                    <tr>
                        <td>Gender</td>
                        <td><?= clean_page($order_member->gender); ?></td>
                    </tr>
                    <tr>
                        <td>Date of birth</td>
                        <td><?php try { echo !empty($order_member->dob) ? Carbon::parse($order_member->dob)->format('d/m/Y') : '-'; } catch (\Throwable $e) { echo '-'; } ?></td>
                    </tr>
                    <?php
                    if (!empty($doctor_surgery)) {
                        ?>
                        <tr>
                            <td>Doctor surgery</td>
                            <td>
                                <?= clean_page($doctor_surgery->practice_name); ?><br />
                                <?= clean_page($doctor_surgery->city); ?><br />
                                <?= clean_page($doctor_surgery->address_1); ?><br />
                                <?= clean_page($doctor_surgery->address_2); ?><br />
                                <?= clean_page($doctor_surgery->postcode); ?><br />
                                <?= clean_page($doctor_surgery->phone); ?><br />
                            </td>
                        </tr>
                        <?php
                    }
                    ?>
                </table>
            </div>

        </div>
        <div class="tabContent" data-tab-id="#tab_3">
            <div class="tabTitle">

            </div>
            <form action="/shop/admin/ajax.php" id="patientNotesForm">
                <div class="el customerdetails">
                    <h2>Patient Notes</h2>
                    <div class="patientNotesFields">
                        <div class="row">
                            <textarea name="note" id="patientNotesInput<?= $timestamp; ?>" class="simpletinymce"
                                      placeholder="Patient notes"></textarea>
                        </div>
                        <div class="row">
                            <input type="hidden" name="order_id" value="<?= $order->getId(); ?>"/>
                            <input type="hidden" name="action" value="update_patient_notes"/>
                            <button type="submit"
                                    class="btn"
                                    id="savePatientNotes">
                                Save
                            </button>
                        </div>
                    </div>
                    <div class="viewPatientNotes">
                        <div class="row">
                            <button type="button"
                                    name="action"
                                    value="edit_notes"
                                    class="btn"
                                    id="editPatientNotes">
                                Add a note
                            </button>
                        </div>
                        <div class="row" id="patientNotesOutput">
                            <?php
                            if ($order->eloquent()->memberNotes()->count()) {
                                echo MemberNote::getOrderNotesHTML($order->getId());
                            } else {
                                echo '<em>No notes</em>';
                            }
                            ?>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    tabs_on_overlay();
    var tab = <?= (int)$tab; ?>;
    $('.js_tabs').mtcTabs({ active: tab });

    init_tinymce();

    // ---- Patient notes UX fixes ----
    (function ($) {
        const $fieldsWrap = $('.patientNotesFields');
        const $editBtn    = $('#editPatientNotes');
        const $form       = $('#patientNotesForm');
        const $output     = $('#patientNotesOutput');
        const $saveBtn    = $('#savePatientNotes');
        const editorId    = 'patientNotesInput<?= (int)$timestamp; ?>';

        function getEditor() {
            return (window.tinymce && tinymce.get(editorId)) ? tinymce.get(editorId) : null;
        }

        function resetEditor() {
            const ed = getEditor();
            if (ed) {
                ed.setContent('');
                // clear undo stack so Ctrl+Z doesn’t bring content back
                if (ed.undoManager) ed.undoManager.clear();
            }
            $('#' + editorId).val('');
        }

        function showEditor() {
            resetEditor();                 // always start fresh
            $fieldsWrap.show();
            $editBtn.hide();
            // focus cursor into editor
            const ed = getEditor();
            if (ed) setTimeout(() => ed.focus(), 0);
        }

        function hideEditor() {
            $fieldsWrap.hide();
            $editBtn.show();
        }

        // initial state
        hideEditor();

        // Open editor
        $editBtn.on('click', function () {
            showEditor();
        });

        // Save note (AJAX)
        $saveBtn.on('click', function (e) {
            e.preventDefault();

            // prevent double submit
            if ($saveBtn.prop('disabled')) return;
            $saveBtn.prop('disabled', true);

            // make sure textarea has current TinyMCE content
            const ed = getEditor();
            if (ed) {
                $('#' + editorId).val(ed.getContent());
            }

            $.ajax({
                type: 'POST',
                url: $form.attr('action'),
                data: $form.serialize(),
                dataType: 'json'
            }).done(function (response) {
                // Expected: { notes: "<html>" }
                if (response && typeof response.notes === 'string') {
                    $output.html(response.notes);
                }
                // start clean for next note
                resetEditor();
                hideEditor();
            }).fail(function () {
                alert('Could not save the note. Please try again.');
            }).always(function () {
                $saveBtn.prop('disabled', false);
            });
        });
    })(jQuery);

    <?php if (empty($_REQUEST['load_all_items'])) { ?>
    // Only load the item if the doctor is reviewing
    get_next_doctor_item(<?= (int)$current_order_id ?>);
    <?php } ?>
</script>

