<?php
require_once __DIR__ . '/../includes/config.php';

$order_id = $_GET['id'] ?? null;
$order = null;
$order_items = [];
$page_title = 'Comandă nouă';

if ($order_id) {
    $order_id = (int)$order_id;
    $result = $db->query("SELECT o.*, c.* FROM orders o JOIN clients c ON o.client_id = c.id WHERE o.id = $order_id");
    $order = $result ? $result->fetch_assoc() : null;
    
    if (!$order) {
        redirectWithMessage(APP_URL . '/admin/orders.php', 'Comandă nu a fost găsită', 'error');
    }
    
    // Get order items
    $items_result = $db->query("SELECT oi.*, p.name as product_name FROM order_items oi JOIN products p ON oi.product_id = p.id WHERE oi.order_id = $order_id");
    if ($items_result && $items_result->num_rows > 0) {
        while ($item = $items_result->fetch_assoc()) {
            $order_items[] = $item;
        }
    }
    
    $page_title = 'Editează comanda #' . $order_id;
}

// Get statuses
$statuses_result = $db->query("SELECT * FROM order_statuses ORDER BY name");
$statuses = [];
while ($status = $statuses_result->fetch_assoc()) {
    $statuses[] = $status;
}

// Get discounts
$discounts_result = $db->query("SELECT * FROM discounts WHERE active = TRUE ORDER BY name");
$discounts = [];
while ($discount = $discounts_result->fetch_assoc()) {
    $discounts[] = $discount;
}

// Get products
$products_result = $db->query("SELECT * FROM products WHERE active = TRUE ORDER BY name");
$products = [];
while ($product = $products_result->fetch_assoc()) {
    $products[] = $product;
}

require_once __DIR__ . '/../includes/header.php';
?>

