<?php
require __DIR__ . '/_auth.php';
require_admin();
$pdo = db();
$title = 'View Order';

if (!$pdo) {
    admin_redirect('orders.php');
}

$id = (int) (isset($_GET['id']) ? $_GET['id'] : 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (verify_csrf_token((string) (isset($_POST['csrf_token']) ? $_POST['csrf_token'] : ''))) {
        $newStatus = clean_text((string) (isset($_POST['status']) ? $_POST['status'] : ''), 80);
        $paymentStatus = clean_text((string) (isset($_POST['payment_status']) ? $_POST['payment_status'] : ''), 80);
        $paymentReference = clean_text((string) (isset($_POST['payment_reference']) ? $_POST['payment_reference'] : ''), 140);
        $paymentLink = trim((string) (isset($_POST['payment_link']) ? $_POST['payment_link'] : ''));
        $paymentLink = function_exists('mb_substr') ? mb_substr($paymentLink, 0, 500) : substr($paymentLink, 0, 500);
        $amountPaid = (float) (isset($_POST['amount_paid']) ? $_POST['amount_paid'] : 0);
        if ($amountPaid < 0) {
            $amountPaid = 0;
        }

        $currentStmt = $pdo->prepare('SELECT total FROM orders WHERE id = ? LIMIT 1');
        $currentStmt->execute(array($id));
        $current = $currentStmt->fetch();
        $balanceDue = $current ? payment_balance((float) $current['total'], $amountPaid) : 0;

        if ($newStatus !== '' && in_array($paymentStatus, payment_status_options(), true)) {
            $stmt = $pdo->prepare('UPDATE orders SET status = ?, payment_status = ?, payment_reference = ?, payment_link = ?, amount_paid = ?, balance_due = ? WHERE id = ?');
            $stmt->execute(array($newStatus, $paymentStatus, $paymentReference, $paymentLink, $amountPaid, $balanceDue, $id));
        }
    }
    admin_redirect('order-view.php?id=' . $id);
}

$stmt = $pdo->prepare('SELECT * FROM orders WHERE id = ? LIMIT 1');
$stmt->execute(array($id));
$order = $stmt->fetch();
if (!$order) {
    admin_redirect('orders.php');
}

$itemStmt = $pdo->prepare('SELECT * FROM order_items WHERE order_id = ? ORDER BY id ASC');
$itemStmt->execute(array($id));
$items = $itemStmt->fetchAll();
$statusOptions = array('Pending quotation', 'Awaiting Payment', 'Confirmed', 'Preparing', 'For Delivery', 'Delivered', 'Cancelled');
$paymentStatusOptions = payment_status_options();
$amountPaid = isset($order['amount_paid']) ? (float) $order['amount_paid'] : 0;
$balanceDue = isset($order['balance_due']) ? (float) $order['balance_due'] : payment_balance((float) $order['total'], $amountPaid);
$proofPath = isset($order['payment_proof_path']) ? trim((string) $order['payment_proof_path']) : '';

