<?php
/**
 * Template: account/login-register.php
 *
 * Shown when a guest visits the [titancart_account] shortcode page.
 * Two panels: Login (left) and Register (right).
 *
 * Available variables:
 *   $redirect — URL to return to after login/registration
 *
 * Override: copy to your-theme/titancart/account/login-register.php
 *
 * @package TitanCart
 */
defined( 'ABSPATH' ) || exit;

// Resolve redirect target. Caller (AccountsModule::render_account) normally
// passes a validated $redirect; if this template is loaded by some other
// surface, fall back to the same query-string contract before settling on
// /my-account/. NEVER use get_permalink() — global $post may be stale.
if ( ! empty( $redirect ) ) {
    $redirect_url = esc_url( (string) $redirect );
} else {
    $requested = isset( $_GET['redirect_to'] )
        ? esc_url_raw( wp_unslash( (string) $_GET['redirect_to'] ) )
        : '';
    $fallback  = home_url( '/my-account/' );
    $resolved  = $requested
        ? wp_validate_redirect( $requested, $fallback )
        : $fallback;
    $redirect_url = esc_url( $resolved );
}

// Handle registration form submission.
$reg_error   = '';
$reg_success = '';

// Registration form settings.
$_quick_reg     = \TitanCart\Services\SettingsService::bool( 'general', 'customers_quick_registration', true );
$_allow_group   = \TitanCart\Services\SettingsService::bool( 'general', 'customers_allow_group_signup', false );
$_signup_groups = [];
if ( $_allow_group ) {
    $db = titancart_db();
    // Get active groups, excluding subscription-gated groups (those linked to a plan).
    $_all_groups = $db->getAll(
        "SELECT g.id, g.name FROM {$db->table('usergroups')} g WHERE g.status = 'active' ORDER BY g.name"
    );
    // Check if subscription plugin tables exist and filter gated groups.
    $sub_table = $db->table('subscription_plans');
    $has_sub   = $db->getField( "SHOW TABLES LIKE ?s", $sub_table );
    $_gated_ids = [];
    if ( $has_sub ) {
        $_gated_ids = array_column( $db->getAll(
            "SELECT DISTINCT usergroup_id FROM {$sub_table} WHERE usergroup_id IS NOT NULL AND usergroup_id > 0 AND status = 'active'"
        ) ?: [], 'usergroup_id' );
    }
    foreach ( $_all_groups ?: [] as $g ) {
        if ( ! in_array( $g['id'], $_gated_ids, false ) ) {
            $_signup_groups[] = $g;
        }
    }
}

