<div class="row">
    <div class="col-sm-12">
        <div class="page-title-box">
            <h2 class="page-title">Outlet-wise Tax Overrides
                <a href="add_outlet_tax" class="btn btn-success btn-sm" style="float:right">
					+ Add Override
				</a>
            </h2>
        </div>
    </div>
</div>

<!-- Info banner -->
<div class="alert alert-info">
    <strong>How this works:</strong> When a POS terminal syncs products, it will use the outlet-specific tax rate if one is configured here. If no override exists, the global product tax applies. Leave <em>Effective From</em> blank to activate immediately.
</div>

<!-- Overrides table -->
<div class="row">
    <div class="col-sm-12">
        <div class="card">
            <div class="card-body">
                <table class="table table-bordered table-hover table-sm" id="overridesTable">
                    <thead class="thead-dark">
                        <tr>
                            <th>#</th>
                            <th>Product</th>
                            <th>Outlet</th>
                            <th>Tax Name</th>
                            <th>Override %</th>
                            <th>Effective From</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($overrides)): ?>
                        <tr><td colspan="7" class="text-center text-muted">No overrides configured yet.</td></tr>
                        <?php else: ?>
                        <?php foreach ($overrides as $ov): $o = $ov['Catalog_product_tax_outlet']; ?>
                        <tr>
                            <td><?= $o['id'] ?></td>
                            <td><?= h($o['product_name']) ?></td>
                            <td><?= h($o['outlet_name']) ?></td>
                            <td><?= h($o['tax_name']) ?></td>
                            <td><strong><?= $o['tax_percentage'] ?>%</strong></td>
                            <td><?= $o['effective_from'] ?? '—' ?></td>
                            <td>
                                <button class="btn btn-danger btn-xs btn-delete-override" data-id="<?= $o['id'] ?>">Delete</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Add Override Modal -->
<div class="modal fade" id="addOverrideModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Outlet Tax Override</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>Product <span class="text-danger">*</span></label>
                    <select id="sel_product" class="form-control">
                        <option value="">-- Select Product --</option>
                        <?php foreach ($products as $p): ?>
                        <option value="<?= $p['Catalog_product']['id'] ?>"><?= h($p['Catalog_product']['cat_name']) ?> / <?= h($p['Catalog_product']['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Outlet <span class="text-danger">*</span></label>
                    <select id="sel_outlet" class="form-control">
                        <option value="">-- Select Outlet --</option>
                        <?php foreach ($outlets as $out): ?>
                        <option value="<?= $out['Location']['id'] ?>"><?= h($out['Location']['name']) ?><?= $out['Location']['state'] ? ' (' . h($out['Location']['state']) . ')' : '' ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Tax <span class="text-danger">*</span></label>
                    <select id="sel_tax" class="form-control" onchange="autoFillPct(this)">
                        <option value="">-- Select Tax --</option>
                        <?php foreach ($taxes as $t): ?>
                        <option value="<?= $t['Catalog_tax']['id'] ?>" data-pct="<?= $t['Catalog_tax']['percentage'] ?>"><?= h($t['Catalog_tax']['name']) ?> (<?= $t['Catalog_tax']['percentage'] ?>%)</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Override Tax % <span class="text-danger">*</span></label>
                    <input type="number" id="inp_pct" class="form-control" step="0.01" min="0" max="100" placeholder="e.g. 9">
                    <small class="text-muted">Enter the outlet-specific rate. This overrides the default.</small>
                </div>
                <div class="form-group">
                    <label>Effective From <small class="text-muted">(optional — blank = immediate)</small></label>
                    <input type="date" id="inp_effdate" class="form-control">
                </div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button class="btn btn-success" id="btnSaveOverride">Save Override</button>
            </div>
        </div>
    </div>
</div>

<script>

$(document).ready(function () {

    $('#overridesTable').DataTable({
        paging: true,
        searching: true,   // ✅ enable search here (no custom search in this page)
        ordering: true,    // ✅ sorting is safe here
        info: true,
        lengthChange: true,
        pageLength: 10,
        columnDefs: [
            { orderable: false, targets: 6 } // ❌ disable sorting on Action column
        ]
    });

});

function autoFillPct(sel) {
    var pct = $(sel).find(':selected').data('pct');
    if (pct !== undefined) { $('#inp_pct').val(pct); }
}

$(document).on('click', '#btnSaveOverride', function () {
    var product_id    = $('#sel_product').val();
    var outlet_id     = $('#sel_outlet').val();
    var tax_id        = $('#sel_tax').val();
    var tax_pct       = $('#inp_pct').val();
    var effective_from = $('#inp_effdate').val();

    if (!product_id || !outlet_id || !tax_id || tax_pct === '') {
        Swal.fire('Missing Fields', 'Please fill all required fields.', 'warning');
        return;
    }

    $.ajax({
        url: '<?= Router::url(['controller' => 'Dashboard', 'action' => 'save_outlet_tax']) ?>',
        type: 'POST',
        dataType: 'json',
        data: { product_id: product_id, outlet_id: outlet_id, tax_id: tax_id,
                tax_percentage: tax_pct, effective_from: effective_from },
        success: function (res) {
            if (res.status) {
                Swal.fire('Saved!', res.message, 'success').then(() => location.reload());
            } else {
                Swal.fire('Error', res.message, 'error');
            }
        }
    });
});

$(document).on('click', '.btn-delete-override', function () {
    var id = $(this).data('id');
    Swal.fire({ title: 'Delete override?', icon: 'warning', showCancelButton: true, confirmButtonText: 'Yes, delete' }).then(function (result) {
        if (result.isConfirmed) {
            $.ajax({
                url: '<?= Router::url(['controller' => 'Dashboard', 'action' => 'delete_outlet_tax']) ?>',
                type: 'POST', dataType: 'json',
                data: { id: id },
                success: function (res) {
                    if (res.status) { location.reload(); }
                    else { Swal.fire('Error', res.message, 'error'); }
                }
            });
        }
    });
});
</script>
