<?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/Customers.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);
$customersRepo = new Customers($conn);

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

$branchId     = isset($_GET['branch_id']) ? (int)$_GET['branch_id'] : null;
$isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);

if ($isSuperAdmin) {
    if (!$branchId) {
        header('Location: ../admin/orders/order_branch_selection.php?error=' . urlencode('Please select a branch.'));
        exit();
    }
    try {
        $branches    = $branch->getAllBranches();
        $validBranch = false;
        foreach ($branches->fetchAll(PDO::FETCH_ASSOC) as $b) {
            if ($b['branch_id'] == $branchId) { $validBranch = true; break; }
        }
        if (!$validBranch) {
            header('Location: ../admin/orders/order_branch_selection.php?error=' . urlencode('Invalid branch selected.'));
            exit();
        }
    } catch (PDOException $e) {
        error_log("Branch validation error: " . $e->getMessage());
        header('Location: ../admin/orders/order_branch_selection.php?error=' . urlencode('Database error: ' . $e->getMessage()));
        exit();
    }
    $_SESSION['selected_branch_id'] = $branchId;
} else {
    $branchId = $userBranchId;
    if (!$branchId) {
        header('Location: ../../login.php?error=' . urlencode('No branch assigned to this user.'));
        exit();
    }
    $_SESSION['selected_branch_id'] = $branchId;
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $itemName       = trim($_POST['item_name'] ?? '');
    $price          = (float)($_POST['price'] ?? 0);
    $customerName   = trim($_POST['customer_name'] ?? '');
    $customerContact = trim($_POST['customer_contact'] ?? '');
    $postedCustomerId = isset($_POST['customer_id']) && $_POST['customer_id'] !== '' ? (int)$_POST['customer_id'] : null;
    $amountPaid     = (float)($_POST['amount_paid'] ?? 0);
    $deliveryDate   = $_POST['delivery_date'] ?? date('Y-m-d', strtotime('+7 days'));
    $status         = $_POST['status'] ?? 'pending';
    $notes          = trim($_POST['notes'] ?? '');
    $paymentMethod  = normalizePaymentMethodValue($_POST['payment_method'] ?? 'cash');
    $createdBy      = (int)$_SESSION['user_id'];

    if (empty($itemName)) {
        $error = 'Item name is required.';
    } elseif ($price <= 0) {
        $error = 'Order price must be greater than zero.';
    } elseif (empty($customerName)) {
        $error = 'Customer name is required.';
    } elseif (empty($customerContact)) {
        $error = 'Customer contact details are required.';
    } elseif ($amountPaid < 0) {
        $error = 'Deposit amount cannot be negative.';
    } elseif ($amountPaid > $price) {
        $error = 'Deposit cannot exceed the order price.';
    } else {
        try {
            $customerId = $customersRepo->findOrCreate($postedCustomerId, $customerName, mb_substr($customerContact, 0, 30), null, $createdBy);
            $result = $orderObj->createOrder($branchId, $itemName, $price, $customerName, $customerContact, $amountPaid, $deliveryDate, $status, $notes, $createdBy, $paymentMethod, $customerId);
            if ($result) {
                header('Location: list_orders.php?success=' . urlencode('Order created successfully.') . '&branch_id=' . $branchId);
                exit();
            } else {
                $error = 'Failed to create order. Please try again.';
            }
        } catch (Exception $e) {
            error_log("Error creating order: " . $e->getMessage());
            $error = 'Database error: ' . $e->getMessage();
        }
    }
}

