<?php
/**
 * Template: account/addresses.php
 *
 * Address book management page.
 *
 * Available variables:
 *   $customer           — tc_customers row
 *   $billing_addresses  — Array of billing address rows
 *   $shipping_addresses — Array of shipping address rows
 *
 * Override: copy to your-theme/titancart/account/addresses.php
 *
 * @package TitanCart
 */
defined( 'ABSPATH' ) || exit;

$base_url = home_url( '/my-account/' );
$back_url = add_query_arg( 'tc_account_page', 'dashboard', $base_url );
$rest_url = esc_url_raw( rest_url( 'titancart/v1/account/addresses' ) );

// Address book gating: when OFF, only allow one address per type.
$_allow_multi = \TitanCart\Services\SettingsService::bool( 'general', 'customers_allow_multiple_profiles', true );
$_can_add_billing  = $_allow_multi || empty( $billing_addresses );
$_can_add_shipping = $_allow_multi || empty( $shipping_addresses );

/**
 * Render a single address card.
 *
 * @param  array  $addr     Address row.
 * @param  string $type     'billing' | 'shipping'
 * @return void
 */
function titancart_render_address_card( array $addr, string $type ): void {
    $id = (int) $addr['id'];
    ?>
    <div class="tc-address-card<?php echo $addr['is_default'] ? ' tc-address-card--default' : ''; ?>"
         data-id="<?php echo esc_attr( $id ); ?>"
         data-type="<?php echo esc_attr( $type ); ?>">

        <?php if ( $addr['is_default'] ) : ?>
            <span class="tc-address-card__badge"><?php esc_html_e( 'Default', 'titancart-lite' ); ?></span>
        <?php endif; ?>

        <address class="tc-address-card__body">
            <?php
            $lines = array_filter( [
                trim( ( $addr['first_name'] ?? '' ) . ' ' . ( $addr['last_name'] ?? '' ) ),
                $addr['company']   ?? '',
                $addr['address_1'] ?? '',
                $addr['address_2'] ?? '',
                trim( ( $addr['city'] ?? '' ) . ( ! empty( $addr['state'] ) ? ', ' . $addr['state'] : '' ) . ' ' . ( $addr['postcode'] ?? '' ) ),
                $addr['country']   ?? '',
                $addr['phone']     ?? '',
            ] );
            foreach ( $lines as $line ) {
                echo esc_html( $line ) . '<br>';
            }
            ?>
        </address>

        <div class="tc-address-card__actions">
            <?php if ( ! $addr['is_default'] ) : ?>
                <button class="tc-btn tc-btn--sm tc-btn--ghost js-set-default-address"
                        data-id="<?php echo esc_attr( $id ); ?>">
                    <?php esc_html_e( 'Set Default', 'titancart-lite' ); ?>
                </button>
            <?php endif; ?>
            <button class="tc-btn tc-btn--sm js-edit-address"
                    data-id="<?php echo esc_attr( $id ); ?>"
                    data-addr="<?php echo esc_attr( wp_json_encode( $addr ) ); ?>">
                <?php esc_html_e( 'Edit', 'titancart-lite' ); ?>
            </button>
            <button class="tc-btn tc-btn--sm tc-btn--danger js-delete-address"
                    data-id="<?php echo esc_attr( $id ); ?>">
                <?php esc_html_e( 'Delete', 'titancart-lite' ); ?>
            </button>
        </div>
    </div>
    <?php
}
?>

