<?php
session_start();

require_once '../../config/database.php';
require_once '../../includes/auth.php';

$basePath = '../../';
include '../../includes/header.php';

$db = (new Database())->connect();

/*
    Load items
*/
$stmt = $db->prepare("
    SELECT
        i.id,
        i.name,
        i.unit_id,
        u.name AS unit_name
    FROM items i
    LEFT JOIN units u ON i.unit_id = u.id
    ORDER BY i.name ASC
");

$stmt->execute();
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="container mt-4">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3>Bulk Stock Entry</h3>

        <a href="index.php" class="btn btn-secondary">
            Back to Stock
        </a>
    </div>

    <div class="card shadow-sm">
        <div class="card-body">

            <form action="save_bulk_stock.php" method="POST">

                <!-- HEADER -->
                <div class="row mb-4">

                    <div class="col-md-3">
                        <label class="form-label">Stock Date</label>
                        <input
                            type="date"
                            name="stock_date"
                            class="form-control"
                            value="<?= date('Y-m-d') ?>"
                            required
                        >
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Reference No.</label>
                        <input
                            type="text"
                            name="reference"
                            class="form-control"
                            placeholder="Invoice / Purchase Ref"
                        >
                    </div>

                    <div class="col-md-5">
                        <label class="form-label">Remarks</label>
                        <input
                            type="text"
                            name="remarks"
                            class="form-control"
                            placeholder="Optional remarks"
                        >
                    </div>

                </div>

                <!-- GRID -->
                <div class="table-responsive">
                    <table class="table table-bordered" id="bulkTable">

                        <thead class="table-dark">
                            <tr>
                                <th>Item</th>
                                <th width="120">Unit</th>
                                <th width="120">Qty</th>
                                <th width="120">Rate</th>
                                <th width="140">Total</th>
                                <th width="100">Action</th>
                            </tr>
                        </thead>

                        <tbody id="bulkBody">
                        </tbody>

                    </table>
                </div>

                <button
                    type="button"
                    class="btn btn-primary mb-3"
                    onclick="addRow()"
                >
                    Add Row
                </button>

                <br>

                <button type="submit" class="btn btn-success">
                    Save Bulk Entry
                </button>

            </form>

        </div>
    </div>

</div>

<script>
const items = <?= json_encode($items) ?>;

function addRow()
{
    let tbody = document.getElementById('bulkBody');
    let rowIndex = tbody.rows.length;

    let itemOptions = '<option value="">Select Item</option>';

    items.forEach(item => {
        itemOptions += `
            <option
                value="${item.id}"
                data-unit="${item.unit_id}"
                data-unitname="${item.unit_name || ''}"
            >
                ${item.name}
            </option>
        `;
    });

    let row = `
        <tr>

            <td>
                <select
                    name="item_id[]"
                    class="form-select item-select"
                    onchange="updateUnit(this)"
                    required
                >
                    ${itemOptions}
                </select>
            </td>

            <td>
                <input
                    type="text"
                    class="form-control unit-name"
                    readonly
                >

                <input
                    type="hidden"
                    name="unit_id[]"
                    class="unit-id"
                >
            </td>

            <td>
                <input
                    type="number"
                    step="0.01"
                    min="0.01"
                    name="qty[]"
                    class="form-control qty"
                    oninput="calculateRow(this)"
                    required
                >
            </td>

            <td>
                <input
                    type="number"
                    step="0.01"
                    min="0"
                    name="rate[]"
                    class="form-control rate"
                    oninput="calculateRow(this)"
                    required
                >
            </td>

            <td>
                <input
                    type="number"
                    step="0.01"
                    name="total[]"
                    class="form-control total"
                    readonly
                >
            </td>

            <td>
                <button
                    type="button"
                    class="btn btn-danger"
                    onclick="removeRow(this)"
                >
                    Remove
                </button>
            </td>

        </tr>
    `;

    tbody.insertAdjacentHTML('beforeend', row);
}

function updateUnit(select)
{
    let selected = select.options[select.selectedIndex];
    let row = select.closest('tr');

    row.querySelector('.unit-name').value =
        selected.dataset.unitname || '';

    row.querySelector('.unit-id').value =
        selected.dataset.unit || '';
}

function calculateRow(input)
{
    let row = input.closest('tr');

    let qty = parseFloat(row.querySelector('.qty').value) || 0;
    let rate = parseFloat(row.querySelector('.rate').value) || 0;

    row.querySelector('.total').value = (qty * rate).toFixed(2);
}

function removeRow(button)
{
    button.closest('tr').remove();
}

/*
    Start with one row
*/
addRow();
</script>

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