require __DIR__ . '/_header.php';
?>
<div class="row g-4">
    <div class="col-lg-8">
        <div class="admin-card p-4 mb-4">
            <div class="d-flex justify-content-between align-items-start mb-4">
                <div>
                    <p class="eyebrow mb-1">Order reference</p>
                    <h1 class="h3 mb-1"><?= e($order['order_number']) ?></h1>
                    <p class="admin-muted mb-0"><?= e(date('M d, Y h:i A', strtotime($order['created_at']))) ?></p>
                </div>
                <div class="text-end">
                    <span class="badge badge-soft fs-6"><?= e($order['status']) ?></span><br>
                    <span class="badge badge-soft mt-2"><?= e(isset($order['payment_status']) ? $order['payment_status'] : 'Unpaid') ?></span>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table align-middle admin-table">
                    <thead><tr><th>Item</th><th>Qty</th><th>Price</th><th>Total</th></tr></thead>
                    <tbody>
                    <?php foreach ($items as $item): ?>
                        <tr>
                            <td>
                                <div class="d-flex gap-3 align-items-center">
                                    <?php if ($item['image']): ?><img src="../<?= e($item['image']) ?>" alt=""><?php endif; ?>
                                    <div><strong><?= e($item['name']) ?></strong><br><span class="small admin-muted"><?= e($item['dimensions']) ?></span></div>
                                </div>
                            </td>
                            <td><?= (int) $item['qty'] ?></td>
                            <td><?= money($item['price']) ?></td>
                            <td><?= money($item['line_total']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                    <tfoot><tr><th colspan="3" class="text-end">Total</th><th><?= money($order['total']) ?></th></tr></tfoot>
                </table>
            </div>
        </div>

        <div class="admin-card p-4 mb-4">
            <h2 class="h5">Payment verification</h2>
            <div class="row g-3 mb-3">
                <div class="col-md-4"><span class="admin-muted small">Method</span><strong class="d-block"><?= e($order['payment_method']) ?></strong></div>
                <div class="col-md-4"><span class="admin-muted small">Amount paid</span><strong class="d-block"><?= money($amountPaid) ?></strong></div>
                <div class="col-md-4"><span class="admin-muted small">Balance due</span><strong class="d-block"><?= money($balanceDue) ?></strong></div>
            </div>
            <?php if (!empty($order['payment_reference'])): ?>
                <p><strong>Reference:</strong> <?= e($order['payment_reference']) ?></p>
            <?php endif; ?>
            <?php if ($proofPath !== ''): ?>
                <p><a class="btn btn-sm btn-outline-primary" href="payment-proof.php?id=<?= (int) $order['id'] ?>" target="_blank" rel="noopener"><i class="bi bi-receipt" aria-hidden="true"></i> View payment proof</a></p>
            <?php else: ?>
                <p class="admin-muted">No payment proof uploaded yet.</p>
            <?php endif; ?>
            <?php if (!empty($order['payment_link'])): ?>
                <p><a class="btn btn-sm btn-primary" href="<?= e($order['payment_link']) ?>" target="_blank" rel="noopener"><i class="bi bi-credit-card" aria-hidden="true"></i> Open payment link</a></p>
            <?php endif; ?>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="admin-card p-4 mb-4">
            <h2 class="h5">Customer</h2>
            <dl class="mb-0">
                <dt>Name</dt><dd><?= e($order['customer_name']) ?></dd>
                <dt>Phone</dt><dd><a href="tel:<?= e(preg_replace('/[^+0-9]/', '', $order['customer_phone'])) ?>"><?= e($order['customer_phone']) ?></a></dd>
                <dt>Email</dt><dd><a href="mailto:<?= e($order['customer_email']) ?>"><?= e($order['customer_email']) ?></a></dd>
                <dt>City</dt><dd><?= e($order['customer_city']) ?></dd>
                <dt>Address</dt><dd><?= e($order['customer_address']) ?></dd>
                <dt>Delivery</dt><dd><?= e($order['delivery_method']) ?></dd>
                <?php if ($order['message']): ?><dt>Notes</dt><dd><?= nl2br(e($order['message'])) ?></dd><?php endif; ?>
            </dl>
        </div>
        <div class="admin-card p-4">
            <h2 class="h5">Update order and payment</h2>
            <form method="post">
                <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
                <label class="form-label" for="status">Order status</label>
                <select class="form-select mb-3" id="status" name="status">
                    <?php foreach ($statusOptions as $option): ?>
                        <option value="<?= e($option) ?>" <?= $order['status'] === $option ? 'selected' : '' ?>><?= e($option) ?></option>
                    <?php endforeach; ?>
                </select>
                <label class="form-label" for="payment_status">Payment status</label>
                <select class="form-select mb-3" id="payment_status" name="payment_status">
                    <?php foreach ($paymentStatusOptions as $option): ?>
                        <option value="<?= e($option) ?>" <?= (isset($order['payment_status']) && $order['payment_status'] === $option) ? 'selected' : '' ?>><?= e($option) ?></option>
                    <?php endforeach; ?>
                </select>
                <label class="form-label" for="amount_paid">Amount paid</label>
                <input class="form-control mb-3" type="number" step="0.01" min="0" id="amount_paid" name="amount_paid" value="<?= e($amountPaid) ?>">
                <label class="form-label" for="payment_reference">Payment reference</label>
                <input class="form-control mb-3" type="text" id="payment_reference" name="payment_reference" maxlength="140" value="<?= e(isset($order['payment_reference']) ? $order['payment_reference'] : '') ?>">
                <label class="form-label" for="payment_link">Payment link</label>
                <input class="form-control mb-3" type="url" id="payment_link" name="payment_link" maxlength="500" value="<?= e(isset($order['payment_link']) ? $order['payment_link'] : '') ?>" placeholder="Paste PayMongo/Maya/Xendit link">
                <button class="btn btn-primary w-100" type="submit">Save Changes</button>
                <p class="small admin-muted mt-3 mb-0">For card payments, create a secure payment link from your chosen gateway and paste it here. Send the link to the customer via chat/email.</p>
            </form>
        </div>
    </div>
</div>
<?php require __DIR__ . '/_footer.php'; ?>
