<?php
/**
 * Template: account/profile.php
 *
 * Edit profile: name, email, phone, and password change.
 *
 * Available variables:
 *   $customer — tc_customers row (array)
 *   $message  — Success or error message string (may be empty)
 *
 * Override: copy to your-theme/titancart/account/profile.php
 *
 * @package TitanCart
 */
defined( 'ABSPATH' ) || exit;

$base_url = home_url( '/my-account/' );
$back_url = add_query_arg( 'tc_account_page', 'dashboard', $base_url );

$message_type = ( ! empty( $message ) && str_contains( strtolower( $message ), 'error' ) )
    ? 'error'
    : 'success';
?>

<div class="tc-account-profile">

    <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( 'Edit Profile', 'titancart-lite' ); ?></h2>
    </div>

    <?php if ( ! empty( $message ) ) : ?>
        <div class="tc-notice tc-notice--<?php echo esc_attr( $message_type ); ?>">
            <?php echo esc_html( $message ); ?>
        </div>
    <?php endif; ?>

    <form class="tc-form tc-profile-form" method="post">
        <?php wp_nonce_field( 'tc_profile_' . get_current_user_id() ); ?>
        <input type="hidden" name="tc_update_profile" value="1" />

        <fieldset class="tc-form__group">
            <legend><?php esc_html_e( 'Personal Information', 'titancart-lite' ); ?></legend>

            <div class="tc-form__row tc-form__row--split">
                <div>
                    <label for="tc-prof-first"><?php esc_html_e( 'First Name', 'titancart-lite' ); ?></label>
                    <input id="tc-prof-first"
                           type="text"
                           name="first_name"
                           class="tc-input"
                           value="<?php echo esc_attr( $customer['first_name'] ?? '' ); ?>" />
                </div>
                <div>
                    <label for="tc-prof-last"><?php esc_html_e( 'Last Name', 'titancart-lite' ); ?></label>
                    <input id="tc-prof-last"
                           type="text"
                           name="last_name"
                           class="tc-input"
                           value="<?php echo esc_attr( $customer['last_name'] ?? '' ); ?>" />
                </div>
            </div>

            <div class="tc-form__row">
                <label for="tc-prof-email"><?php esc_html_e( 'Email Address', 'titancart-lite' ); ?></label>
                <input id="tc-prof-email"
                       type="email"
                       name="email"
                       class="tc-input"
                       required
                       value="<?php echo esc_attr( $customer['email'] ?? '' ); ?>" />
            </div>

            <div class="tc-form__row">
                <label for="tc-prof-phone"><?php esc_html_e( 'Phone Number', 'titancart-lite' ); ?></label>
                <input id="tc-prof-phone"
                       type="tel"
                       name="phone"
                       class="tc-input"
                       value="<?php echo esc_attr( $customer['phone'] ?? '' ); ?>" />
            </div>

            <div class="tc-form__row">
                <label for="tc-prof-dob"><?php esc_html_e( 'Date of Birth', 'titancart-lite' ); ?></label>
                <input id="tc-prof-dob"
                       type="date"
                       name="date_of_birth"
                       class="tc-input"
                       max="<?php echo esc_attr( current_time( 'Y-m-d' ) ); ?>"
                       value="<?php echo esc_attr( $customer['date_of_birth'] ?? '' ); ?>" />
                <?php if ( \TitanCart\REST\Extensions\ExtensionsController::is_active( 'rewards' ) ) : ?>
                <span class="tc-field-hint"><?php esc_html_e( 'Optional — add your birthday to receive a reward each year.', 'titancart-lite' ); ?></span>
                <?php else : ?>
                <span class="tc-field-hint"><?php esc_html_e( 'Optional.', 'titancart-lite' ); ?></span>
                <?php endif; ?>
            </div>
        </fieldset>

        <?php
        // Custom (non-system) contact fields configured via Customer Fields admin
        // page (S127.C-1). Only renders when admin has marked at least one
        // non-system field visible. Pre-fills from tc_customer_field_values.
        $_fields_manager = new \TitanCart\Modules\Accounts\CustomerFieldsManager();
        $_custom_html    = $_fields_manager->render_section_html(
            'contact',
            (int) ( $customer['id'] ?? 0 ),
            'tc-prof-cf-'
        );
        if ( $_custom_html !== '' ) :
        ?>
        <fieldset class="tc-form__group">
            <legend><?php esc_html_e( 'Additional Information', 'titancart-lite' ); ?></legend>
            <?php echo wp_kses( $_custom_html, \TitanCart\Modules\Accounts\CustomerFieldsManager::form_kses_allowed() ); ?>
        </fieldset>
        <?php endif; ?>

        <fieldset class="tc-form__group">
            <legend><?php esc_html_e( 'Change Password', 'titancart-lite' ); ?></legend>
            <p class="tc-field-hint"><?php esc_html_e( 'Leave blank to keep your current password.', 'titancart-lite' ); ?></p>

            <div class="tc-form__row">
                <label for="tc-prof-cur-pass"><?php esc_html_e( 'Current Password', 'titancart-lite' ); ?></label>
                <input id="tc-prof-cur-pass"
                       type="password"
                       name="current_password"
                       class="tc-input"
                       autocomplete="current-password" />
            </div>

            <div class="tc-form__row">
                <label for="tc-prof-new-pass"><?php esc_html_e( 'New Password', 'titancart-lite' ); ?></label>
                <input id="tc-prof-new-pass"
                       type="password"
                       name="new_password"
                       class="tc-input"
                       minlength="6"
                       autocomplete="new-password" />
                <span class="tc-field-hint"><?php esc_html_e( 'At least 6 characters', 'titancart-lite' ); ?></span>
            </div>
        </fieldset>

        <div class="tc-form__row tc-form__actions">
            <button type="submit" class="tc-btn tc-btn--primary">
                <?php esc_html_e( 'Save Changes', 'titancart-lite' ); ?>
            </button>
            <a href="<?php echo esc_url( $back_url ); ?>" class="tc-btn tc-btn--ghost">
                <?php esc_html_e( 'Cancel', 'titancart-lite' ); ?>
            </a>
        </div>
    </form>

    <?php
    // Delete Account section — gated by admin setting.
    $show_delete = \TitanCart\Services\SettingsService::get( 'customers', 'customers_show_delete_account', '0' );
    if ( $show_delete === '1' || $show_delete === 'Y' ) :
        $delete_url = esc_url_raw( rest_url( 'titancart/v1/account/delete' ) );
        $del_nonce  = wp_create_nonce( 'wp_rest' );
    ?>
    <div class="tc-account-delete" style="margin-top:48px; padding-top:24px; border-top:1px solid #E5E5E5;">
        <h3 style="font-size:15px; font-weight:600; color:#DC2626; margin:0 0 8px;">
            <?php esc_html_e( 'Delete My Account', 'titancart-lite' ); ?>
        </h3>
        <p style="font-size:13px; color:#737373; margin:0 0 16px; max-width:480px; line-height:1.6;">
            <?php esc_html_e( 'This action is permanent and cannot be undone. All your personal data, addresses, wishlists, and account access will be removed. Your order history will be preserved for our records but anonymized.', 'titancart-lite' ); ?>
        </p>
        <button type="button" id="tc-delete-account-btn" class="tc-btn" style="background:#DC2626; color:#fff; border:none; padding:10px 20px; border-radius:8px; font-size:13px; font-weight:600; cursor:pointer;">
            <?php esc_html_e( 'Delete My Account', 'titancart-lite' ); ?>
        </button>

        <!-- Confirmation modal -->
        <div id="tc-delete-modal" style="display:none; position:fixed; top:0; left:0; right:0; bottom:0; z-index:9999; background:rgba(0,0,0,0.5); align-items:center; justify-content:center;">
            <div style="background:#fff; border-radius:12px; padding:32px; max-width:420px; width:90%; text-align:center; box-shadow:0 20px 60px rgba(0,0,0,0.2);">
                <div style="font-size:36px; margin-bottom:12px;">⚠️</div>
                <h3 style="font-size:18px; font-weight:700; color:#0A0A0A; margin:0 0 8px;">
                    <?php esc_html_e( 'Are you sure?', 'titancart-lite' ); ?>
                </h3>
                <p style="font-size:13px; color:#737373; margin:0 0 20px; line-height:1.6;">
                    <?php esc_html_e( 'Type DELETE below to confirm you want to permanently delete your account and all associated data.', 'titancart-lite' ); ?>
                </p>
                <input type="text" id="tc-delete-confirm-input" placeholder="DELETE"
                       style="width:100%; padding:10px 14px; border:1px solid #E5E5E5; border-radius:8px; font-size:14px; text-align:center; margin-bottom:16px; outline:none; font-family:monospace; letter-spacing:2px;" />
                <div style="display:flex; gap:10px; justify-content:center;">
                    <button type="button" id="tc-delete-cancel" style="padding:10px 24px; border:1px solid #E5E5E5; border-radius:8px; background:#fff; color:#737373; font-size:13px; font-weight:500; cursor:pointer;">
                        <?php esc_html_e( 'Cancel', 'titancart-lite' ); ?>
                    </button>
                    <button type="button" id="tc-delete-confirm" disabled
                            style="padding:10px 24px; border:none; border-radius:8px; background:#DC2626; color:#fff; font-size:13px; font-weight:600; cursor:pointer; opacity:0.5;">
                        <?php esc_html_e( 'Delete Forever', 'titancart-lite' ); ?>
                    </button>
                </div>
            </div>
        </div>

        <?php
        // WP.org R2: NOWDOC + strtr() slots, attached via wp_add_inline_script (stub handle, footer).
        $tc_del_url_js   = wp_json_encode( $delete_url );
        $tc_del_nonce_js = wp_json_encode( $del_nonce );
        $tc_del_home_js  = wp_json_encode( home_url( '/' ) );
        $tc_profile_inline_js = <<<'JS'
        (function() {
            var btn      = document.getElementById('tc-delete-account-btn');
            var modal    = document.getElementById('tc-delete-modal');
            var input    = document.getElementById('tc-delete-confirm-input');
            var cancel   = document.getElementById('tc-delete-cancel');
            var confirm  = document.getElementById('tc-delete-confirm');
            var url      = %%URL%%;
            var nonce    = %%NONCE%%;

            btn.addEventListener('click', function() {
                modal.style.display = 'flex';
                input.value = '';
                confirm.disabled = true;
                confirm.style.opacity = '0.5';
                input.focus();
            });

            cancel.addEventListener('click', function() { modal.style.display = 'none'; });
            modal.addEventListener('click', function(e) { if (e.target === modal) modal.style.display = 'none'; });

            input.addEventListener('input', function() {
                var ok = input.value.trim() === 'DELETE';
                confirm.disabled = !ok;
                confirm.style.opacity = ok ? '1' : '0.5';
            });

            confirm.addEventListener('click', function() {
                confirm.disabled = true;
                confirm.textContent = 'Deleting…';
                fetch(url, {
                    method: 'DELETE',
                    headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json' },
                })
                .then(function(r) { return r.json(); })
                .then(function(d) {
                    if (d.deleted) {
                        modal.querySelector('div > div').innerHTML =
                            '<div style="font-size:36px;margin-bottom:12px;">👋</div>' +
                            '<h3 style="font-size:18px;font-weight:700;color:#0A0A0A;margin:0 0 8px;">Account Deleted</h3>' +
                            '<p style="font-size:13px;color:#737373;margin:0 0 20px;">Your account has been permanently deleted. Redirecting…</p>';
                        setTimeout(function() { window.location.href = %%HOME%%; }, 2000);
                    } else {
                        alert(d.message || 'Failed to delete account.');
                        confirm.disabled = false;
                        confirm.textContent = 'Delete Forever';
                    }
                })
                .catch(function() {
                    alert('Network error. Please try again.');
                    confirm.disabled = false;
                    confirm.textContent = 'Delete Forever';
                });
            });
        })();
JS;
        $tc_profile_inline_js = strtr( $tc_profile_inline_js, [ '%%URL%%' => $tc_del_url_js, '%%NONCE%%' => $tc_del_nonce_js, '%%HOME%%' => $tc_del_home_js ] );
        wp_register_script( 'titancart-profile-inline', false, array(), TITANCART_VERSION, true );
        wp_enqueue_script( 'titancart-profile-inline' );
        wp_add_inline_script( 'titancart-profile-inline', $tc_profile_inline_js );
        ?>
    </div>
    <?php endif; ?>

</div><!-- .tc-account-profile -->
