/*
Theme Name:   Negarshop
Description:  پوسته فروشگاهی نگارشاپ محصولی از تیم پسر کدنویس
Author:       CoderBoy team
Author URI:   https://www.coderboy.ir/
Version:      11.4.7
Text Domain:  negarshop
Domain Path:  /includes/languages/theme/
Tags:         Negarshop, shop, woocommerce
*/




//login
//
// Auto-register / auto-login by phone on checkout (compatible with Negashop storing billing_phone)
add_action( 'woocommerce_checkout_order_processed', 'negashop_auto_register_or_login_by_phone', 10, 3 );
function negashop_auto_register_or_login_by_phone( $order_id, $posted_data, $order ) {
    if ( is_user_logged_in() ) return;

    $phone_raw = $order->get_billing_phone();
    if ( empty( $phone_raw ) ) return;

    // ساخت چند variant از شماره برای تطابق (مثلاً +98, 0098, 0..., بدون صفر و ...)
    $digits = preg_replace('/\D/', '', $phone_raw);
    $variants = array_unique(array_filter(array(
        $digits,
        (substr($digits,0,2) === '98') ? '0'.substr($digits,2) : null,
        (substr($digits,0,1) === '0') ? '98'.substr($digits,1) : null,
        (substr($digits,0,4) === '0098') ? ltrim(substr($digits,2), '0') : null,
    )));

    // تلاش برای پیدا کردن کاربر از طریق user_login یا meta billing_phone
    $found_user = null;
    foreach ( $variants as $v ) {
        if ( empty($v) ) continue;

        // 1) بر اساس user_login
        $u = get_user_by( 'login', $v );
        if ( $u ) { $found_user = $u; break; }

        // 2) بر اساس متای billing_phone
        $users = get_users( array(
            'meta_key'   => 'billing_phone',
            'meta_value' => $v,
            'number'     => 1,
            'fields'     => 'all',
        ) );
        if ( ! empty( $users ) ) { $found_user = $users[0]; break; }
    }

    if ( $found_user ) {
        $user_id = $found_user->ID;
        // به‌روز کردن متای billing_phone با فرمت اصلی سفارش (اختیاری ولی مفید)
        update_user_meta( $user_id, 'billing_phone', $phone_raw );

        // لاگین کاربر
        wp_set_current_user( $user_id );
        wp_set_auth_cookie( $user_id );

        // نسبت دادن سفارش به کاربر (اختیاری اما معمولاً خواسته‌شده)
        if ( method_exists( $order, 'set_customer_id' ) ) {
            $order->set_customer_id( $user_id );
            $order->save();
        } else {
            update_post_meta( $order_id, '_customer_user', $user_id );
        }

        return;
    }

    // اگر کاربر پیدا نشد => ایجاد کاربر جدید (مثل قبل)
    $username = reset( $variants ); // از اولین variant استفاده می‌کنیم
    if ( ! $username ) $username = $digits;

    // اگر به هر دلیل username یا ایمیل تکراری بود، کمی تغییر می‌دیم
    $email = $username . '@auto-user.local';
    if ( username_exists( $username ) || email_exists( $email ) ) {
        $username = $username . '_' . wp_generate_password(4, false, false);
        $email = $username . '@auto-user.local';
    }

    $user_id = wp_insert_user( array(
        'user_login'   => $username,
        'user_pass'    => wp_generate_password(12), // استفاده نمیشه (OTP)
        'user_email'   => $email,
        'nickname'     => $username,
        'display_name' => $username,
        'role'         => 'customer',
    ) );

    if ( is_wp_error( $user_id ) ) return;

    update_user_meta( $user_id, 'billing_phone', $phone_raw );

    // لاگین کاربر جدید
    wp_set_current_user( $user_id );
    wp_set_auth_cookie( $user_id );

    // نسبت دادن سفارش
    if ( method_exists( $order, 'set_customer_id' ) ) {
        $order->set_customer_id( $user_id );
        $order->save();
    } else {
        update_post_meta( $order_id, '_customer_user', $user_id );
    }
}


// اختیاری کردن فیلد کد پستی در ووکامرس
add_filter( 'woocommerce_default_address_fields' , 'custom_override_postcode_field' );

function custom_override_postcode_field( $fields ) {
    $fields['postcode']['required'] = false; // غیراجباری کردن
    return $fields;
}
add_filter( 'woocommerce_default_address_fields', 'custom_require_address_field' );

function custom_require_address_field( $fields ) {
    $fields['address_1']['required'] = true; // اجباری کردن آدرس
    return $fields;
}