<div class="tc-addresses" id="tc-addresses-app">

    <div class="tc-page-header">
        <a href="<?php echo esc_url( $back_url ); ?>" class="tc-back-link">← <?php esc_html_e( 'My Account', 'titancart-lite' ); ?></a>
        <h2><?php esc_html_e( 'Address Book', 'titancart-lite' ); ?></h2>
    </div>

    <div class="tc-notice tc-notice--success" id="tc-addr-success" style="display:none;"></div>
    <div class="tc-notice tc-notice--error"   id="tc-addr-error"   style="display:none;"></div>

    <!-- ── Billing ──────────────────────────────────────────────────────── -->
    <div class="tc-address-section">
        <div class="tc-address-section__header">
            <h3><?php esc_html_e( 'Billing Addresses', 'titancart-lite' ); ?></h3>
            <?php if ( $_can_add_billing ) : ?>
            <button class="tc-btn tc-btn--sm js-add-address" data-type="billing">
                + <?php esc_html_e( 'Add Billing Address', 'titancart-lite' ); ?>
            </button>
            <?php endif; ?>
        </div>
        <div class="tc-address-grid" id="tc-billing-addresses">
            <?php if ( empty( $billing_addresses ) ) : ?>
                <p class="tc-empty-hint"><?php esc_html_e( 'No billing addresses saved.', 'titancart-lite' ); ?></p>
            <?php else : ?>
                <?php foreach ( $billing_addresses as $addr ) : titancart_render_address_card( $addr, 'billing' ); endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- ── Shipping ─────────────────────────────────────────────────────── -->
    <div class="tc-address-section">
        <div class="tc-address-section__header">
            <h3><?php esc_html_e( 'Shipping Addresses', 'titancart-lite' ); ?></h3>
            <?php if ( $_can_add_shipping ) : ?>
            <button class="tc-btn tc-btn--sm js-add-address" data-type="shipping">
                + <?php esc_html_e( 'Add Shipping Address', 'titancart-lite' ); ?>
            </button>
            <?php endif; ?>
        </div>
        <div class="tc-address-grid" id="tc-shipping-addresses">
            <?php if ( empty( $shipping_addresses ) ) : ?>
                <p class="tc-empty-hint"><?php esc_html_e( 'No shipping addresses saved.', 'titancart-lite' ); ?></p>
            <?php else : ?>
                <?php foreach ( $shipping_addresses as $addr ) : titancart_render_address_card( $addr, 'shipping' ); endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- ── Add / Edit Modal ─────────────────────────────────────────────── -->
    <div class="tc-modal" id="tc-address-modal" style="display:none;" role="dialog" aria-modal="true">
        <div class="tc-modal__overlay js-close-modal"></div>
        <div class="tc-modal__content">
            <button class="tc-modal__close js-close-modal" aria-label="<?php esc_attr_e( 'Close', 'titancart-lite' ); ?>">×</button>
            <h3 id="tc-modal-title"><?php esc_html_e( 'Add Address', 'titancart-lite' ); ?></h3>

            <form id="tc-address-form" class="tc-form">
                <input type="hidden" id="tc-addr-id"   name="id"   value="" />
                <input type="hidden" id="tc-addr-type" name="type" value="" />

                <div class="tc-form__row tc-form__row--split">
                    <div>
                        <label for="tc-addr-first"><?php esc_html_e( 'First Name *', 'titancart-lite' ); ?></label>
                        <input id="tc-addr-first" type="text" name="first_name" class="tc-input" required />
                    </div>
                    <div>
                        <label for="tc-addr-last"><?php esc_html_e( 'Last Name *', 'titancart-lite' ); ?></label>
                        <input id="tc-addr-last" type="text" name="last_name" class="tc-input" required />
                    </div>
                </div>

                <div class="tc-form__row">
                    <label for="tc-addr-company"><?php esc_html_e( 'Company', 'titancart-lite' ); ?></label>
                    <input id="tc-addr-company" type="text" name="company" class="tc-input" />
                </div>

                <div class="tc-form__row">
                    <label for="tc-addr-address1"><?php esc_html_e( 'Address Line 1 *', 'titancart-lite' ); ?></label>
                    <input id="tc-addr-address1" type="text" name="address_1" class="tc-input" data-tc-autocomplete="account" required />
                </div>

                <div class="tc-form__row">
                    <label for="tc-addr-address2"><?php esc_html_e( 'Address Line 2', 'titancart-lite' ); ?></label>
                    <input id="tc-addr-address2" type="text" name="address_2" class="tc-input" />
                </div>

                <div class="tc-form__row tc-form__row--split">
                    <div>
                        <label for="tc-addr-city"><?php esc_html_e( 'City *', 'titancart-lite' ); ?></label>
                        <input id="tc-addr-city" type="text" name="city" class="tc-input" required />
                    </div>
                    <div>
                        <label for="tc-addr-state"><?php esc_html_e( 'State / Province', 'titancart-lite' ); ?></label>
                        <input id="tc-addr-state" type="text" name="state" class="tc-input" />
                    </div>
                </div>

                <div class="tc-form__row tc-form__row--split">
                    <div>
                        <label for="tc-addr-postcode"><?php esc_html_e( 'Postcode / ZIP', 'titancart-lite' ); ?></label>
                        <input id="tc-addr-postcode" type="text" name="postcode" class="tc-input" />
                    </div>
                    <div>
                        <label for="tc-addr-country"><?php esc_html_e( 'Country Code *', 'titancart-lite' ); ?></label>
                        <input id="tc-addr-country" type="text" name="country" class="tc-input" maxlength="2" placeholder="US" required />
                    </div>
                </div>

                <div class="tc-form__row">
                    <label for="tc-addr-phone"><?php esc_html_e( 'Phone', 'titancart-lite' ); ?></label>
                    <input id="tc-addr-phone" type="tel" name="phone" class="tc-input" />
                </div>

                <div class="tc-form__row tc-form__actions">
                    <button type="submit" class="tc-btn tc-btn--primary" id="tc-addr-save">
                        <?php esc_html_e( 'Save Address', 'titancart-lite' ); ?>
                    </button>
                    <button type="button" class="tc-btn tc-btn--ghost js-close-modal">
                        <?php esc_html_e( 'Cancel', 'titancart-lite' ); ?>
                    </button>
                </div>
            </form>
        </div>
    </div><!-- .tc-modal -->