<div class="card" style="max-width:900px">
    <div class="card-header">
        <div class="card-title"><?php echo $order ? 'Editează comanda #' . $order_id : 'Comandă nouă'; ?></div>
    </div>
    <div class="card-body">
        <form method="POST" action="<?php echo APP_URL; ?>/api/save-order.php" id="order-form">
            <?php if ($order): ?>
                <input type="hidden" name="id" value="<?php echo $order['id']; ?>">
            <?php endif; ?>

            <!-- CLIENT INFO -->
            <div style="background:var(--bg3);border:1px solid var(--border);border-radius:12px;padding:16px;margin-bottom:16px">
                <div style="font-size:11px;font-weight:700;color:var(--text3);text-transform:uppercase;letter-spacing:1px;margin-bottom:12px;display:flex;align-items:center;gap:6px">
                    <span style="display:inline-block;width:3px;height:14px;background:var(--accent);border-radius:2px"></span>
                    Informații client
                </div>
                <div class="form-grid c3">
                    <div class="form-group">
                        <label class="form-label">Nume *</label>
                        <input class="form-input" name="first_name" value="<?php echo $order ? htmlspecialchars($order['first_name']) : ''; ?>" placeholder="Maria" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Prenume</label>
                        <input class="form-input" name="last_name" value="<?php echo $order ? htmlspecialchars($order['last_name'] ?? '') : ''; ?>" placeholder="Popescu">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Telefon</label>
                        <input class="form-input" name="phone" value="<?php echo $order ? htmlspecialchars($order['phone'] ?? '') : ''; ?>" placeholder="07XX XXX XXX">
                    </div>
                </div>
            </div>

            <!-- ORDER META -->
            <div class="form-grid" style="margin-bottom:16px">
                <div class="form-group">
                    <label class="form-label">Status</label>
                    <select class="form-select form-input" name="status_id">
                        <?php foreach ($statuses as $s): ?>
                            <option value="<?php echo $s['id']; ?>" <?php echo !$order && $s['id'] == 1 || $order && $order['status_id'] == $s['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($s['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Reducere</label>
                    <select class="form-select form-input" name="discount_id" onchange="recalcTotal()">
                        <option value="">— Fără reducere —</option>
                        <?php foreach ($discounts as $d): ?>
                            <option value="<?php echo $d['id']; ?>" <?php echo $order && $order['discount_id'] == $d['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($d['name']) . ' (' . ($d['type'] === 'percent' ? $d['value'] . '%' : number_format($d['value'], 2, '.', '') . ' lei') . ')'; ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label">Data comenzii</label>
                    <input class="form-input" type="date" name="order_date" value="<?php echo $order ? htmlspecialchars($order['order_date']) : date('Y-m-d'); ?>" required>
                </div>
                <div class="form-group">
                    <label class="form-label">Note</label>
                    <input class="form-input" name="notes" placeholder="Note opționale..." value="<?php echo $order ? htmlspecialchars($order['notes'] ?? '') : ''; ?>">
                </div>
            </div>

            <!-- DELIVERY TOGGLE -->
            <div style="background:var(--bg3);border:1px solid var(--border);border-radius:12px;padding:14px 16px;margin-bottom:16px">
                <div style="display:flex;align-items:center;justify-content:space-between;cursor:pointer;user-select:none" onclick="toggleDelivery()">
                    <div>
                        <div style="font-size:13.5px;font-weight:500">🚚 Livrare la domiciliu</div>
                        <div style="font-size:12px;color:var(--text3);margin-top:2px">Activează pentru a adăuga costul livrării la total</div>
                    </div>
                    <label class="switch" onclick="event.stopPropagation()">
                        <input type="checkbox" id="delivery-enabled" name="delivery_enabled" <?php echo $order && $order['delivery_enabled'] ? 'checked' : ''; ?> onchange="toggleDelivery()">
                        <div class="switch-track"></div>
                    </label>
                </div>
                <div id="delivery-fields" style="display:<?php echo $order && $order['delivery_enabled'] ? 'grid' : 'none'; ?>;grid-template-columns:1fr 1fr;gap:12px;margin-top:12px;padding-top:12px;border-top:1px solid var(--border)">
                    <div class="form-group">
                        <label class="form-label">Cost livrare (lei)</label>
                        <input class="form-input" type="number" id="delivery-price" name="delivery_price" min="0" step="1" value="<?php echo $order ? htmlspecialchars($order['delivery_price'] ?? '0') : '25'; ?>" oninput="recalcTotal()">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Adresă livrare</label>
                        <input class="form-input" name="delivery_address" placeholder="Str. Exemplu 10, Oraș" value="<?php echo $order ? htmlspecialchars($order['delivery_address'] ?? '') : ''; ?>">
                    </div>
                </div>
            </div>

            <!-- PRODUCTS -->
            <div style="font-size:11px;font-weight:700;color:var(--text3);text-transform:uppercase;letter-spacing:1px;margin-bottom:10px">Produse comandate</div>
            <div id="items-container" style="margin-bottom:10px">
                <?php if (!empty($order_items)): ?>
                    <?php foreach ($order_items as $idx => $item): ?>
                        <div class="order-item-row" style="background:var(--bg3);border:1px solid var(--border);border-radius:10px;padding:10px 12px;display:flex;align-items:center;gap:8px;margin-bottom:6px">
                            <select name="product_id[]" onchange="onProductChange(this)" style="flex:1;background:var(--bg4);border:1px solid var(--border);color:var(--text);border-radius:8px;padding:8px 10px;font-family:'DM Sans',sans-serif;font-size:13px;outline:none;cursor:pointer">
                                <?php foreach ($products as $p): ?>
                                    <option value="<?php echo $p['id']; ?>" <?php echo $item['product_id'] == $p['id'] ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($p['name']) . ' — ' . number_format($p['price'], 2, '.', '') . ' lei'; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <div style="display:flex;align-items:center;gap:4px;flex-shrink:0">
                                <button type="button" onclick="changeQty(this, -1)" style="width:28px;height:28px;background:var(--bg4);border:1px solid var(--border);color:var(--text);border-radius:7px;cursor:pointer;font-size:17px;line-height:1;display:flex;align-items:center;justify-content:center">−</button>
                                <input type="number" name="quantity[]" min="1" value="<?php echo $item['quantity']; ?>" style="width:50px;text-align:center;background:var(--bg4);border:1px solid var(--border);color:var(--text);border-radius:7px;padding:6px;font-family:'DM Sans',sans-serif;font-size:13px;outline:none" onchange="recalcTotal()">
                                <button type="button" onclick="changeQty(this, 1)" style="width:28px;height:28px;background:var(--bg4);border:1px solid var(--border);color:var(--text);border-radius:7px;cursor:pointer;font-size:17px;line-height:1;display:flex;align-items:center;justify-content:center">+</button>
                            </div>
                            <input type="number" name="price[]" step="0.01" value="<?php echo $item['price']; ?>" placeholder="Auto" readonly style="width:80px;text-align:center;background:var(--bg4);border:1px solid var(--border);color:var(--text3);border-radius:7px;padding:6px;font-family:'DM Sans',sans-serif;font-size:13px;outline:none" onchange="recalcTotal()">
                            <div style="font-weight:600;color:var(--accent);min-width:82px;text-align:right;font-size:13.5px;font-family:'Syne',sans-serif" class="item-total"><?php echo number_format(($item['price'] * $item['quantity']), 2, '.', ''); ?> lei</div>
                            <button type="button" onclick="removeItem(this)" style="background:none;border:none;color:var(--text3);cursor:pointer;padding:4px;border-radius:5px;display:flex;flex-shrink:0">
                                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
                            </button>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div style="background:var(--bg3);border:1px dashed var(--border2);border-radius:10px;padding:9px 14px;cursor:pointer;display:flex;align-items:center;gap:8px;color:var(--text3);transition:all 0.15s;font-size:13px" onclick="addItem()" style="hover:">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                Adaugă produs
            </div>

            <!-- TOTAL -->
            <div style="background:var(--bg4);border-radius:12px;padding:14px 16px;margin-top:16px">
                <div style="display:flex;justify-content:space-between;align-items:center;font-size:13px;padding:3px 0;color:var(--text2)">
                    <span>Subtotal produse</span>
                    <span id="subtotal-display" style="font-family:'Syne',sans-serif;font-size:13px;font-weight:600">0 lei</span>
                </div>
                <div id="discount-row" style="display:none;justify-content:space-between;align-items:center;font-size:13px;padding:3px 0;color:var(--green)">
                    <span>Reducere aplicată</span>
                    <span id="discount-display" style="font-family:'Syne',sans-serif;font-size:13px;font-weight:600">0 lei</span>
                </div>
                <div id="delivery-row" style="display:none;justify-content:space-between;align-items:center;font-size:13px;padding:3px 0;color:var(--blue)">
                    <span>Cost livrare</span>
                    <span id="delivery-display" style="font-family:'Syne',sans-serif;font-size:13px;font-weight:600">0 lei</span>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;border-top:1px solid var(--border);margin-top:6px;padding-top:10px">
                    <span style="font-size:14px;font-weight:600;color:var(--text)">TOTAL DE PLATĂ</span>
                    <span id="total-display" style="font-size:22px;color:var(--accent);font-family:'Syne',sans-serif;font-weight:700">0 lei</span>
                </div>
            </div>

            <div style="display:flex;gap:10px;margin-top:20px">
                <a href="<?php echo APP_URL; ?>/admin/orders.php" class="btn btn-ghost" style="flex:1;text-align:center;text-decoration:none">Anulează</a>
                <button type="submit" class="btn btn-primary" style="flex:1">✓ Salvează comanda</button>
            </div>
        </form>
    </div>
</div>

<style>
.switch{position:relative;width:40px;height:22px;flex-shrink:0}
.switch input{opacity:0;width:0;height:0;position:absolute}
.switch-track{position:absolute;inset:0;background:var(--border2);border-radius:11px;transition:background 0.2s;cursor:pointer}
.switch-track::before{content:'';position:absolute;width:16px;height:16px;left:3px;top:3px;background:white;border-radius:50%;transition:transform 0.2s}
.switch input:checked + .switch-track{background:var(--accent)}
.switch input:checked + .switch-track::before{transform:translateX(18px)}
</style>

<script>
const products = <?php echo json_encode($products); ?>;
const discounts = <?php echo json_encode($discounts); ?>;

function onProductChange(select) {
    const productId = select.value;
    const product = products.find(p => p.id == productId);
    
    if (product) {
        // Update price automatically
        const row = select.closest('.order-item-row');
        const priceInput = row.querySelector('input[name="price[]"]');
        priceInput.value = parseFloat(product.price).toFixed(2);
        recalcTotal();
    }
}

function toggleDelivery() {
    const checkbox = document.getElementById('delivery-enabled');
    const fields = document.getElementById('delivery-fields');
    fields.style.display = checkbox.checked ? 'grid' : 'none';
    recalcTotal();
}

function addItem() {
    const container = document.getElementById('items-container');
    
    const row = document.createElement('div');
    row.className = 'order-item-row';
    row.style.cssText = 'background:var(--bg3);border:1px solid var(--border);border-radius:10px;padding:10px 12px;display:flex;align-items:center;gap:8px;margin-bottom:6px';
    
    let options = '<option value="">— Selectează produs —</option>';
    options += products.map(p => `<option value="${p.id}">${p.name} — ${parseFloat(p.price).toFixed(2)} lei</option>`).join('');
    
    row.innerHTML = `
        <select name="product_id[]" onchange="onProductChange(this)" style="flex:1;background:var(--bg4);border:1px solid var(--border);color:var(--text);border-radius:8px;padding:8px 10px;font-family:'DM Sans',sans-serif;font-size:13px;outline:none;cursor:pointer" required>
            ${options}
        </select>
        <div style="display:flex;align-items:center;gap:4px;flex-shrink:0">
            <button type="button" onclick="changeQty(this, -1)" style="width:28px;height:28px;background:var(--bg4);border:1px solid var(--border);color:var(--text);border-radius:7px;cursor:pointer;font-size:17px;line-height:1;display:flex;align-items:center;justify-content:center">−</button>
            <input type="number" name="quantity[]" min="1" value="1" style="width:50px;text-align:center;background:var(--bg4);border:1px solid var(--border);color:var(--text);border-radius:7px;padding:6px;font-family:'DM Sans',sans-serif;font-size:13px;outline:none" onchange="recalcTotal()">
            <button type="button" onclick="changeQty(this, 1)" style="width:28px;height:28px;background:var(--bg4);border:1px solid var(--border);color:var(--text);border-radius:7px;cursor:pointer;font-size:17px;line-height:1;display:flex;align-items:center;justify-content:center">+</button>
        </div>
        <input type="number" name="price[]" step="0.01" placeholder="Auto" readonly style="width:80px;text-align:center;background:var(--bg4);border:1px solid var(--border);color:var(--text3);border-radius:7px;padding:6px;font-family:'DM Sans',sans-serif;font-size:13px;outline:none">
        <div style="font-weight:600;color:var(--accent);min-width:82px;text-align:right;font-size:13.5px;font-family:'Syne',sans-serif" class="item-total">0 lei</div>
        <button type="button" onclick="removeItem(this)" style="background:none;border:none;color:var(--text3);cursor:pointer;padding:4px;border-radius:5px;display:flex;flex-shrink:0">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
        </button>
    `;
    
    container.appendChild(row);
    recalcTotal();
}

function removeItem(btn) {
    btn.parentElement.remove();
    recalcTotal();
}

function changeQty(btn, change) {
    const input = btn.parentElement.querySelector('input[type="number"]');
    const newVal = Math.max(1, parseInt(input.value) + change);
    input.value = newVal;
    recalcTotal();
}

function recalcTotal() {
    const rows = document.querySelectorAll('.order-item-row');
    let subtotal = 0;
    
    rows.forEach((row, i) => {
        const price = parseFloat(row.querySelector('input[name="price[]"]').value) || 0;
        const qty = parseInt(row.querySelector('input[name="quantity[]"]').value) || 1;
        const rowTotal = price * qty;
        row.querySelector('.item-total').textContent = rowTotal.toFixed(2) + ' lei';
        subtotal += rowTotal;
    });
    
    // Calculate discount
    const discountSelect = document.querySelector('select[name="discount_id"]');
    const discountId = discountSelect.value;
    let discount = 0;
    
    if (discountId) {
        const disc = discounts.find(d => d.id == discountId);
        if (disc) {
            discount = disc.type === 'percent' ? Math.round(subtotal * disc.value / 100) : disc.value;
        }
    }
    
    // Calculate delivery
    const deliveryEnabled = document.getElementById('delivery-enabled').checked;
    const deliveryPrice = deliveryEnabled ? parseFloat(document.getElementById('delivery-price').value) || 0 : 0;
    
    const total = Math.max(0, subtotal - discount + deliveryPrice);
    
    // Update display
    document.getElementById('subtotal-display').textContent = subtotal.toFixed(2) + ' lei';
    
    if (discount > 0) {
        document.getElementById('discount-row').style.display = 'flex';
        document.getElementById('discount-display').textContent = '− ' + discount.toFixed(2) + ' lei';
    } else {
        document.getElementById('discount-row').style.display = 'none';
    }
    
    if (deliveryEnabled && deliveryPrice > 0) {
        document.getElementById('delivery-row').style.display = 'flex';
        document.getElementById('delivery-display').textContent = '+ ' + deliveryPrice.toFixed(2) + ' lei';
    } else {
        document.getElementById('delivery-row').style.display = 'none';
    }
    
    document.getElementById('total-display').textContent = total.toFixed(2) + ' lei';
}

// Initialize
recalcTotal();
</script>

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