// Pre-fill values on validation failure
$fItemName       = htmlspecialchars($_POST['item_name'] ?? '');
$fPrice          = htmlspecialchars($_POST['price'] ?? '');
$fCustomerName   = htmlspecialchars($_POST['customer_name'] ?? '');
$fCustomerContact = htmlspecialchars($_POST['customer_contact'] ?? '');
$fAmountPaid     = htmlspecialchars($_POST['amount_paid'] ?? '0');
$fDeliveryDate   = htmlspecialchars($_POST['delivery_date'] ?? date('Y-m-d', strtotime('+7 days')));
$fStatus         = $_POST['status'] ?? 'pending';
$fNotes          = htmlspecialchars($_POST['notes'] ?? '');
$fPaymentMethod  = $_POST['payment_method'] ?? 'cash';
?>
<?php include __DIR__ . '/../../includes/header.php'; ?>
    <style>
        :root {
            --brand:    #2c3e50;
            --brand-lt: #34495e;
            --accent:   #3498db;
            --green:    #27ae60;
            --green-dk: #229954;
            --orange:   #e67e22;
            --red:      #e74c3c;
            --gray-bg:  #f4f6f9;
            --card-bg:  #ffffff;
            --border:   #e2e8f0;
            --text:     #2d3748;
            --muted:    #718096;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: var(--gray-bg);
            min-height: 100vh;
            color: var(--text);
        }

        /* ══ TOP NAV BAR ══ */
        .top-bar {
            background: var(--brand);
            color: #fff;
            padding: 0 28px;
            height: 58px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            box-shadow: 0 2px 10px rgba(0,0,0,.2);
            position: sticky;
            top: 0;
            z-index: 100;
        }
        .top-bar-left { display: flex; align-items: center; gap: 14px; }
        .top-bar-logo { max-height: 36px; }
        .top-bar-company { font-size: 16px; font-weight: 700; letter-spacing: .5px; }
        .top-bar-divider { width: 1px; height: 28px; background: rgba(255,255,255,.2); }
        .top-bar-page { font-size: 13px; opacity: .75; }
        .btn-nav-back {
            display: inline-flex; align-items: center; gap: 6px;
            background: rgba(255,255,255,.12);
            color: #fff; border: none; border-radius: 7px;
            padding: 7px 16px; font-size: 13px; font-weight: 600;
            text-decoration: none; cursor: pointer; transition: background .2s;
        }
        .btn-nav-back:hover { background: rgba(255,255,255,.22); color: #fff; text-decoration: none; }

        /* ══ PAGE LAYOUT ══ */
        .page-wrap {
            max-width: 960px;
            margin: 32px auto;
            padding: 0 20px 60px;
        }

        /* ══ PAGE TITLE ══ */
        .page-title-row {
            display: flex;
            align-items: center;
            gap: 14px;
            margin-bottom: 28px;
        }
        .page-title-icon {
            width: 52px; height: 52px;
            background: linear-gradient(135deg, var(--accent), #2980b9);
            border-radius: 14px;
            display: flex; align-items: center; justify-content: center;
            color: #fff; font-size: 22px;
            box-shadow: 0 4px 14px rgba(52,152,219,.35);
            flex-shrink: 0;
        }
        .page-title-text h1 { font-size: 22px; font-weight: 800; color: var(--brand); margin: 0; }
        .page-title-text p  { font-size: 13px; color: var(--muted); margin: 2px 0 0; }

        /* ══ FORM + SIDEBAR LAYOUT ══ */
        .form-layout {
            display: grid;
            grid-template-columns: 1fr 300px;
            gap: 22px;
            align-items: start;
        }

        /* ══ SECTION CARD ══ */
        .section-card {
            background: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 1px 6px rgba(0,0,0,.07), 0 4px 18px rgba(0,0,0,.04);
            margin-bottom: 18px;
            overflow: hidden;
        }
        .section-card:last-child { margin-bottom: 0; }

        .section-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 18px 24px;
            border-bottom: 1px solid var(--border);
        }
        .step-badge {
            width: 30px; height: 30px;
            border-radius: 50%;
            display: flex; align-items: center; justify-content: center;
            font-size: 13px; font-weight: 800; color: #fff; flex-shrink: 0;
        }
        .step-1 { background: linear-gradient(135deg, #3498db, #2980b9); }
        .step-2 { background: linear-gradient(135deg, #9b59b6, #8e44ad); }
        .step-3 { background: linear-gradient(135deg, var(--green), var(--green-dk)); }
        .step-4 { background: linear-gradient(135deg, #6c757d, #495057); }

        .section-header-text h3 { font-size: 15px; font-weight: 700; color: var(--brand); margin: 0; }
        .section-header-text p  { font-size: 12px; color: var(--muted); margin: 2px 0 0; }

        .section-body { padding: 22px 24px; }

        /* ══ FORM FIELDS ══ */
        .field-group { margin-bottom: 18px; }
        .field-group:last-child { margin-bottom: 0; }
        .field-row { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
        .field-row.thirds { grid-template-columns: 1fr 1fr 1fr; }

        .field-label {
            display: flex;
            align-items: center;
            gap: 6px;
            font-size: 12px;
            font-weight: 700;
            color: var(--muted);
            text-transform: uppercase;
            letter-spacing: .5px;
            margin-bottom: 7px;
        }
        .field-label .req { color: var(--red); }
        .field-label i { font-size: 11px; }

        .form-input {
            width: 100%;
            border: 2px solid var(--border);
            border-radius: 9px;
            padding: 11px 14px;
            font-size: 14px;
            color: var(--text);
            background: #fff;
            transition: border-color .2s, box-shadow .2s;
            font-family: inherit;
        }
        .form-input:focus {
            outline: none;
            border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(52,152,219,.12);
        }
        .form-input.input-success { border-color: var(--green); }
        .form-input.input-error   { border-color: var(--red); }
        textarea.form-input { resize: vertical; min-height: 88px; }
        select.form-input { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23718096' d='M6 8L1 3h10z'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 14px center; padding-right: 36px; }
        .field-hint { font-size: 11px; color: var(--muted); margin-top: 5px; }

        /* Status select colours */
        .status-pending   { color: #856404; }
        .status-approved  { color: #0c5460; }

        /* ══ SIDEBAR CARDS ══ */
        .sidebar { display: flex; flex-direction: column; gap: 18px; }

        .info-card {
            background: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 1px 6px rgba(0,0,0,.07);
            overflow: hidden;
        }
        .info-card-header {
            padding: 14px 18px;
            font-size: 13px;
            font-weight: 700;
            color: #fff;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .info-card-header.blue   { background: linear-gradient(135deg, var(--accent), #2980b9); }
        .info-card-header.green  { background: linear-gradient(135deg, var(--green), var(--green-dk)); }
        .info-card-header.orange { background: linear-gradient(135deg, var(--orange), #d35400); }
        .info-card-body { padding: 16px 18px; }

        /* Payment preview */
        .preview-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 9px 0;
            font-size: 13px;
            border-bottom: 1px solid var(--border);
        }
        .preview-row:last-child { border-bottom: none; padding-bottom: 0; }
        .preview-row.total-row  { font-weight: 700; font-size: 14px; padding-top: 11px; }
        .preview-label { color: var(--muted); }
        .preview-value { font-weight: 600; color: var(--text); }
        .preview-value.green  { color: var(--green); }
        .preview-value.red    { color: var(--red); }
        .preview-value.orange { color: var(--orange); }

        /* Progress bar */
        .deposit-progress {
            margin-top: 14px;
        }
        .progress-label {
            display: flex;
            justify-content: space-between;
            font-size: 11px;
            color: var(--muted);
            margin-bottom: 6px;
        }
        .progress-bar-track {
            height: 8px;
            background: var(--border);
            border-radius: 20px;
            overflow: hidden;
        }
        .progress-bar-fill {
            height: 100%;
            border-radius: 20px;
            background: linear-gradient(90deg, var(--green), #2ecc71);
            transition: width .4s ease;
        }

        /* Status key */
        .status-legend { display: flex; flex-direction: column; gap: 6px; }
        .status-legend-item { display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--muted); }
        .status-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }

        /* ══ ERROR ALERT ══ */
        .alert-error {
            background: #fef2f2;
            border: 1px solid #fecaca;
            border-left: 4px solid var(--red);
            border-radius: 10px;
            padding: 14px 18px;
            display: flex;
            align-items: flex-start;
            gap: 12px;
            margin-bottom: 22px;
            color: #991b1b;
            font-size: 14px;
        }
        .alert-error i { color: var(--red); margin-top: 1px; flex-shrink: 0; }

        /* ══ SUBMIT BAR ══ */
        .submit-bar {
            background: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 1px 6px rgba(0,0,0,.07);
            padding: 20px 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 12px;
            margin-top: 18px;
        }
        .submit-bar-note { font-size: 12px; color: var(--muted); }
        .submit-bar-note strong { color: var(--text); }
        .btn-submit {
            background: linear-gradient(135deg, var(--green), var(--green-dk));
            color: #fff;
            border: none;
            border-radius: 10px;
            padding: 12px 30px;
            font-size: 15px;
            font-weight: 700;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 9px;
            transition: all .2s;
            box-shadow: 0 4px 14px rgba(39,174,96,.3);
        }
        .btn-submit:hover { transform: translateY(-2px); box-shadow: 0 8px 22px rgba(39,174,96,.4); }
        .btn-submit:active { transform: translateY(0); }
        .btn-cancel-link {
            display: inline-flex; align-items: center; gap: 6px;
            color: var(--muted); font-size: 13px; font-weight: 600;
            text-decoration: none; padding: 8px 14px;
            border-radius: 8px; transition: background .2s;
        }
        .btn-cancel-link:hover { background: var(--border); color: var(--text); text-decoration: none; }

        /* ══ RESPONSIVE ══ */
        @media (max-width: 768px) {
            .top-bar { padding: 0 16px; }
            .page-wrap { margin: 18px auto; padding: 0 12px 40px; }
            .form-layout { grid-template-columns: 1fr; }
            .sidebar { display: contents; }
            .field-row { grid-template-columns: 1fr; }
            .field-row.thirds { grid-template-columns: 1fr; }
            .submit-bar { flex-direction: column-reverse; align-items: stretch; text-align: center; }
            .btn-submit { justify-content: center; }
        }
    </style>

<div class="page-wrap">

    <!-- Page Title -->
    <div class="page-title-row">
        <div class="page-title-icon"><i class="fas fa-file-alt"></i></div>
        <div class="page-title-text">
            <h1>Create New Order</h1>
            <p>Fill in the details below to record a customer order and initial deposit.</p>
        </div>
        <a href="list_orders.php?branch_id=<?php echo $branchId; ?>" class="btn-cancel-link ms-auto">
            <i class="fas fa-arrow-left"></i> Back to Orders
        </a>
    </div>

    <!-- Error Alert -->
    <?php if ($error): ?>
    <div class="alert-error">
        <i class="fas fa-exclamation-circle"></i>
        <div><?php echo htmlspecialchars($error); ?></div>
    </div>
    <?php endif; ?>

    <form method="POST" id="orderForm" novalidate>
        <div class="form-layout">

            <!-- ── LEFT: Form Sections ── -->
            <div class="form-sections">

                <!-- Section 1: Customer Details -->
                <div class="section-card">
                    <div class="section-header">
                        <div class="step-badge step-1">1</div>
                        <div class="section-header-text">
                            <h3>Customer Details</h3>
                            <p>Who is placing this order?</p>
                        </div>
                    </div>
                    <div class="section-body">
                        <input type="hidden" name="customer_id" id="customer_id" value="<?php echo htmlspecialchars($_POST['customer_id'] ?? '', ENT_QUOTES, 'UTF-8'); ?>">
                        <div class="field-group">
                            <div class="field-label">
                                <i class="fas fa-user"></i> Customer / Company Name <span class="req">*</span>
                            </div>
                            <div class="position-relative">
                                <input type="text" name="customer_name" id="customer_name" class="form-input" autocomplete="off"
                                       placeholder="e.g. John Banda or ABC Electronics Ltd"
                                       value="<?php echo $fCustomerName; ?>" required autofocus>
                                <div id="customerSearchResults" class="list-group position-absolute w-100 shadow-sm" style="z-index:1050; display:none;"></div>
                            </div>
                            <div class="field-hint">Start typing to find an existing customer, or enter a new one — it will be saved automatically.</div>
                        </div>
                        <div class="field-group">
                            <div class="field-label">
                                <i class="fas fa-address-book"></i> Contact Details <span class="req">*</span>
                            </div>
                            <textarea name="customer_contact" id="customer_contact" class="form-input"
                                      placeholder="Phone number, email address, physical address..."
                                      required><?php echo $fCustomerContact; ?></textarea>
                            <div class="field-hint">Include phone, email or address — the more the better.</div>
                        </div>
                    </div>
                </div>

                <!-- Section 2: Item & Order Details -->
                <div class="section-card">
                    <div class="section-header">
                        <div class="step-badge step-2">2</div>
                        <div class="section-header-text">
                            <h3>Item &amp; Order Details</h3>
                            <p>What is being ordered and when is it due?</p>
                        </div>
                    </div>
                    <div class="section-body">
                        <div class="field-group">
                            <div class="field-label">
                                <i class="fas fa-box"></i> Item Name / Description <span class="req">*</span>
                            </div>
                            <input type="text" name="item_name" class="form-input"
                                   placeholder="e.g. Dell Vostro Laptop 15 – 8GB RAM, 256GB SSD"
                                   value="<?php echo $fItemName; ?>" required>
                        </div>
                        <div class="field-row">
                            <div class="field-group">
                                <div class="field-label">
                                    <i class="fas fa-tag"></i> Order Price (MWK) <span class="req">*</span>
                                </div>
                                <input type="number" name="price" id="price" class="form-input"
                                       placeholder="0.00" step="0.01" min="0.01"
                                       value="<?php echo $fPrice; ?>" required>
                            </div>
                            <div class="field-group">
                                <div class="field-label">
                                    <i class="fas fa-calendar-alt"></i> Expected Delivery Date <span class="req">*</span>
                                </div>
                                <input type="date" name="delivery_date" class="form-input"
                                       value="<?php echo $fDeliveryDate; ?>" required>
                            </div>
                        </div>
                        <div class="field-group">
                            <div class="field-label">
                                <i class="fas fa-circle"></i> Initial Status
                            </div>
                            <select name="status" class="form-input">
                                <?php
                                $statuses = [
                                    'pending'   => 'Pending – awaiting approval',
                                    'approved'  => 'Approved – confirmed order',
                                    'delivered' => 'Delivered – item received',
                                ];
                                foreach ($statuses as $val => $label): ?>
                                <option value="<?php echo $val; ?>" <?php echo $fStatus === $val ? 'selected' : ''; ?>>
                                    <?php echo $label; ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Section 3: Initial Payment / Deposit -->
                <div class="section-card">
                    <div class="section-header">
                        <div class="step-badge step-3">3</div>
                        <div class="section-header-text">
                            <h3>Initial Deposit</h3>
                            <p>Record any upfront payment made today. Leave at 0 if no deposit yet.</p>
                        </div>
                    </div>
                    <div class="section-body">
                        <div class="field-row">
                            <div class="field-group">
                                <div class="field-label">
                                    <i class="fas fa-money-bill-wave"></i> Deposit Amount (MWK)
                                </div>
                                <input type="number" name="amount_paid" id="amount_paid" class="form-input"
                                       placeholder="0.00" step="0.01" min="0"
                                       value="<?php echo $fAmountPaid; ?>">
                                <div class="field-hint">Can be 0 if no deposit is collected now.</div>
                            </div>
                            <div class="field-group">
                                <div class="field-label">
                                    <i class="fas fa-credit-card"></i> Payment Method
                                </div>
                                <select name="payment_method" class="form-input">
                                    <?php echo paymentMethodSelectOptions($fPaymentMethod); ?>
                                </select>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Section 4: Notes -->
                <div class="section-card">
                    <div class="section-header">
                        <div class="step-badge step-4">4</div>
                        <div class="section-header-text">
                            <h3>Notes &amp; Terms</h3>
                            <p>Any special instructions, conditions or remarks.</p>
                        </div>
                    </div>
                    <div class="section-body">
                        <div class="field-group">
                            <div class="field-label"><i class="fas fa-sticky-note"></i> Additional Notes</div>
                            <textarea name="notes" class="form-input" rows="3"
                                      placeholder="e.g. Customer to call before collection. Colour preference: black. Delivery to Blantyre office."><?php echo $fNotes; ?></textarea>
                        </div>
                    </div>
                </div>

                <!-- Submit Bar -->
                <div class="submit-bar">
                    <div class="submit-bar-note">
                        Fields marked <strong style="color:var(--red);">*</strong> are required.
                        You can add more payments later from the order page.
                    </div>
                    <div style="display:flex;align-items:center;gap:14px;">
                        <a href="list_orders.php?branch_id=<?php echo $branchId; ?>" class="btn-cancel-link">
                            <i class="fas fa-times"></i> Cancel
                        </a>
                        <button type="submit" class="btn-submit" id="submitBtn">
                            <i class="fas fa-save"></i> Create Order
                        </button>
                    </div>
                </div>

            </div><!-- /form-sections -->

            <!-- ── RIGHT: Sidebar ── -->
            <div class="sidebar">

                <!-- Payment Preview -->
                <div class="info-card">
                    <div class="info-card-header green">
                        <i class="fas fa-calculator"></i> Payment Preview
                    </div>
                    <div class="info-card-body">
                        <div class="preview-row">
                            <span class="preview-label">Order Price</span>
                            <span class="preview-value" id="prev-price">MWK 0.00</span>
                        </div>
                        <div class="preview-row">
                            <span class="preview-label">Deposit Today</span>
                            <span class="preview-value green" id="prev-paid">MWK 0.00</span>
                        </div>
                        <div class="preview-row total-row">
                            <span class="preview-label">Balance Due</span>
                            <span class="preview-value orange" id="prev-balance">MWK 0.00</span>
                        </div>

                        <div class="deposit-progress">
                            <div class="progress-label">
                                <span>Deposit</span>
                                <span id="prev-pct">0%</span>
                            </div>
                            <div class="progress-bar-track">
                                <div class="progress-bar-fill" id="progress-fill" style="width:0%"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Status Guide -->
                <div class="info-card">
                    <div class="info-card-header blue">
                        <i class="fas fa-info-circle"></i> Status Guide
                    </div>
                    <div class="info-card-body">
                        <div class="status-legend">
                            <div class="status-legend-item">
                                <div class="status-dot" style="background:#f39c12;"></div>
                                <span><strong>Pending</strong> — awaiting stock or approval</span>
                            </div>
                            <div class="status-legend-item">
                                <div class="status-dot" style="background:#17a2b8;"></div>
                                <span><strong>Approved</strong> — confirmed, being sourced</span>
                            </div>
                            <div class="status-legend-item">
                                <div class="status-dot" style="background:#3498db;"></div>
                                <span><strong>Delivered</strong> — item in store, ready for collection</span>
                            </div>
                            <div class="status-legend-item">
                                <div class="status-dot" style="background:#27ae60;"></div>
                                <span><strong>Completed</strong> — paid in full and collected</span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Tips -->
                <div class="info-card">
                    <div class="info-card-header orange">
                        <i class="fas fa-lightbulb"></i> Tips
                    </div>
                    <div class="info-card-body">
                        <ul style="padding-left:16px;font-size:12px;color:var(--muted);margin:0;line-height:1.9;">
                            <li>A deposit of <strong>0</strong> is allowed — add payments later from the order details page.</li>
                            <li>Once fully paid, a controller can assign a unique item code to complete the order.</li>
                            <li>A full receipt with all transactions is generated at completion.</li>
                        </ul>
                    </div>
                </div>

            </div><!-- /sidebar -->

        </div><!-- /form-layout -->
    </form>

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

<script>
    function fmt(n) {
        return 'MWK ' + parseFloat(n || 0).toLocaleString('en-MW', {minimumFractionDigits:2, maximumFractionDigits:2});
    }

    function updatePreview() {
        const price   = parseFloat(document.getElementById('price').value) || 0;
        const paid    = parseFloat(document.getElementById('amount_paid').value) || 0;
        const balance = Math.max(0, price - paid);
        const pct     = price > 0 ? Math.min(100, Math.round((paid / price) * 100)) : 0;

        document.getElementById('prev-price').textContent   = fmt(price);
        document.getElementById('prev-paid').textContent    = fmt(paid);
        document.getElementById('prev-balance').textContent = fmt(balance);
        document.getElementById('prev-pct').textContent     = pct + '%';
        document.getElementById('progress-fill').style.width = pct + '%';

        const balEl = document.getElementById('prev-balance');
        balEl.className = 'preview-value ' + (balance === 0 && price > 0 ? 'green' : balance > 0 ? 'orange' : '');
    }

    document.getElementById('price').addEventListener('input', updatePreview);
    document.getElementById('amount_paid').addEventListener('input', updatePreview);

    /* ── Customer search (find existing or auto-create new on submit) ── */
    (function() {
        const nameInput = document.getElementById('customer_name');
        const idInput = document.getElementById('customer_id');
        const contactInput = document.getElementById('customer_contact');
        const resultsBox = document.getElementById('customerSearchResults');
        let searchTimer = null;
        let searchXhr = null;

        nameInput.addEventListener('input', function() {
            idInput.value = '';
            const term = this.value.trim();
            clearTimeout(searchTimer);
            if (searchXhr) { searchXhr.abort(); searchXhr = null; }
            if (term.length < 2) { resultsBox.style.display = 'none'; resultsBox.innerHTML = ''; return; }
            searchTimer = setTimeout(function() {
                searchXhr = new XMLHttpRequest();
                searchXhr.open('GET', '../../ajax/customer_search.php?term=' + encodeURIComponent(term));
                searchXhr.onload = function() {
                    searchXhr = null;
                    let response;
                    try { response = JSON.parse(this.responseText); } catch (e) { return; }
                    resultsBox.innerHTML = '';
                    if (!response.success || !response.customers || !response.customers.length) {
                        resultsBox.style.display = 'none';
                        return;
                    }
                    response.customers.forEach(function(c) {
                        const btn = document.createElement('button');
                        btn.type = 'button';
                        btn.className = 'list-group-item list-group-item-action';
                        btn.textContent = c.customer_name + (c.customer_phone ? ' — ' + c.customer_phone : '');
                        btn.addEventListener('click', function() {
                            idInput.value = c.customer_id || '';
                            nameInput.value = c.customer_name || '';
                            if (c.customer_phone && !contactInput.value.trim()) {
                                contactInput.value = c.customer_phone;
                            }
                            resultsBox.style.display = 'none';
                            resultsBox.innerHTML = '';
                        });
                        resultsBox.appendChild(btn);
                    });
                    resultsBox.style.display = 'block';
                };
                searchXhr.send();
            }, 250);
        });

        document.addEventListener('click', function(e) {
            if (!e.target.closest('#customer_name, #customerSearchResults')) {
                resultsBox.style.display = 'none';
            }
        });
    })();

    // Prevent deposit exceeding price
    document.getElementById('amount_paid').addEventListener('blur', function() {
        const price = parseFloat(document.getElementById('price').value) || 0;
        const paid  = parseFloat(this.value) || 0;
        if (price > 0 && paid > price) {
            this.value = price.toFixed(2);
            updatePreview();
        }
    });

    // Client-side validation feedback
    document.getElementById('orderForm').addEventListener('submit', function(e) {
        const price    = parseFloat(document.getElementById('price').value) || 0;
        const amtPaid  = parseFloat(document.getElementById('amount_paid').value) || 0;
        let valid = true;

        [['item_name','Item name'], ['customer_name','Customer name'], ['customer_contact','Contact details']].forEach(([id, label]) => {
            const el = document.querySelector('[name="' + id + '"]');
            if (!el.value.trim()) {
                el.classList.add('input-error');
                valid = false;
            } else {
                el.classList.remove('input-error');
                el.classList.add('input-success');
            }
        });

        if (price <= 0) {
            document.getElementById('price').classList.add('input-error');
            valid = false;
        } else {
            document.getElementById('price').classList.remove('input-error');
        }

        if (!valid) {
            e.preventDefault();
            window.scrollTo({top: 0, behavior: 'smooth'});
        } else {
            const btn = document.getElementById('submitBtn');
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving…';
            btn.disabled = true;
        }
    });

    // Init preview with any prefilled values
    updatePreview();
</script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