// Custom contact-section fields configured via Customer Fields admin page
// (S127.C-1). The manager loads visible non-system fields and renders them
// dynamically below. Submitted values are extracted from $_POST so they
// survive a validation-failure re-render.
$_fields_manager   = new \TitanCart\Modules\Accounts\CustomerFieldsManager();
$_submitted_fields = $_fields_manager->extract_submitted( $_POST ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- read-only sticky-form extraction (sanitized per element inside the seam, #631); the only write path below is gated by check_admin_referer('tc_register').

// Referral code capture (S277, #5 / KI-13). Pre-fill from a validation re-render
// ($_POST) or a shared ?ref= deep-link. The field is shown when the store runs an
// active referral rule, OR whenever a code is already in hand (so a shared link
// always surfaces it even if the program is paused). Attribution is captured
// server-side in AccountManager::register() regardless of whether the field shows.
$_ref_prefill = '';
if ( isset( $_POST['reg_referral_code'] ) ) {
    $_ref_prefill = sanitize_text_field( wp_unslash( $_POST['reg_referral_code'] ) );
} elseif ( isset( $_GET['ref'] ) ) {
    $_ref_prefill = sanitize_text_field( wp_unslash( $_GET['ref'] ) );
}
$_show_referral = ( $_ref_prefill !== '' );
if ( ! $_show_referral && \TitanCart\REST\Extensions\ExtensionsController::is_active( 'rewards' ) ) {
    $_ref_db        = titancart_db();
    $_show_referral = (int) $_ref_db->getField(
        "SELECT COUNT(*) FROM {$_ref_db->table('reward_point_rules')} WHERE event = 'referral' AND status = 'active'"
    ) > 0;
}

$tc_lr_reg_ok = ! empty( $_POST['tc_register'] ) && check_admin_referer( 'tc_register' );
if ( $tc_lr_reg_ok && ! \TitanCart\Extensions\RecaptchaExtension::passes( 'register' ) ) {
    $reg_error = __( 'reCAPTCHA verification failed. Please try again.', 'titancart-lite' );
    $tc_lr_reg_ok = false;
}
if ( $tc_lr_reg_ok ) {
    $manager = new \TitanCart\Modules\Accounts\AccountManager();
    $reg_data = [
        'email'         => sanitize_email( wp_unslash( $_POST['reg_email']      ?? '' ) ),
        'password'      => wp_unslash( $_POST['reg_password'] ?? '' ), // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- passwords must not be sanitized; hashed by AccountManager::register().
        'first_name'    => sanitize_text_field( wp_unslash( $_POST['reg_first_name'] ?? '' ) ),
        'last_name'     => sanitize_text_field( wp_unslash( $_POST['reg_last_name']  ?? '' ) ),
        'referral_code' => sanitize_text_field( wp_unslash( $_POST['reg_referral_code'] ?? '' ) ),
        'custom_fields' => $_submitted_fields,
    ];
    if ( ! $_quick_reg ) {
        $reg_data['phone']   = sanitize_text_field( wp_unslash( $_POST['reg_phone']   ?? '' ) );
        $reg_data['company'] = sanitize_text_field( wp_unslash( $_POST['reg_company'] ?? '' ) );
    }
    if ( $_allow_group && ! empty( $_POST['reg_usergroup'] ) ) {
        $reg_data['usergroup_id'] = absint( $_POST['reg_usergroup'] );
    }
    $result = $manager->register( $reg_data );

    if ( is_wp_error( $result ) ) {
        $reg_error = $result->get_error_message();
    } else {
        // Auto-login and redirect.
        $user = get_user_by( 'email', sanitize_email( wp_unslash( $_POST['reg_email'] ?? '' ) ) );
        if ( $user ) {
            wp_set_current_user( $user->ID );
            wp_set_auth_cookie( $user->ID );
            wp_safe_redirect( $redirect_url );
            exit;
        }
        $reg_success = __( 'Account created! You can now log in.', 'titancart-lite' );
    }
}
?>

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

    <!-- ── Login ──────────────────────────────────────────────────────────── -->
    <div class="tc-auth-panel tc-auth-panel--login">
        <h2 class="tc-auth-panel__title"><?php esc_html_e( 'Sign In', 'titancart-lite' ); ?></h2>

        <?php if ( ! empty( $_GET['tc_login_error'] ) ) : ?>
            <div class="tc-notice tc-notice--error">
                <?php esc_html_e( 'Incorrect email or password.', 'titancart-lite' ); ?>
            </div>
        <?php endif; ?>

        <form class="tc-form" method="post" action="<?php echo esc_url( wp_login_url( $redirect_url ) ); ?>">
            <div class="tc-form__row">
                <label for="tc-login-email"><?php esc_html_e( 'Email Address', 'titancart-lite' ); ?></label>
                <input id="tc-login-email"
                       type="email"
                       name="log"
                       autocomplete="username email"
                       class="tc-input"
                       required />
            </div>

            <div class="tc-form__row">
                <label for="tc-login-password"><?php esc_html_e( 'Password', 'titancart-lite' ); ?></label>
                <input id="tc-login-password"
                       type="password"
                       name="pwd"
                       autocomplete="current-password"
                       class="tc-input"
                       required />
            </div>

            <div class="tc-form__row tc-form__row--checkbox">
                <label>
                    <input type="checkbox" name="rememberme" value="forever" />
                    <?php esc_html_e( 'Remember me', 'titancart-lite' ); ?>
                </label>
            </div>

            <input type="hidden" name="redirect_to" value="<?php echo esc_attr( $redirect_url ); ?>" />
            <?php wp_nonce_field( 'log-in' ); ?>
            <input type="hidden" name="tc_rc_login" value="1" />
            <?php do_action( 'titancart_recaptcha_field', 'login' ); ?>

            <button type="submit" class="tc-btn tc-btn--primary tc-btn--full">
                <?php esc_html_e( 'Sign In', 'titancart-lite' ); ?>
            </button>

            <p class="tc-auth-panel__forgot">
                <a href="<?php echo esc_url( wp_lostpassword_url() ); ?>">
                    <?php esc_html_e( 'Forgot your password?', 'titancart-lite' ); ?>
                </a>
            </p>
        </form>
    </div>

    <!-- ── Register ───────────────────────────────────────────────────────── -->
    <div class="tc-auth-panel tc-auth-panel--register">
        <h2 class="tc-auth-panel__title"><?php esc_html_e( 'Create Account', 'titancart-lite' ); ?></h2>

        <?php if ( $reg_error ) : ?>
            <div class="tc-notice tc-notice--error"><?php echo esc_html( $reg_error ); ?></div>
        <?php endif; ?>

        <?php if ( $reg_success ) : ?>
            <div class="tc-notice tc-notice--success"><?php echo esc_html( $reg_success ); ?></div>
        <?php endif; ?>

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

            <div class="tc-form__row tc-form__row--split">
                <div>
                    <label for="tc-reg-first"><?php esc_html_e( 'First Name', 'titancart-lite' ); ?></label>
                    <input id="tc-reg-first"
                           type="text"
                           name="reg_first_name"
                           class="tc-input"
                           value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['reg_first_name'] ?? '' ) ) ); ?>" />
                </div>
                <div>
                    <label for="tc-reg-last"><?php esc_html_e( 'Last Name', 'titancart-lite' ); ?></label>
                    <input id="tc-reg-last"
                           type="text"
                           name="reg_last_name"
                           class="tc-input"
                           value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['reg_last_name'] ?? '' ) ) ); ?>" />
                </div>
            </div>

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

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

            <?php if ( ! $_quick_reg ) : ?>
            <div class="tc-form__row">
                <label for="tc-reg-phone"><?php esc_html_e( 'Phone', 'titancart-lite' ); ?></label>
                <input id="tc-reg-phone"
                       type="tel"
                       name="reg_phone"
                       class="tc-input"
                       value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['reg_phone'] ?? '' ) ) ); ?>" />
            </div>

            <div class="tc-form__row">
                <label for="tc-reg-company"><?php esc_html_e( 'Company', 'titancart-lite' ); ?></label>
                <input id="tc-reg-company"
                       type="text"
                       name="reg_company"
                       class="tc-input"
                       value="<?php echo esc_attr( sanitize_text_field( wp_unslash( $_POST['reg_company'] ?? '' ) ) ); ?>" />
            </div>
            <?php endif; ?>

            <?php
            // Custom contact-section fields. Renders only if the admin has
            // marked any non-system fields visible. Submitted values survive
            // a validation-failure re-render via $_submitted_fields overrides.
            // (S127.C-1)
            echo wp_kses( $_fields_manager->render_section_html( 'contact', 0, 'tc-reg-cf-', $_submitted_fields ), \TitanCart\Modules\Accounts\CustomerFieldsManager::form_kses_allowed() );
            ?>

            <?php if ( $_allow_group && ! empty( $_signup_groups ) ) : ?>
            <div class="tc-form__row">
                <label for="tc-reg-group"><?php esc_html_e( 'Customer Group', 'titancart-lite' ); ?></label>
                <select id="tc-reg-group" name="reg_usergroup" class="tc-input">
                    <option value=""><?php esc_html_e( '— Select —', 'titancart-lite' ); ?></option>
                    <?php foreach ( $_signup_groups as $g ) : ?>
                    <option value="<?php echo (int) $g['id']; ?>" <?php selected( absint( wp_unslash( $_POST['reg_usergroup'] ?? 0 ) ), (int) $g['id'] ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- sticky-form re-render only; the registration write at the top of this template is nonce-gated by check_admin_referer('tc_register'). ?>>
                        <?php echo esc_html( $g['name'] ); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <?php endif; ?>

            <?php if ( $_show_referral ) : ?>
            <div class="tc-form__row">
                <label for="tc-reg-referral"><?php esc_html_e( 'Referral code', 'titancart-lite' ); ?> <span class="tc-field-hint">(<?php esc_html_e( 'optional', 'titancart-lite' ); ?>)</span></label>
                <input id="tc-reg-referral"
                       type="text"
                       name="reg_referral_code"
                       class="tc-input"
                       autocomplete="off"
                       value="<?php echo esc_attr( $_ref_prefill ); ?>" />
                <span class="tc-field-hint"><?php esc_html_e( 'Got a code from a friend? Enter it to earn rewards.', 'titancart-lite' ); ?></span>
            </div>
            <?php endif; ?>

            <?php do_action( 'titancart_recaptcha_field', 'register' ); ?>
            <button type="submit" class="tc-btn tc-btn--secondary tc-btn--full">
                <?php esc_html_e( 'Create Account', 'titancart-lite' ); ?>
            </button>
        </form>
    </div>

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