<?php

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

use Mtc\Modules\B2B\Enums\AccountOrderStatus;
use Mtc\Modules\B2B\Events\AccountOrderPaidEvent;
use Mtc\Modules\B2B\Models\AccountOrder;

$page_meta['title'] = 'Account Orders';

init_request_values([
    'action' => null,
    'id' => null,
    'status' => null,
    'search' => null,
    'date_from' => null,
    'date_to' => null,
]);

$errors = [];
$success = '';

// Handle mark as paid
if ($_REQUEST['action'] === 'mark_paid' && is_numeric($_REQUEST['id'])) {
    if (!CSRF::checkToken('b2b_mark_paid')) {
        $errors[] = 'Invalid request. Please try again.';
    } else {
        $order = AccountOrder::with('tradeCustomer.member')->find($_REQUEST['id']);
        if ($order && $order->status === AccountOrderStatus::Unpaid) {
            $paymentReference = $_POST['payment_reference'] ?? '';
            $order->markPaid('manual', $paymentReference, $_SESSION['adminId'] ?? null);

            AccountOrderPaidEvent::dispatch($order->load('tradeCustomer'));

            $success = "Order {$order->po_number} marked as paid";
        }
    }
}

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

<ul class="breadcrumbs el">
    <li><a href="/admin/">Home</a> /</li>
    <li class="end">Account Orders</li>
</ul>

<h1>Account Orders</h1>

<?php include __DIR__ . '/tabnav.php'; ?>

<?php
if (!empty($errors)) {
    showerrors($errors);
}
if (!empty($success)) {
    showmsg($success, 'success', $path);
}

$query = AccountOrder::with(['tradeCustomer', 'order']);

if (!empty($_REQUEST['status'])) {
    $query->where('status', $_REQUEST['status']);
}
if (!empty($_REQUEST['search'])) {
    $search = $_REQUEST['search'];
    $query->where(function ($q) use ($search) {
        $q->where('po_number', 'like', "%{$search}%")
          ->orWhereHas('tradeCustomer', function ($tq) use ($search) {
              $tq->where('company_name', 'like', "%{$search}%");
          });
    });
}
if (!empty($_REQUEST['date_from'])) {
    $query->where('created_at', '>=', $_REQUEST['date_from']);
}
if (!empty($_REQUEST['date_to'])) {
    $query->where('created_at', '<=', $_REQUEST['date_to'] . ' 23:59:59');
}

$orders = $query->orderBy('created_at', 'desc')->paginate(25);
$orders->appends($_GET);
?>

<form method="get" class="style">
    <fieldset class="show">
        <h1><a class="show el">Filter <i class="fa fa-caret-right"></i></a></h1>
        <div class="row">
            <label for="status">Status</label>
            <select name="status" id="status">
                <option value="">All Statuses</option>
                <option value="<?= AccountOrderStatus::Unpaid->value ?>" <?= $_REQUEST['status'] === AccountOrderStatus::Unpaid->value ? 'selected' : '' ?>>Unpaid</option>
                <option value="<?= AccountOrderStatus::Paid->value ?>" <?= $_REQUEST['status'] === AccountOrderStatus::Paid->value ? 'selected' : '' ?>>Paid</option>
            </select>
        </div>
        <div class="row">
            <label for="search">Search</label>
            <input type="text" name="search" id="search" class="text" value="<?= clean_page($_REQUEST['search'] ?? '') ?>" placeholder="PO number or company...">
        </div>
        <div class="row">
            <label for="date_from">Date From</label>
            <input type="date" name="date_from" id="date_from" class="text" value="<?= clean_page($_REQUEST['date_from'] ?? '') ?>">
        </div>
        <div class="row">
            <label for="date_to">Date To</label>
            <input type="date" name="date_to" id="date_to" class="text" value="<?= clean_page($_REQUEST['date_to'] ?? '') ?>">
        </div>
        <div class="row">
            <input type="submit" value="Filter" class="btn">
            <a href="orders.php" class="btn cancel">Reset</a>
        </div>
    </fieldset>
</form>

<?php if ($orders->total() > 0) { ?>
<table class="manage-items">
    <thead>
        <tr>
            <th>PO Number</th>
            <th>Order Ref</th>
            <th>Company</th>
            <th>Amount</th>
            <th>Status</th>
            <th>Date</th>
            <th>Actions</th>
        </tr>
    </thead>
    <tbody class="tabular">
        <?php foreach ($orders as $order) { ?>
        <tr>
            <td><?= clean_page($order->po_number) ?></td>
            <td><?= $order->order ? '<a href="/shop/admin/orders/manage.order.php?id=' . $order->order->id . '">' . $order->order->id . '</a>' : '-' ?></td>
            <td><?= $order->tradeCustomer ? clean_page($order->tradeCustomer->company_name) : '-' ?></td>
            <td>&pound;<?= number_format($order->amount_due, 2) ?></td>
            <td><?= htmlspecialchars(ucfirst($order->status->value)) ?></td>
            <td><?= $order->created_at ? $order->created_at->format('d/m/Y') : '-' ?></td>
            <td>
                <?php if ($order->status === AccountOrderStatus::Unpaid) { ?>
                    <form method="post" action="?action=mark_paid&id=<?= $order->id ?>">
                        <?= CSRF::token('b2b_mark_paid') ?>
                        <input type="text" name="payment_reference" class="short" placeholder="Ref (optional)">
                        <button type="submit" class="btn btn-smaller" onclick="return confirm('Mark this order as paid?')">Mark Paid</button>
                    </form>
                <?php } else { ?>
                    <span title="Paid: <?= $order->paid_at ? $order->paid_at->format('d/m/Y H:i') : '' ?>">Paid</span>
                    <?php if ($order->payment_reference) { ?>
                        <br><small>Ref: <?= clean_page($order->payment_reference) ?></small>
                    <?php } ?>
                <?php } ?>
            </td>
        </tr>
        <?php } ?>
    </tbody>
</table>

<?= $orders->render() ?>

<?php } else { ?>
    <p>No account orders found.</p>
<?php } ?>

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