/**
 * Template: ms-lms-starter-theme
 * Theme Name: MasterStudy Templates Child
 * Theme URI: https://starter.stylemixthemes.com/
 * Author: StylemixThemes
 * Author URI: https://stylemixthemes.com/
 * Description: MasterStudy Templates Child Theme is the child theme for the MasterStudy Templates. With this child theme, you can customize your eLearning website appearance without changing the original templates.
 * License: GNU General Public License v2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 * Tags: classes, courses, Education, education center, e-commerce, learning center, tutoring, teaching, study, studying, learning, lessons, instructor, teacher, mentor
 * Text Domain: starter-text-domain
 * Version: 1.0.0
 */

/* // Tự động check checkbox "Tạo tài khoản" nếu khách chưa login */
add_action('woocommerce_before_checkout_form', function(){
  if ( ! is_user_logged_in() ) {
    echo '<script>
      jQuery(function($){ $("#createaccount").prop("checked", true); });
    </script>';
  }
});

/* // Khi đơn chuyển sang trạng thái processing/completed, kiểm tra và tạo user */
add_action('woocommerce_order_status_processing', 'auto_create_customer_account', 10, 1);
add_action('woocommerce_order_status_completed',  'auto_create_customer_account', 10, 1);
function auto_create_customer_account( $order_id ) {
  $order = wc_get_order( $order_id );
  $email = $order->get_billing_email();
  if ( email_exists( $email ) ) return; // đã có user
/*   // Sinh username và password ngẫu nhiên */
  $username = sanitize_user( current( explode( '@', $email ) ), true );
  $username = wp_unique_username( $username );
  $password = wp_generate_password( 12, false );
  // Tạo user
  $user_id = wc_create_new_customer( $email, $username, $password );
  if ( is_wp_error( $user_id ) ) {
    error_log( 'Auto-create user failed: ' . $user_id->get_error_message() );
    return;
  }
/*   // Gửi email thông báo */
  wc_mail(
    $email,
    'Thông tin tài khoản của bạn trên '. get_bloginfo('name'),
    "Chào bạn,\n\nTài khoản đã được tạo tự động sau khi bạn đặt hàng.\n\n• Username: $username\n• Password: $password\n\nBạn có thể đăng nhập tại: ". wc_get_page_permalink('myaccount')
  );
/*   // (Tùy chọn) gán đơn hàng về đúng user */
  $order->set_customer_id( $user_id );
  $order->save();
}
