<?php

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

use Mtc\Core\Models\CountryState;
use Mtc\Shop\Order\Contact;
use Mtc\Shop\StandardTemplateLetter;

$page_meta['title'] = 'Contact Customer';

$order = new Order($_REQUEST['id']);
$basket = &$order;
$errors = [];

$display_form = true;
$subject = '';
$subject_other = '';
$message = '';

if (!empty($_REQUEST['subject'])) {
    $subject = clean_page($_REQUEST['subject']);
}

if (!empty($_REQUEST['subject_other']) && $subject == 'custom') {
    $subject = clean_page($_REQUEST['subject_other']);
}

if (!empty($_REQUEST['message'])) {
    $message = $_REQUEST['message'];
}

if ($_REQUEST['action'] == 'Send') {

    if (empty($subject)) {
        $errors['subject'] = 'Subject is a required field';
    }

    if (empty($message)) {
        $errors['message'] = 'Message is a required field';
    }

    if (empty($errors)) {

        $options = [
            'order' => $order, // order details
            'order_total' => $order->getTotalCost(), // orders total cost
            'line_items' => $order->getLineItems(), // Order items with additional up to date information pulled from the item class
            'order_subtotal' => $order->getSubtotalCost(),
            'vat_cost' => $order->getVatCost(), // Total VAT cost of the order
            'order_date' => $order->getOrderDate('Y-m-d H:i:s'), // order date sent in full... twig can re-render into any date format from here
            'delivery_cost' => $order->getDelivery()->cost, // Delivery Cost
            'delivery_name' => $order->getDelivery()->name, // Delivery Name
            'order_status_text' => $order->getOrderStatusText(0), // Order status text as defined in admin under shop/order status text
            'html' => $message,
            'subject' => $subject,
            'countries' => $countries, // Country name
            'state_list' => CountryState::getCountryStateList(),
        ];

        $email_body = $twig->render('emails/shop/contact_email.twig', $options);

        email($order->info['email'], config('app.name') . ' - ' . $subject, $email_body);

        Contact::query()
            ->create([
                'order_id' => $order->info['order_id'],
                'subject' => $subject,
                'message' => $message,
            ]);

        $display_form = false;
    }

}

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

?>

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li><a href="manage.orders.php">Manage Orders</a> /</li>
    <li><a href="manage.order.php?id=<?= clean_page($order->getId()) ?>">View Order</a> /</li>
    <li class="end">Contact Customer</li>
</ul>

<h1>Contact Customer</h1>

<?php

require_once 'tabnav.php';

if (!empty($errors)) {
    showerrors($errors);
}
$hideForm = false;
if (empty($errors) && isset($_REQUEST['action'])) {
    echo showmsg("Message Sent to Customer<br /><a href='/shop/admin/orders/manage.order.php?id=" . clean_page($_REQUEST['id']) . "'>Return to order</a>", "success", $path);
    $hideForm = true;
}

?>

<?php
if (!$hideForm) {
?>

    <form method="post" name="messagefrm" id="messagefrm" class="style">
        <div class="row">
            <label>To:</label>
            <?= clean_page($order->address['billing']['firstname']) . ' ' . clean_page($order->address['billing']['lastname']) . ' (' . clean_page($order->info['email']) . ')' ?>
        </div>
        <div class="row">
            <label>From:</label>
            <?= config('app.name') ?> (<?= config('site.from_email') ?>)
        </div>

        <div class="row">
            <label for="subject">Subject: </label>
            <select name="subject" id="subject" onchange="document.messagefrm.submit();">
                <?php

                $standardTemplateLetters = StandardTemplateLetter::all();

                foreach ($standardTemplateLetters as $letter) {
                    $data = $letter->toArray();
                ?>
                    <option value="<?= clean_page($data['title']) ?>" <?= ($subject == $data['title']) ? 'selected' : '' ?>>
                        <?= clean_page($data['title']) ?>
                    </option>
                <?php
                }
                ?>
                <option value="custom" <?= $subject == 'custom' || (empty($subject)) ? 'selected' : '' ?>>
                    Custom
                </option>
            </select>
        </div> <!-- .row -->

        <?php
        if ($subject == 'custom' || empty($subject)) {
        ?>
            <div class="row">
                <label>Subject Line</label>
                <input type="text" name="subject_other" id="subject_other" value="<?= clean_page($subject_other) ?>" />
            </div>

        <?php
        }
        ?>

        <div class="row">
            <label for="emailmessage">Message</label>
            <?php
                $standardTemplateLetter = StandardTemplateLetter::query()
                    ->where('title', $subject)
                    ->first();

                if (!empty($standardTemplateLetter)) {
                    $message = $standardTemplateLetter->template;
                }

            ?>
            <textarea name="message" id="emailmessage" style="width:485px; height:300px;"><?= clean_page($message) ?></textarea>
        </div>

        <input type="submit" name="action" value="Send" class="button"/>
        <input type="hidden" name="id" value="<?= clean_page($_REQUEST['id']) ?>" />

    </form>

<?php
}

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