<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyName    = Branding::companyName();
$companyLogo    = Branding::logoUrl();
$companyLogoFile = Branding::logoFilePath();
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Order.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Inventory.php';
require_once __DIR__ . '/../../includes/payment_options.php';

$database  = new Database();
$conn      = $database->getConnection();
$auth      = new Auth($conn);
$orderObj  = new Order($conn);
$branch    = new Branch($conn);
$inventory = new Inventory($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

$orderId   = isset($_GET['order_id']) ? (int)$_GET['order_id'] : 0;
$orderData = [];
try {
    $orderData = $orderObj->getOrderById($orderId) ?? [];
} catch (Exception $e) {
    error_log("Error fetching order: " . $e->getMessage());
    header('Location: list_orders.php?error=' . urlencode('Database error: ' . $e->getMessage()));
    exit();
}

if (!$orderData) {
    header('Location: list_orders.php?error=' . urlencode('Order not found.'));
    exit();
}

$branchId           = $orderData['branch_id'] ?? null;
$orderBranding      = Branding::documentDetailsForBranchId($conn, (int)$branchId);
$companyName        = $orderBranding['name'];
$companyLogo        = $orderBranding['logo'];
$companyLogoFile    = $orderBranding['logo_file'];
$companyContactLine = Branding::contactLine($orderBranding, ' • ');
$isSuperAdmin       = $auth->isSuperAdmin($_SESSION['user_id']);
$isController       = method_exists($auth, 'isController') && $auth->isController($_SESSION['user_id']);
$userBranchId       = $auth->getUserBranch($_SESSION['user_id']);
$isUserAssignedBranch = ((int)$branchId === (int)$userBranchId) || $isSuperAdmin;

// Payment data
$payments  = $orderObj->getPayments($orderId);
$totalPaid = $orderObj->getTotalPaid($orderId);
$price     = round((float)($orderData['price'] ?? 0), 2);
$balance   = round($price - $totalPaid, 2);
$isFullyPaid = $balance <= 0.009;

// Who may assign the completion code: controllers/superadmins always; a branch
// user assigned to this order's branch only once the order is fully paid.
$canAssignCode = $isController || $isSuperAdmin || ($isUserAssignedBranch && $isFullyPaid);

// Available (in-stock, unsold) items for this order's branch, for the code picker —
// same source (Inventory::getDetailedItems()) used by the stock browser on create_sale.php.
$availableItems = [];
if ($canAssignCode && empty($orderData['assigned_code'])) {
    $availableItems = $inventory->getDetailedItems($branchId);
}

// Status helper
function getStatus($delivery_date, $status) {
    $now = new DateTime();
    $d   = new DateTime($delivery_date);
    if ($now > $d && $status === 'pending') return 'overdue';
    return $status;
}
$status = getStatus($orderData['delivery_date'], $orderData['status']);

$statusColors = [
    'pending'   => 'warning',
    'approved'  => 'info',
    'rejected'  => 'danger',
    'delivered' => 'primary',
    'completed' => 'success',
    'overdue'   => 'danger',
];
$statusColor = $statusColors[$status] ?? 'secondary';
?>
<?php include __DIR__ . '/../../includes/header.php'; ?>
    <style>
        /* ── Google Font (matches create_order.php / edit_sale.php) ── */
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap');

        *, *::before, *::after { box-sizing: border-box; }
        :root {
            --brand:          #4F46E5;
            --brand-dark:     #3730A3;
            --brand-light:    #EEF2FF;
            --brand-ring:     rgba(79,70,229,.18);

            --success:        #059669;
            --success-bg:     #ECFDF5;
            --success-border: #A7F3D0;
            --danger:         #DC2626;
            --danger-bg:      #FEF2F2;
            --danger-border:  #FECACA;
            --warning:        #D97706;
            --warning-bg:     #FFFBEB;
            --warning-border: #FDE68A;
            --info:           #0284C7;
            --info-bg:        #E0F2FE;

            --n900: #0F172A; --n800: #1E293B; --n700: #334155; --n600: #475569;
            --n500: #64748B; --n400: #94A3B8; --n300: #CBD5E1; --n200: #E2E8F0;
            --n100: #F1F5F9; --n50:  #F8FAFC; --white: #FFFFFF;

            --topbar-h: 58px;
            --r-sm: 6px; --r: 10px; --r-lg: 14px;
            --s1: 0 1px 2px rgba(0,0,0,.05);
            --s2: 0 1px 3px rgba(0,0,0,.07), 0 1px 2px rgba(0,0,0,.04);
            --s3: 0 4px 6px -1px rgba(0,0,0,.07), 0 2px 4px -1px rgba(0,0,0,.04);
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            color: var(--n800);
            background: var(--n100);
            -webkit-font-smoothing: antialiased;
        }

        /* ── Top Bar ─────────────────────────────────── */
        .pos-topbar {
            display: flex; align-items: center; justify-content: space-between;
            background: var(--n900); color: var(--white);
            min-height: var(--topbar-h);
            position: sticky; top: 0; z-index: 300;
            border-bottom: 3px solid var(--brand);
            padding: 10px 20px; margin: 0 -15px 24px; gap: 12px; flex-wrap: wrap;
        }
        .pos-topbar-left { display: flex; align-items: center; gap: 12px; min-width: 0; }
        .pos-topbar .brand-icon {
            width: 32px; height: 32px; border-radius: var(--r-sm);
            background: var(--brand); display: flex; align-items: center;
            justify-content: center; font-size: 14px; color: #fff; flex-shrink: 0;
        }
        .pos-topbar-title-wrap { line-height: 1.25; min-width: 0; }
        .pos-topbar-title {
            font-size: .92rem; font-weight: 700; color: var(--white);
            overflow: hidden; text-overflow: ellipsis; white-space: nowrap; display: block;
        }
        .pos-topbar-sub { font-size: .74rem; color: var(--n400); }
        .pos-topbar-right { display: flex; align-items: center; gap: 10px; flex-shrink: 0; }
        .pos-back {
            display: flex; align-items: center; gap: 6px;
            color: var(--n400); text-decoration: none; font-size: .78rem; font-weight: 500;
            padding: 6px 12px; border-radius: var(--r-sm);
            border: 1px solid rgba(255,255,255,.1);
            transition: all .15s; white-space: nowrap;
        }
        .pos-back:hover { background: rgba(255,255,255,.08); color: var(--white); border-color: rgba(255,255,255,.2); }
        .status-pill {
            font-size: .72rem; font-weight: 700; padding: 5px 12px; border-radius: 20px;
            text-transform: uppercase; letter-spacing: .04em;
        }
        .status-pill.badge-warning   { background: var(--warning-bg); color: var(--warning); }
        .status-pill.badge-info      { background: var(--info-bg); color: var(--info); }
        .status-pill.badge-danger    { background: var(--danger-bg); color: var(--danger); }
        .status-pill.badge-primary   { background: var(--brand-light); color: var(--brand); }
        .status-pill.badge-success   { background: var(--success-bg); color: var(--success); }
        .status-pill.badge-secondary { background: var(--n200); color: var(--n600); }

        /* ── Page wrap ───────────────────────────────── */
        .page-wrap { max-width: 900px; margin: 0 auto 60px; padding: 0 5px; }

        /* ── Letterhead strip (company details, compact) ── */
        .letterhead {
            background: var(--white); border-radius: var(--r); border: 1px solid var(--n200);
            box-shadow: var(--s2); padding: 16px 20px; margin-bottom: 18px;
            display: flex; align-items: center; gap: 14px; flex-wrap: wrap;
        }
        .letterhead img { max-height: 40px; flex-shrink: 0; }
        .letterhead-name { font-size: 1rem; font-weight: 800; color: var(--n900); letter-spacing: -.01em; }
        .letterhead-detail { font-size: .74rem; color: var(--n500); line-height: 1.5; }

        /* ── Section card ────────────────────────────── */
        .pos-card {
            background: var(--white); border-radius: var(--r);
            padding: 18px 20px; box-shadow: var(--s2);
            border: 1px solid var(--n200); margin-bottom: 18px;
        }
        .pos-card.accent-green  { border-left: 4px solid var(--success); }
        .pos-card.accent-orange { border-left: 4px solid var(--warning); }
        .pos-card.accent-purple { border-left: 4px solid #9333EA; }
        .pos-card.accent-grey   { border-left: 4px solid var(--n400); }
        .pos-card-title {
            display: flex; align-items: center; gap: 8px;
            font-size: .95rem; font-weight: 700; color: var(--n800);
            margin-bottom: 16px;
        }
        .pos-card-title .icon-badge {
            width: 26px; height: 26px; border-radius: 50%;
            background: var(--brand-light); color: var(--brand);
            display: flex; align-items: center; justify-content: center;
            font-size: .72rem; flex-shrink: 0;
        }
        .pos-card-title .icon-badge.green  { background: var(--success-bg); color: var(--success); }
        .pos-card-title .icon-badge.orange { background: var(--warning-bg); color: var(--warning); }
        .pos-card-title .icon-badge.purple { background: #F3E8FF; color: #9333EA; }
        .pos-card-title .icon-badge.grey   { background: var(--n100); color: var(--n500); }
        .pos-card-title .count-note { font-size: .78rem; color: var(--n500); font-weight: 500; }

        /* ── Info grid ───────────────────────────────── */
        .info-grid {
            display: grid; grid-template-columns: repeat(auto-fit, minmax(210px, 1fr)); gap: 16px;
        }
        .info-item.full { grid-column: 1 / -1; }
        .info-label {
            font-size: .68rem; font-weight: 700; color: var(--n500);
            text-transform: uppercase; letter-spacing: .06em; margin-bottom: 4px;
            display: flex; align-items: center; gap: 5px;
        }
        .info-value { font-size: .88rem; color: var(--n800); }

        /* ── Payment summary tiles ───────────────────── */
        .summary-bar { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-bottom: 16px; }
        .summary-tile {
            background: var(--n50); border-radius: var(--r-sm); padding: 14px 16px;
            text-align: center; border-top: 3px solid var(--n300);
        }
        .summary-tile.total   { border-top-color: var(--brand); }
        .summary-tile.paid    { border-top-color: var(--success); }
        .summary-tile.balance { border-top-color: var(--danger); }
        .summary-tile.balance.is-paid { border-top-color: var(--success); }
        .summary-label { font-size: .68rem; font-weight: 700; color: var(--n500); text-transform: uppercase; letter-spacing: .05em; }
        .summary-value { font-size: 1.25rem; font-weight: 800; margin-top: 3px; color: var(--n900); }
        .summary-tile.paid .summary-value { color: var(--success); }
        .summary-tile.balance .summary-value { color: var(--danger); }
        .summary-tile.balance.is-paid .summary-value { color: var(--success); }

        /* ── Payments table ──────────────────────────── */
        .payments-table { width: 100%; border-collapse: collapse; }
        .payments-table th {
            font-size: .68rem; font-weight: 700; color: var(--n500);
            text-transform: uppercase; letter-spacing: .05em;
            padding: 8px 10px; border-bottom: 2px solid var(--n200); text-align: left;
        }
        .payments-table td { padding: 10px; font-size: .84rem; color: var(--n700); border-bottom: 1px solid var(--n100); }
        .payments-table tr:last-child td { border-bottom: none; }
        .badge-method {
            display: inline-block; background: var(--success-bg); color: var(--success);
            border-radius: 20px; padding: 2px 9px; font-size: .72rem; font-weight: 600;
        }
        .badge-deposit {
            display: inline-block; background: var(--info-bg); color: var(--info);
            border-radius: 20px; padding: 2px 7px; font-size: .66rem; font-weight: 600; margin-left: 4px;
        }
        .no-payments { font-size: .84rem; color: var(--n400); font-style: italic; text-align: center; padding: 16px; }

        /* ── Notices ─────────────────────────────────── */
        .notice {
            border-radius: var(--r-sm); padding: 11px 15px; font-size: .84rem;
            margin-bottom: 16px; display: flex; align-items: center; gap: 8px;
        }
        .notice.warn    { background: var(--warning-bg); border: 1px solid var(--warning-border); color: #92400E; }
        .notice.ok      { background: var(--success-bg); border: 1px solid var(--success-border); color: #065F46; }

        /* ── Completion form ─────────────────────────── */
        .completion-form label {
            font-size: .72rem; font-weight: 700; color: var(--n500);
            text-transform: uppercase; letter-spacing: .04em; margin-bottom: 5px; display: block;
        }
        .completion-form .form-control {
            border: 1.5px solid var(--n300); border-radius: var(--r-sm);
            padding: 9px 13px; font-size: .88rem; font-family: 'Inter', sans-serif;
        }
        .completion-form .form-control:focus {
            border-color: var(--brand); box-shadow: 0 0 0 3px var(--brand-ring); outline: none;
        }

        /* ── Assigned code display ───────────────────── */
        .assigned-code-display {
            background: linear-gradient(135deg, var(--n900) 0%, var(--n800) 100%);
            color: #fff; border-radius: var(--r-lg); padding: 20px 22px;
            display: flex; align-items: center; justify-content: space-between;
            margin-bottom: 16px; flex-wrap: wrap; gap: 12px;
            box-shadow: 0 8px 24px rgba(15,23,42,.18); position: relative; overflow: hidden;
        }
        .assigned-code-display::before {
            content: ''; position: absolute; top: -30px; right: -30px;
            width: 120px; height: 120px; border-radius: 50%;
            background: radial-gradient(circle, rgba(79,70,229,.25) 0%, transparent 70%);
            pointer-events: none;
        }
        .code-label-sm { font-size: .68rem; opacity: .75; text-transform: uppercase; letter-spacing: .08em; position: relative; }
        .code-value { font-size: 1.7rem; font-weight: 800; font-family: 'JetBrains Mono', monospace; letter-spacing: .1em; margin-top: 2px; position: relative; }
        .code-meta { text-align: right; position: relative; }
        .code-meta .meta-label { font-size: .66rem; opacity: .7; text-transform: uppercase; letter-spacing: .06em; }
        .code-meta .meta-value { font-size: .84rem; font-weight: 700; margin-top: 2px; font-family: monospace; }
        .code-meta .meta-date { font-size: .74rem; opacity: .7; margin-top: 6px; }

        /* ── Buttons ─────────────────────────────────── */
        .btn-action {
            padding: 9px 18px; border: none; border-radius: var(--r-sm);
            font-size: .84rem; font-weight: 600; cursor: pointer; transition: all .15s;
            text-decoration: none; display: inline-flex; align-items: center; gap: 7px;
        }
        .btn-primary-c   { background: var(--brand); color: #fff; }
        .btn-primary-c:hover   { background: var(--brand-dark); color: #fff; }
        .btn-secondary-c { background: var(--n200); color: var(--n700); }
        .btn-secondary-c:hover { background: var(--n300); color: var(--n800); }
        .btn-danger-c    { background: var(--danger); color: #fff; }
        .btn-danger-c:hover    { background: #B91C1C; color: #fff; }
        .btn-success-c   { background: var(--success); color: #fff; }
        .btn-success-c:hover   { background: #047857; color: #fff; }
        .btn-warning-c   { background: var(--warning); color: #fff; }
        .btn-warning-c:hover   { background: #B45309; color: #fff; }
        .btn-receipt-c   { background: #9333EA; color: #fff; }
        .btn-receipt-c:hover   { background: #7E22CE; color: #fff; }
        .btn-action:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0,0,0,.15); text-decoration: none; }

        .action-bar {
            display: flex; justify-content: space-between; align-items: center;
            flex-wrap: wrap; gap: 12px; padding-top: 18px; border-top: 1px solid var(--n200); margin-top: 6px;
        }
        .action-bar-right { display: flex; gap: 10px; flex-wrap: wrap; }

        .alert { border-radius: var(--r-sm); padding: 12px 16px; margin-bottom: 18px; display: flex; align-items: center; gap: 10px; font-size: .88rem; }
        .alert-success { background: var(--success-bg); color: #065F46; border: 1px solid var(--success-border); }
        .alert-danger  { background: var(--danger-bg); color: #991B1B; border: 1px solid var(--danger-border); }

        @media (max-width: 768px) {
            .summary-bar { grid-template-columns: 1fr; }
            .action-bar { flex-direction: column; align-items: flex-start; }
        }

        /* ── Stock picker modal ──────────────────────── */
        #stockPickerModal .modal-content {
            border: none; border-radius: var(--r-lg); overflow: hidden;
            box-shadow: 0 20px 60px rgba(0,0,0,.25);
        }
        #stockPickerModal .modal-header {
            background: var(--n900); color: #fff; border-bottom: 3px solid var(--brand);
            padding: 16px 22px;
        }
        #stockPickerModal .modal-title { font-size: .95rem; font-weight: 700; display: flex; align-items: center; gap: 8px; }
        #stockPickerModal .modal-title::before {
            content: '\f468'; font-family: 'Font Awesome 6 Free'; font-weight: 900;
            color: var(--brand); font-size: .85rem;
        }
        #stockPickerModal .btn-close { filter: invert(1) grayscale(1) brightness(2); opacity: .8; }
        #stockPickerModal .btn-close:hover { opacity: 1; }
        #stockPickerModal .modal-body { padding: 20px 22px; background: var(--n50); }
        #assignedUniqueCode:focus { border-color: var(--brand); box-shadow: 0 0 0 3px var(--brand-ring); }
        #browseStockCodeBtn {
            border-color: var(--n300); color: var(--n600); font-weight: 600; font-size: .82rem;
        }
        #browseStockCodeBtn:hover { background: var(--brand-light); color: var(--brand); border-color: var(--brand); }

        .stock-picker-table { width: 100%; border-collapse: collapse; background: var(--white); border-radius: var(--r-sm); overflow: hidden; }
        .stock-picker-table thead th {
            background: var(--n900); color: var(--n300); font-size: .68rem; font-weight: 700;
            text-transform: uppercase; letter-spacing: .05em; padding: 10px 12px; border: none; text-align: left;
        }
        .stock-picker-table tbody td { padding: 10px 12px; font-size: .84rem; color: var(--n700); border-bottom: 1px solid var(--n100); }
        .stock-picker-table tbody tr { cursor: pointer; transition: background .12s; }
        .stock-picker-table tbody tr:hover { background: var(--brand-light); }
        .stock-picker-table tbody tr:hover td { color: var(--brand-dark); }
        .stock-picker-table tbody tr:last-child td { border-bottom: none; }
        #stockPickerModal .dataTables_wrapper .dataTables_filter input,
        #stockPickerModal .dataTables_wrapper .dataTables_length select {
            border: 1.5px solid var(--n300); border-radius: var(--r-sm); padding: 5px 10px; font-size: .82rem;
        }
        #stockPickerModal .dataTables_wrapper .dataTables_filter input:focus { outline: none; border-color: var(--brand); }
        #stockPickerModal .page-link { color: var(--brand); }
        #stockPickerModal .page-item.active .page-link { background: var(--brand); border-color: var(--brand); }
    </style>

    <div class="pos-topbar">
        <div class="pos-topbar-left">
            <div class="brand-icon"><i class="fas fa-file-invoice"></i></div>
            <div class="pos-topbar-title-wrap">
                <span class="pos-topbar-title">Order #<?php echo htmlspecialchars($orderData['order_number'] ?? 'N/A'); ?></span>
                <span class="pos-topbar-sub"><?php echo htmlspecialchars($orderData['customer_name'] ?? ''); ?></span>
            </div>
        </div>
        <div class="pos-topbar-right">
            <span class="status-pill badge-<?php echo $statusColor; ?>"><?php echo ucfirst($status); ?></span>
            <a href="list_orders.php?branch_id=<?php echo $branchId; ?>" class="pos-back"><i class="fas fa-arrow-left"></i> Back to Orders</a>
        </div>
    </div>

    <div class="page-wrap">

        <div class="letterhead">
            <?php if ($companyLogoFile && file_exists($companyLogoFile)): ?>
                <img src="<?php echo htmlspecialchars($companyLogo); ?>" alt="Logo">
            <?php endif; ?>
            <div>
                <div class="letterhead-name"><?php echo htmlspecialchars($companyName); ?></div>
                <div class="letterhead-detail">
                    <?php echo htmlspecialchars($companyContactLine); ?>
                </div>
            </div>
        </div>

        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success"><i class="fas fa-check-circle"></i><?php echo htmlspecialchars(urldecode($_GET['success'])); ?></div>
        <?php elseif (isset($_GET['error'])): ?>
            <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i><?php echo htmlspecialchars(urldecode($_GET['error'])); ?></div>
        <?php endif; ?>

        <!-- Order Info -->
        <div class="pos-card">
            <div class="pos-card-title">
                <div class="icon-badge"><i class="fas fa-box"></i></div>
                Order Information
            </div>
            <div class="info-grid">
                <div class="info-item">
                    <div class="info-label"><i class="fas fa-box"></i> Item Name</div>
                    <div class="info-value"><?php echo htmlspecialchars($orderData['item_name'] ?? 'N/A'); ?></div>
                </div>
                <div class="info-item">
                    <div class="info-label"><i class="fas fa-tag"></i> Order Price</div>
                    <div class="info-value"><strong>MWK <?php echo number_format($price, 2); ?></strong></div>
                </div>
                <div class="info-item full">
                    <div class="info-label"><i class="fas fa-building"></i> Customer / Company</div>
                    <div class="info-value"><?php echo htmlspecialchars($orderData['customer_name'] ?? 'N/A'); ?></div>
                </div>
                <div class="info-item full">
                    <div class="info-label"><i class="fas fa-address-book"></i> Contact Details</div>
                    <div class="info-value"><?php echo nl2br(htmlspecialchars($orderData['customer_contact'] ?? 'N/A')); ?></div>
                </div>
                <div class="info-item">
                    <div class="info-label"><i class="fas fa-calendar"></i> Delivery Date</div>
                    <div class="info-value"><?php echo htmlspecialchars($orderData['delivery_date'] ?? 'N/A'); ?></div>
                </div>
                <div class="info-item">
                    <div class="info-label"><i class="fas fa-circle"></i> Status</div>
                    <div class="info-value">
                        <span class="status-pill badge-<?php echo $statusColor; ?>"><?php echo ucfirst($status); ?></span>
                    </div>
                </div>
                <div class="info-item">
                    <div class="info-label"><i class="fas fa-user"></i> Created By</div>
                    <div class="info-value"><?php echo htmlspecialchars($orderData['created_by_name'] ?? 'Unknown'); ?></div>
                </div>
                <div class="info-item">
                    <div class="info-label"><i class="fas fa-clock"></i> Created At</div>
                    <div class="info-value"><?php echo htmlspecialchars($orderData['created_at'] ?? 'N/A'); ?></div>
                </div>
                <?php if (!empty($orderData['notes'])): ?>
                <div class="info-item full">
                    <div class="info-label"><i class="fas fa-sticky-note"></i> Notes</div>
                    <div class="info-value"><?php echo nl2br(htmlspecialchars($orderData['notes'])); ?></div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Payment Summary -->
        <div class="pos-card accent-green">
            <div class="pos-card-title">
                <div class="icon-badge green"><i class="fas fa-money-bill-wave"></i></div>
                Payment Summary
            </div>

            <div class="summary-bar">
                <div class="summary-tile total">
                    <div class="summary-label">Order Total</div>
                    <div class="summary-value">MWK <?php echo number_format($price, 2); ?></div>
                </div>
                <div class="summary-tile paid">
                    <div class="summary-label">Total Paid</div>
                    <div class="summary-value">MWK <?php echo number_format($totalPaid, 2); ?></div>
                </div>
                <div class="summary-tile balance<?php echo $isFullyPaid ? ' is-paid' : ''; ?>">
                    <div class="summary-label"><?php echo $isFullyPaid ? 'Fully Paid' : 'Balance Due'; ?></div>
                    <div class="summary-value">MWK <?php echo number_format(max(0, $balance), 2); ?></div>
                </div>
            </div>

            <?php if ($orderData['status'] !== 'completed' && $isUserAssignedBranch && !$isFullyPaid): ?>
                <a href="add_order_payment.php?order_id=<?php echo $orderId; ?>" class="btn-action btn-success-c">
                    <i class="fas fa-plus-circle"></i> Add Payment
                </a>
            <?php elseif ($orderData['status'] !== 'completed' && $isFullyPaid): ?>
                <span style="font-size:.84rem;color:var(--success);font-weight:600;">
                    <i class="fas fa-check-circle"></i> Fully paid &mdash;
                    <?php if ($canAssignCode): ?>
                        assign one or more codes below to complete the order.
                    <?php else: ?>
                        awaiting code assignment.
                    <?php endif; ?>
                </span>
            <?php endif; ?>
        </div>

        <!-- Payment History -->
        <div class="pos-card accent-grey">
            <div class="pos-card-title">
                <div class="icon-badge grey"><i class="fas fa-list-ul"></i></div>
                Payment History
                <span class="count-note">(<?php echo count($payments); ?> record<?php echo count($payments) !== 1 ? 's' : ''; ?>)</span>
            </div>

            <?php if (!empty($payments)): ?>
            <div style="overflow-x:auto;">
                <table class="payments-table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Date &amp; Time</th>
                            <th>Amount (MWK)</th>
                            <th>Method</th>
                            <th>Notes</th>
                            <th>Recorded By</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($payments as $i => $p): ?>
                        <tr>
                            <td style="color:var(--n400);font-weight:700;"><?php echo $i + 1; ?></td>
                            <td><?php echo date('d M Y, H:i', strtotime($p['payment_date'])); ?></td>
                            <td><strong><?php echo number_format($p['amount'], 2); ?></strong></td>
                            <td><span class="badge-method"><?php echo htmlspecialchars(paymentMethodLabel($p['payment_method'])); ?></span></td>
                            <td>
                                <?php echo htmlspecialchars($p['notes'] ?? '—'); ?>
                                <?php if ($p['is_initial']): ?><span class="badge-deposit">Deposit</span><?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($p['recorded_by_name'] ?? '—'); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php else: ?>
            <div class="no-payments">No payments recorded yet for this order.</div>
            <?php endif; ?>
        </div>

        <!-- Completed Order: Show assigned code + receipt link -->
        <?php if (!empty($orderData['assigned_code'])): ?>
        <div class="pos-card accent-purple">
            <div class="pos-card-title">
                <div class="icon-badge purple"><i class="fas fa-check-double"></i></div>
                Order Completed
            </div>
            <div class="assigned-code-display">
                <div>
                    <div class="code-label-sm">Assigned Item Code(s)</div>
                    <div class="code-value"><?php echo htmlspecialchars($orderData['assigned_code']); ?></div>
                </div>
                <div class="code-meta">
                    <?php if (!empty($orderData['eis_transaction_id'])): ?>
                        <div class="meta-label">EIS Reference</div>
                        <div class="meta-value"><?php echo htmlspecialchars($orderData['eis_transaction_id']); ?></div>
                    <?php endif; ?>
                    <?php if (!empty($orderData['completed_at'])): ?>
                        <div class="meta-date">Completed <?php echo date('d M Y', strtotime($orderData['completed_at'])); ?></div>
                    <?php endif; ?>
                </div>
            </div>
            <a href="order_receipt.php?order_id=<?php echo $orderId; ?>" class="btn-action btn-receipt-c">
                <i class="fas fa-receipt"></i> View Full Receipt
            </a>
            <a href="order_receipt.php?order_id=<?php echo $orderId; ?>" class="btn-action btn-primary-c" target="_blank" rel="noopener">
                <i class="fas fa-print"></i> Print Receipt
            </a>
        </div>

        <!-- Completion Form: shown when not yet completed, for Controllers/SuperAdmins,
             or a branch user assigned to this order's branch once it's fully paid. -->
        <?php elseif ($canAssignCode): ?>
        <div class="pos-card accent-orange">
            <div class="pos-card-title">
                <div class="icon-badge orange"><i class="fas fa-barcode"></i></div>
                Complete Order &amp; Assign Code(s)
            </div>

            <?php if ($isFullyPaid): ?>
                <div class="notice ok">
                    <i class="fas fa-check-circle"></i>
                    Order is fully paid (MWK <?php echo number_format($totalPaid, 2); ?>). Enter the assigned item code(s) to finalize.
                </div>
            <?php else: ?>
                <div class="notice warn">
                    <i class="fas fa-exclamation-triangle"></i>
                    There is still an outstanding balance of <strong>MWK <?php echo number_format($balance, 2); ?></strong>.
                    You may record the final payment here, or use the Add Payment button above first.
                </div>
            <?php endif; ?>

            <form method="post" action="../dashboard/controller_action.php" class="completion-form">
                <input type="hidden" name="action" value="complete_order_code">
                <input type="hidden" name="order_id" value="<?php echo (int)$orderId; ?>">

                <div class="row">
                    <div class="col-md-7 mb-3">
                        <label><i class="fas fa-barcode me-1"></i>Assigned Item Codes and Values <span class="text-danger">*</span></label>
                        <div id="orderCodeRows">
                            <div class="row order-code-row g-2 mb-2">
                                <div class="col-md-6"><input type="text" name="unique_code[]" class="form-control assigned-code-input" placeholder="Unique code" required></div>
                                <div class="col-md-4"><input type="number" step="0.01" min="0.01" name="code_value[]" class="form-control code-value-input" value="<?php echo htmlspecialchars(number_format($price, 2, '.', '')); ?>" placeholder="Value" required></div>
                                <div class="col-md-2"><button type="button" class="btn btn-outline-danger remove-order-code" disabled>&times;</button></div>
                            </div>
                        </div>
                        <button type="button" class="btn btn-outline-secondary btn-sm" id="browseStockCodeBtn"><i class="fas fa-list"></i> Browse Stock</button>
                        <button type="button" class="btn btn-outline-primary btn-sm" id="addOrderCodeBtn"><i class="fas fa-plus"></i> Add Code</button>
                        <small class="text-muted d-block mt-1">The combined code values must equal MWK <?php echo number_format($price, 2); ?>.</small>
                    </div>

                    <?php if (!$isFullyPaid && ($isController || $isSuperAdmin)): ?>
                    <div class="col-md-4 mb-3">
                        <label><i class="fas fa-money-bill me-1"></i>Final Payment Amount</label>
                        <input type="number" step="0.01" min="0" name="final_payment_amount"
                               class="form-control" value="<?php echo $balance; ?>">
                        <small class="text-muted">Balance: MWK <?php echo number_format($balance, 2); ?></small>
                    </div>
                    <div class="col-md-3 mb-3">
                        <label><i class="fas fa-credit-card me-1"></i>Payment Method</label>
                        <select name="payment_method" class="form-control">
                            <?php echo paymentMethodSelectOptions($orderData['payment_method'] ?? 'cash'); ?>
                        </select>
                    </div>
                    <?php else: ?>
                    <input type="hidden" name="final_payment_amount" value="0">
                    <input type="hidden" name="payment_method" value="cash">
                    <?php endif; ?>
                </div>

                <button type="submit" class="btn-action btn-success-c">
                    <i class="fas fa-check-circle"></i>
                    <?php echo ($isFullyPaid || !($isController || $isSuperAdmin)) ? 'Assign Code &amp; Complete Order' : 'Record Final Payment &amp; Complete Order'; ?>
                </button>
            </form>
        </div>

        <!-- Stock picker modal — same available-stock source used by the Browse
             button on create_sale.php, so the assigned code always matches a real,
             in-stock item at this order's branch. -->
        <div class="modal fade" id="stockPickerModal" tabindex="-1" role="dialog">
            <div class="modal-dialog modal-xl" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Branch Stock — Pick Item Code</h5>
                        <button class="btn-close" type="button" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <table class="stock-picker-table" id="stockPickerTable" width="100%" cellspacing="0">
                            <thead>
                                <tr><th>Code</th><th>Name</th><th>Price</th><th>S/N</th><th>Specs</th></tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($availableItems)): ?>
                                    <?php foreach ($availableItems as $item): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($item['unique_id'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($item['item_name'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars(isset($item['unit_price']) ? number_format((float)$item['unit_price'], 2) : 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($item['serial_number'] ?? 'N/A'); ?></td>
                                        <td><?php echo htmlspecialchars($item['technical_specs'] ?? 'N/A'); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr><td colspan="5" class="text-center">No available stock items found for this branch.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <script>
            $(function() {
                const stockPickerTable = $('#stockPickerTable').DataTable({
                    paging: true, searching: true, ordering: true, info: true,
                    lengthMenu: [5, 10, 25, 50], pageLength: 10
                });

                const codeRows = document.getElementById('orderCodeRows');
                function addOrderCodeRow(code = '') {
                    const row = codeRows.querySelector('.order-code-row').cloneNode(true);
                    row.querySelector('.assigned-code-input').value = code;
                    row.querySelector('.code-value-input').value = '';
                    row.querySelector('.remove-order-code').disabled = false;
                    codeRows.appendChild(row);
                    return row;
                }
                $('#addOrderCodeBtn').on('click', function() { addOrderCodeRow(); });
                codeRows.addEventListener('click', function(event) {
                    if (event.target.classList.contains('remove-order-code') && codeRows.children.length > 1) {
                        event.target.closest('.order-code-row').remove();
                    }
                });

                $('#browseStockCodeBtn').on('click', function() {
                    bootstrap.Modal.getOrCreateInstance(document.getElementById('stockPickerModal')).show();
                });

                $('#stockPickerTable tbody').on('click', 'tr', function() {
                    const data = stockPickerTable.row(this).data();
                    if (!data) return;
                    const uniqueCode = $('<div>').html(data[0]).text();
                    const existing = Array.from(codeRows.querySelectorAll('.assigned-code-input'));
                    if (existing.some(input => input.value.trim() === uniqueCode)) return;
                    const emptyInput = existing.find(input => input.value.trim() === '');
                    if (emptyInput) {
                        emptyInput.value = uniqueCode;
                    } else {
                        addOrderCodeRow(uniqueCode);
                    }
                });
            });
        </script>
        <?php endif; ?>

        <!-- Action Bar -->
        <div class="action-bar">
            <a href="list_orders.php?branch_id=<?php echo $branchId; ?>" class="btn-action btn-secondary-c">
                <i class="fas fa-arrow-left"></i> Back to Orders
            </a>

            <div class="action-bar-right">
                <?php if ($isUserAssignedBranch && $orderData['status'] !== 'completed'): ?>
                    <a href="edit_order.php?order_id=<?php echo $orderId; ?>" class="btn-action btn-primary-c">
                        <i class="fas fa-edit"></i> Edit
                    </a>
                    <a href="order_receipt.php?order_id=<?php echo $orderId; ?>" class="btn-action btn-secondary-c" target="_blank" rel="noopener">
                        <i class="fas fa-print"></i> Print Statement
                    </a>
                    <form action="delete_order.php" method="POST" style="display:inline;">
                        <input type="hidden" name="order_id" value="<?php echo $orderId; ?>">
                        <button type="submit" class="btn-action btn-danger-c"
                                onclick="return confirm('Delete this order and all its payment records?');">
                            <i class="fas fa-trash"></i> Delete
                        </button>
                    </form>
                    <?php if ($status === 'delivered'): ?>
                        <a href="generate_delivery_note.php?order_id=<?php echo $orderId; ?>" class="btn-action btn-warning-c">
                            <i class="fas fa-truck"></i> Delivery Note
                        </a>
                    <?php endif; ?>
                <?php elseif ($orderData['status'] === 'completed'): ?>
                    <a href="order_receipt.php?order_id=<?php echo $orderId; ?>" class="btn-action btn-receipt-c">
                        <i class="fas fa-receipt"></i> View Receipt
                    </a>
                    <a href="order_receipt.php?order_id=<?php echo $orderId; ?>" class="btn-action btn-primary-c" target="_blank" rel="noopener">
                        <i class="fas fa-print"></i> Print Receipt
                    </a>
                <?php endif; ?>
            </div>
        </div>

    </div><!-- /page-wrap -->

<?php include __DIR__ . '/../../includes/footer.php'; ?>
