<?php
use Core\System\ThemeManager;

if (!isset($product)) {
    return;
}

$action = '/submit-order';

$price = (int) (($product['sale_price'] ?? 0) ?: ($product['price'] ?? 0));
$currency = ThemeManager::getSetting('currency', 'DA');
?>

<section class="home-section checkout-section" id="checkout">
    <div class="container">

        <div class="section-head">
            <h2><?= __('sections.checkout', 'Order Now') ?></h2>
        </div>

        <form action="<?= htmlspecialchars($action, ENT_QUOTES, 'UTF-8') ?>" method="post" class="checkout-form">

            <div class="form-group">
                <input type="text" name="full_name" placeholder="<?= __('checkout.name', 'Full Name') ?>" required>
            </div>

            <div class="form-group">
                <input type="tel" name="phone" placeholder="<?= __('checkout.phone', 'Phone Number') ?>" required>
            </div>

            <div class="form-group">
                <select id="state" disabled required>
                    <option value=""><?= __('checkout.state', 'State') ?></option>
                </select>
            </div>

            <div class="form-group">
                <select id="city" disabled required>
                    <option value=""><?= __('checkout.city', 'City') ?></option>
                </select>
            </div>

            <div class="form-group">
                <textarea name="address_extra" placeholder="<?= __('checkout.address', 'Full Address') ?>" required></textarea>
            </div>

            <div class="order-quantity">
                <button type="button" id="qty-minus">-</button>
                <input type="text" id="quantity" value="1" readonly>
                <button type="button" id="qty-plus">+</button>
            </div>

            <div class="order-summary">
                <div class="summary-row">
                    <span><?= __('checkout.product_price', 'Product Price') ?></span>
                    <span id="summary-product-price"></span>
                </div>

                <div class="summary-row">
                    <span><?= __('checkout.shipping', 'Shipping') ?></span>
                    <span id="summary-shipping-price"></span>
                </div>

                <div class="summary-row total">
                    <span><?= __('checkout.total', 'Total') ?></span>
                    <span id="summary-total-price"></span>
                </div>
            </div>

            <input type="hidden" name="quantity" id="quantity-input" value="1">
            <input type="hidden" name="total_amount" id="total-amount-input" value="">
            <input type="hidden" name="product_id" value="<?= htmlspecialchars((string)($product['id'] ?? ''), ENT_QUOTES, 'UTF-8') ?>">

            <button type="submit" class="product-btn checkout-btn">
                <?= __('actions.confirm_order', 'Confirm Order') ?>
            </button>

        </form>

        <!-- Spacer to avoid footer being visually covered by sticky bar on some layouts -->
        <div style="height:120px"></div>

    </div>
</section>

<script>
(function () {
    const state = document.getElementById('state');
    const city  = document.getElementById('city');

    const qtyMinus  = document.getElementById('qty-minus');
    const qtyPlus   = document.getElementById('qty-plus');
    const qtyInput  = document.getElementById('quantity');
    const qtyHidden = document.getElementById('quantity-input');

    const summaryProduct  = document.getElementById('summary-product-price');
    const summaryShipping = document.getElementById('summary-shipping-price');
    const summaryTotal    = document.getElementById('summary-total-price');
    const totalInput      = document.getElementById('total-amount-input');

    const productPrice = <?= (int)$price ?>;
    const currency = <?= json_encode($currency) ?>;
    let shippingPrice = 0;
    let shippingDisplayText = null;
    let shippingUsesCustomText = false;

    function updateSummary() {
        const qty = parseInt(qtyInput.value || '1', 10);
        const productTotal = productPrice * qty;
        const total = productTotal + shippingPrice;

        summaryProduct.textContent  = productTotal + ' ' + currency;
        summaryShipping.textContent = shippingDisplayText ? shippingDisplayText : (shippingPrice === 0 ? <?= json_encode(__('shipping.free','Free')) ?> : (shippingPrice + ' ' + currency));
        summaryTotal.textContent    = shippingUsesCustomText ? <?= json_encode(__('shipping.total_pending_with_shipping','Total after shipping confirmation')) ?> : (total + ' ' + currency);

        qtyHidden.value = qty;
        totalInput.value = total;
    }

    qtyPlus.addEventListener('click', () => {
        qtyInput.value = String(parseInt(qtyInput.value || '1', 10) + 1);
        updateSummary();
    });

    qtyMinus.addEventListener('click', () => {
        const current = parseInt(qtyInput.value || '1', 10);
        if (current > 1) {
            qtyInput.value = String(current - 1);
            updateSummary();
        }
    });

    fetch('/api/dz/states')
        .then(r => r.json())
        .then(data => {
            state.innerHTML = '<option value=""><?= __('checkout.state', 'State') ?></option>';
            (data || []).forEach(s => {
                const code = String(s.code).padStart(2, '0');
                const label = `${code} ${s.name} - ${s.ar_name || ''}`.trim();
                state.innerHTML += `<option value="${code}" data-state-name="${s.name}">${label}</option>`;
            });
            state.disabled = false;
        })
        .catch(() => {});

    state.addEventListener('change', function () {
        const code = this.value;
        if (!code) return;

        fetch('/api/dz/cities/' + encodeURIComponent(code))
            .then(r => r.json())
            .then(data => {
                city.innerHTML = '<option value=""><?= __('checkout.city', 'City') ?></option>';
                (data || []).forEach(c => {
                    city.innerHTML += `<option value="${c.id}" data-city-name="${c.name}">${c.name}</option>`;
                });
                city.disabled = false;
            })
            .catch(() => {});
    });

    city.addEventListener('change', function () {
        const cityId = this.value;
        const stateCode = state.value;
        if (!cityId || !stateCode) return;

        fetch('/api/shipping/price/' + encodeURIComponent(stateCode) + '/' + encodeURIComponent(cityId) + '?shipping_type=home')
            .then(r => r.json())
            .then(data => {
                shippingDisplayText = data && data.display_text ? String(data.display_text) : null;
                shippingUsesCustomText = !!(data && data.uses_custom_text);
                shippingPrice = (data && data.price !== null && data.price !== undefined && data.price !== '') ? (parseInt(data.price, 10) || 0) : 0;
                updateSummary();
            })
            .catch(() => {});
    });

    updateSummary();
})();
</script>
