<?php
/**
 * @var array $suppliers
 * @var array $products
 */
?>
<div class="page-title mb-4">
    <h5><i class="fas fa-cart-plus me-2 text-gold"></i>Create Purchase Order</h5>
</div>

<div class="glass-card p-0">
    <div class="card-header">
        <div class="card-header-left">
            <i class="fas fa-shopping-cart card-icon"></i>
            <h6 class="card-title">Purchase Order Details</h6>
        </div>
        <div>
            <span class="text-muted small"><span class="text-danger">*</span> Required fields</span>
        </div>
    </div>
    <div class="card-body">
        <form method="POST" action="<?= url('purchases/store') ?>" id="poForm">
            <?= csrf_field() ?>

            <div class="row g-3 mb-4">
                <div class="col-md-4">
                    <div class="mb-3">
                        <label class="form-label">Supplier <span class="text-danger">*</span></label>
                        <select name="supplier_id" class="form-select bg-transparent <?= errorClass('supplier_id') ?>" required>
                            <option value="">Select Supplier</option>
                            <?php foreach ($suppliers as $sup): ?>
                                <option value="<?= $sup->id ?>" <?= old('supplier_id') == $sup->id ? 'selected' : '' ?>>
                                    <?= e($sup->name) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?= errorMsg('supplier_id') ?>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <label class="form-label">Expected Date</label>
                        <input type="date" name="expected_date" class="form-control bg-transparent <?= errorClass('expected_date') ?>"
                               value="<?= e(old('expected_date')) ?>">
                        <?= errorMsg('expected_date') ?>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control bg-transparent <?= errorClass('notes') ?>"
                                  rows="2" maxlength="2000"><?= e(old('notes')) ?></textarea>
                        <?= errorMsg('notes') ?>
                    </div>
                </div>
            </div>

            <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="mb-0"><i class="fas fa-list me-2 text-gold"></i>Order Items</h6>
                <button type="button" class="btn btn-sm btn-gold" onclick="addRow()">
                    <i class="fas fa-plus me-1"></i>Add Item
                </button>
            </div>

            <div class="table-responsive">
                <table class="table table-dark table-hover mb-0" id="itemsTable">
                    <thead>
                        <tr>
                            <th width="40%">Product</th>
                            <th width="15%" class="text-center">Quantity</th>
                            <th width="15%" class="text-end">Unit Cost</th>
                            <th width="15%" class="text-end">Total</th>
                            <th width="10%" class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="itemsBody">
                        <tr id="noItemsRow">
                            <td colspan="5" class="text-center text-muted py-3">
                                <i class="fas fa-box-open fa-2x mb-2"></i>
                                <p class="mb-0">No items added yet. Click "Add Item" to begin.</p>
                            </td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr>
                            <td colspan="3" class="text-end"><strong>Grand Total:</strong></td>
                            <td class="text-end"><strong id="grandTotal"><?= currency(0) ?></strong></td>
                            <td></td>
                        </tr>
                    </tfoot>
                </table>
            </div>

            <div class="mt-4 d-flex gap-2">
                <button type="submit" class="btn btn-gold">
                    <i class="fas fa-save me-1"></i>Create Purchase Order
                </button>
                <a href="<?= url('purchases') ?>" class="btn btn-outline-secondary">
                    <i class="fas fa-times me-1"></i>Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<?php
$productOptions = '<option value="">Select Product</option>';
foreach ($products as $p) {
    $productOptions .= '<option value="' . $p->id . '" data-price="' . e($p->cost_price ?? 0) . '" data-name="' . e($p->name) . '">' . e($p->name) . ' (' . e($p->sku) . ')</option>';
}
?>

<?php $inlineScripts = <<<'EOS'
var productOptions = `__PRODUCT_OPTIONS__`;
var rowCount = 0;

window.addRow = function(data) {
    rowCount++;
    var html = '<tr class="item-row" data-row="' + rowCount + '">';
    html += '<td><select name="items[' + rowCount + '][product_id]" class="form-select form-select-sm bg-transparent product-select" required onchange="updateRowTotal(this)">' + productOptions + '</select></td>';
    html += '<td><input type="number" name="items[' + rowCount + '][quantity]" class="form-control form-control-sm bg-transparent text-center qty-input" value="' + (data ? data.quantity : 1) + '" min="1" required onchange="updateRowTotal(this)"></td>';
    html += '<td><input type="number" step="0.01" name="items[' + rowCount + '][unit_cost]" class="form-control form-control-sm bg-transparent text-end cost-input" value="' + (data ? data.unit_cost : '0.00') + '" min="0" step="0.01" required onchange="updateRowTotal(this)"></td>';
    html += '<td class="text-end row-total">' + currency(0) + '</td>';
    html += '<td class="text-center"><button type="button" class="btn btn-sm btn-outline-danger" onclick="removeRow(this)"><i class="fas fa-trash"></i></button></td>';
    html += '</tr>';

    $('#noItemsRow').hide();
    $('#itemsBody').append(html);

    if (data && data.product_id) {
        var $select = $('#itemsBody tr:last .product-select');
        $select.val(data.product_id);
    }

    updateRowTotal($('#itemsBody tr:last .qty-input'));
};

window.removeRow = function(el) {
    $(el).closest('tr').remove();
    updateGrandTotal();
    if ($('#itemsBody .item-row').length === 0) {
        $('#noItemsRow').show();
    }
};

window.updateRowTotal = function(el) {
    var $row = $(el).closest('tr');
    var $select = $row.find('.product-select');
    var qty = parseFloat($row.find('.qty-input').val()) || 0;
    var cost = parseFloat($row.find('.cost-input').val()) || 0;

    if ($select.length && !$row.find('.cost-input').val() || $row.find('.cost-input').val() == '0') {
        var selectedPrice = $select.find('option:selected').data('price');
        if (selectedPrice) {
            $row.find('.cost-input').val(selectedPrice);
            cost = parseFloat(selectedPrice);
        }
    }

    var total = qty * cost;
    $row.find('.row-total').text(currency(total));
    updateGrandTotal();
};

window.updateGrandTotal = function() {
    var grandTotal = 0;
    $('.row-total').each(function() {
        var val = $(this).text().replace(/Rs\.\s*/g, '').replace(/,/g, '');
        grandTotal += parseFloat(val) || 0;
    });
    $('#grandTotal').text(currency(grandTotal));
};

window.currency = function(amount) {
    return 'Rs. ' + parseFloat(amount).toFixed(2);
};

$(document).ready(function() {
    $(document).on('change', '.product-select', function() {
        var $row = $(this).closest('tr');
        var price = $(this).find('option:selected').data('price');
        if (price) {
            $row.find('.cost-input').val(price);
        }
        updateRowTotal(this);
    });
});
EOS;
$inlineScripts = str_replace('__PRODUCT_OPTIONS__', $productOptions, $inlineScripts);
?>
