<?php
include 'includes/tax_helpers.php';

// Get current settings
$tax_method = getTaxCalculationMethod($conn);
$payment_tax_rates = getAllPaymentMethodTaxRates($conn);
$show_tax_rates = shouldShowPaymentMethodTaxRates($conn);
$enable_preview = isTaxPreviewEnabled($conn);

// Get all payment methods
$payment_methods = [];
$pm_result = $conn->query("SELECT method_name, display_name FROM payment_methods WHERE is_active = 1 ORDER BY sort_order");
while ($row = $pm_result->fetch_assoc()) {
    $payment_methods[] = $row;
}

// Get setting IDs for the existing update system
$tax_method_setting = $conn->query("SELECT id FROM settings WHERE code = 'tax_calculation_method'")->fetch_assoc();
$show_rates_setting = $conn->query("SELECT id FROM settings WHERE code = 'show_payment_method_tax_rates'")->fetch_assoc();
$enable_preview_setting = $conn->query("SELECT id FROM settings WHERE code = 'enable_tax_preview_on_payment'")->fetch_assoc();
?>

<!-- Tax Calculation Method Setting -->
<div class="col-xxl-4 col-xl-6 col-lg-12 col-md-6 d-flex mb-3">
    <div class="connected-app-card d-flex w-100">
        <ul class="w-100">
            <li class="flex-column align-items-start">
                <div class="d-flex align-items-center justify-content-between w-100">
                    <div class="security-type d-flex align-items-center">
                        <span class="system-app-icon">
                            <i data-feather="percent"></i>
                        </span>
                        <div class="security-title ms-2">
                            <h5>Tax Calculation Method</h5>
                        </div>
                    </div>
                </div>
                <p>Choose how taxes are calculated: item-wise (per item) or payment method based (uniform rate per payment type)</p>
                
                <select class="form-select mt-2" onchange="updateTaxMethod(this.value)">
                    <option value="item_wise" <?= $tax_method === 'item_wise' ? 'selected' : '' ?>>
                        Item-wise Tax (Current System)
                    </option>
                    <option value="payment_method" <?= $tax_method === 'payment_method' ? 'selected' : '' ?>>
                        Payment Method Tax
                    </option>
                </select>
            </li>
        </ul>
    </div>
</div>

<!-- Show Payment Method Tax Rates Setting -->
<div class="col-xxl-4 col-xl-6 col-lg-12 col-md-6 d-flex mb-3">
    <div class="connected-app-card d-flex w-100">
        <ul class="w-100">
            <li class="flex-column align-items-start">
                <div class="d-flex align-items-center justify-content-between w-100">
                    <div class="security-type d-flex align-items-center">
                        <span class="system-app-icon">
                            <i data-feather="eye"></i>
                        </span>
                        <div class="security-title ms-2">
                            <h5>Show Payment Method Tax Rates</h5>
                        </div>
                    </div>
                    <div class="status-toggle d-flex align-items-center ms-2">
                        <input type="checkbox" 
                               id="show_payment_method_tax_rates" 
                               class="check setting-toggle" 
                               data-id="<?= $show_rates_setting['id'] ?? '' ?>"
                               <?= $show_tax_rates ? 'checked' : '' ?>>
                        <label for="show_payment_method_tax_rates" class="checktoggle"></label>
                    </div>
                </div>
                <p>Display tax rates for different payment methods on POS interface</p>
            </li>
        </ul>
    </div>
</div>

<!-- Enable Tax Preview Setting -->
<div class="col-xxl-4 col-xl-6 col-lg-12 col-md-6 d-flex mb-3">
    <div class="connected-app-card d-flex w-100">
        <ul class="w-100">
            <li class="flex-column align-items-start">
                <div class="d-flex align-items-center justify-content-between w-100">
                    <div class="security-type d-flex align-items-center">
                        <span class="system-app-icon">
                            <i data-feather="refresh-cw"></i>
                        </span>
                        <div class="security-title ms-2">
                            <h5>Enable Tax Preview on Payment Selection</h5>
                        </div>
                    </div>
                    <div class="status-toggle d-flex align-items-center ms-2">
                        <input type="checkbox" 
                               id="enable_tax_preview_on_payment" 
                               class="check setting-toggle" 
                               data-id="<?= $enable_preview_setting['id'] ?? '' ?>"
                               <?= $enable_preview ? 'checked' : '' ?>>
                        <label for="enable_tax_preview_on_payment" class="checktoggle"></label>
                    </div>
                </div>
                <p>Show updated tax amount when payment method is selected (for payment method tax mode)</p>
            </li>
        </ul>
    </div>
</div>

<!-- Payment Method Tax Rates Section -->
<?php if ($tax_method === 'payment_method'): ?>
<div class="col-12 mb-3">
    <div class="card">
        <div class="card-header">
            <h5 class="card-title">Payment Method Tax Rates</h5>
        </div>
        <div class="card-body">
            <div class="row">
                <?php foreach ($payment_methods as $pm): ?>
                    <div class="col-md-6 mb-3">
                        <div class="connected-app-card d-flex w-100">
                            <ul class="w-100">
                                <li class="flex-column align-items-start">
                                    <div class="d-flex align-items-center justify-content-between w-100">
                                        <div class="security-type d-flex align-items-center">
                                            <span class="system-app-icon">
                                                <i data-feather="credit-card"></i>
                                            </span>
                                            <div class="security-title ms-2">
                                                <h5><?= htmlspecialchars($pm['display_name']) ?></h5>
                                            </div>
                                        </div>
                                    </div>
                                    <p>Tax rate for <?= htmlspecialchars($pm['display_name']) ?> payments</p>
                                    
                                    <div class="d-flex align-items-center">
                                        <input type="number" 
                                               class="form-control me-2" 
                                               step="0.01" 
                                               min="0" 
                                               max="100" 
                                               value="<?= htmlspecialchars($payment_tax_rates[$pm['method_name']] ?? 0) ?>"
                                               onchange="updatePaymentMethodTaxRate('<?= htmlspecialchars($pm['method_name']) ?>', this.value)"
                                               style="width: 100px;">
                                        <span class="text-muted">%</span>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>
<?php endif; ?>

<script>
function updateTaxMethod(value) {
    // Use the existing update_setting.php mechanism
    const settingId = <?= $tax_method_setting['id'] ?? 'null' ?>;
    if (settingId) {
        fetch('update_setting.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `id=${settingId}&value=${encodeURIComponent(value)}`
        })
        .then(res => res.text())
        .then(msg => {
            if (typeof Swal !== 'undefined') {
                Swal.fire({
                    toast: true,
                    icon: 'success',
                    title: 'Tax method updated',
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 1200
                });
            }
            
            // Reload the page to refresh the payment rates section
            setTimeout(() => {
                location.reload();
            }, 1500);
        })
        .catch(() => alert('Error updating tax method'));
    }
}

function updatePaymentMethodTaxRate(paymentMethod, taxRate) {
    // Direct database update for payment method tax rates
    fetch('ajax/update_payment_method_tax_rate.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `payment_method=${paymentMethod}&tax_rate=${encodeURIComponent(taxRate)}`
    })
    .then(res => res.text())
    .then(msg => {
        if (typeof Swal !== 'undefined') {
            Swal.fire({
                toast: true,
                icon: 'success',
                title: 'Tax rate updated',
                position: 'top-end',
                showConfirmButton: false,
                timer: 1200
            });
        }
    })
    .catch(() => alert('Error updating tax rate'));
}
</script>