</div><!-- .tc-addresses -->

<?php
// WP.org R2: NOWDOC + strtr() slots, attached via wp_add_inline_script (stub handle, footer).
$tc_addr_rest_js    = wp_json_encode( $rest_url );
$tc_addr_nonce_js   = wp_json_encode( wp_create_nonce( 'wp_rest' ) );
$tc_addr_edit_js    = wp_json_encode( __( 'Edit Address', 'titancart-lite' ) );
$tc_addr_add_js     = wp_json_encode( __( 'Add Address', 'titancart-lite' ) );
$tc_addr_delq_js    = wp_json_encode( __( 'Delete this address?', 'titancart-lite' ) );
$tc_addr_saved_js   = wp_json_encode( __( 'Address saved.', 'titancart-lite' ) );
$tc_addr_inline_js  = <<<'JS'
(function(){
    var restUrl = %%REST%%;
    var nonce   = %%NONCE%%;

    function apiFetch(url, method, data) {
        var opts = {
            method: method || 'GET',
            headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json' },
        };
        if (data) opts.body = JSON.stringify(data);
        return fetch(url, opts).then(function(r){ return r.json().then(function(d){ return {ok: r.ok, data: d, status: r.status}; }); });
    }

    function showMsg(type, msg) {
        var el = document.getElementById('tc-addr-' + type);
        el.textContent = msg;
        el.style.display = 'block';
        setTimeout(function(){ el.style.display = 'none'; }, 5000);
    }

    function openModal(addr, type) {
        var modal = document.getElementById('tc-address-modal');
        var form  = document.getElementById('tc-address-form');
        document.getElementById('tc-modal-title').textContent = addr
            ? %%EDIT%%
            : %%ADD%%;
        form.reset();
        document.getElementById('tc-addr-id').value   = addr ? addr.id   : '';
        document.getElementById('tc-addr-type').value = addr ? addr.type : (type || 'shipping');
        if (addr) {
            ['first_name','last_name','company','address_1','address_2','city','state','postcode','country','phone'].forEach(function(f){
                var el = form.querySelector('[name="' + f + '"]');
                if (el) el.value = addr[f] || '';
            });
        }
        modal.style.display = 'flex';
    }

    function closeModal() {
        document.getElementById('tc-address-modal').style.display = 'none';
    }

    document.addEventListener('click', function(e){
        if (e.target.classList.contains('js-add-address')) {
            openModal(null, e.target.dataset.type);
        }
        if (e.target.classList.contains('js-edit-address')) {
            openModal(JSON.parse(e.target.dataset.addr), null);
        }
        if (e.target.classList.contains('js-close-modal')) {
            closeModal();
        }
        if (e.target.classList.contains('js-delete-address')) {
            if (!confirm(%%DELQ%%)) return;
            var id = e.target.dataset.id;
            apiFetch(restUrl + '/' + id, 'DELETE').then(function(r){
                if (r.ok || r.status === 204) { location.reload(); }
                else showMsg('error', (r.data && r.data.message) || 'Error');
            });
        }
        if (e.target.classList.contains('js-set-default-address')) {
            var id = e.target.dataset.id;
            apiFetch(restUrl + '/' + id + '/default', 'POST').then(function(r){
                if (r.ok) location.reload();
                else showMsg('error', (r.data && r.data.message) || 'Error');
            });
        }
    });

    document.getElementById('tc-address-form').addEventListener('submit', function(e){
        e.preventDefault();
        var data  = {};
        new FormData(this).forEach(function(v, k){ data[k] = v; });
        var id    = data.id;
        var url   = id ? restUrl + '/' + id : restUrl;
        var meth  = id ? 'PUT' : 'POST';
        delete data.id;
        apiFetch(url, meth, data).then(function(r){
            if (r.ok) {
                closeModal();
                showMsg('success', %%SAVED%%);
                setTimeout(function(){ location.reload(); }, 800);
            } else {
                showMsg('error', (r.data && r.data.message) || 'Error');
            }
        });
    });
}());
JS;
$tc_addr_inline_js = strtr( $tc_addr_inline_js, [
	'%%REST%%'  => $tc_addr_rest_js,
	'%%NONCE%%' => $tc_addr_nonce_js,
	'%%EDIT%%'  => $tc_addr_edit_js,
	'%%ADD%%'   => $tc_addr_add_js,
	'%%DELQ%%'  => $tc_addr_delq_js,
	'%%SAVED%%' => $tc_addr_saved_js,
] );
wp_register_script( 'titancart-addresses-inline', false, array(), TITANCART_VERSION, true );
wp_enqueue_script( 'titancart-addresses-inline' );
wp_add_inline_script( 'titancart-addresses-inline', $tc_addr_inline_js );
?>
