<?php
/**
 * Class SUP_CSV_Import_Manager
 * مدیریت درون‌ریزی گروهی کاربران از طریق فایل CSV
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit; // جلوگیری از دسترسی مستقیم
}

class SUP_CSV_Import_Manager {

    /**
     * ثبت هوک‌های AJAX
     */
    public function init() {
        add_action( 'wp_ajax_sup_upload_import_file', array( $this, 'ajax_upload_file' ) );
        add_action( 'wp_ajax_sup_process_import_chunk', array( $this, 'ajax_process_chunk' ) );
    }

    /**
     * مدیریت آپلود فایل و شمارش ردیف‌ها
     */
    public function ajax_upload_file() {
        check_ajax_referer( 'sup_import_nonce', 'security' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'شما اجازه دسترسی به این بخش را ندارید.' ) );
        }

        if ( empty( $_FILES['import_file']['tmp_name'] ) ) {
            wp_send_json_error( array( 'message' => 'هیچ فایلی انتخاب نشده است.' ) );
        }

        $file = $_FILES['import_file'];

        // بررسی پسوند فایل
        $file_ext = pathinfo( $file['name'], PATHINFO_EXTENSION );
        if ( strtolower( $file_ext ) !== 'csv' ) {
            wp_send_json_error( array( 'message' => 'لطفا فقط فایل CSV آپلود کنید.' ) );
        }

        // انتقال فایل به پوشه موقت آپلودهای وردپرس
        $upload_dir = wp_upload_dir();
        $target_path = $upload_dir['path'] . '/sup_import_' . time() . '.csv';

        if ( ! move_uploaded_file( $file['tmp_name'], $target_path ) ) {
            wp_send_json_error( array( 'message' => 'خطا در ذخیره فایل موقت.' ) );
        }

        // شمارش تعداد کل ردیف‌ها
        $row_count = 0;
        if ( ( $handle = fopen( $target_path, "r" ) ) !== FALSE ) {
            while ( ( $data = fgetcsv( $handle, 1000, "," ) ) !== FALSE ) {
                $row_count++;
            }
            fclose( $handle );
        }

        // کسر کردن ردیف اول (Header)
        $total_records = $row_count > 0 ? $row_count - 1 : 0;

        wp_send_json_success( array(
            'file_path'     => $target_path,
            'total_records' => $total_records
        ) );
    }

    /**
     * پردازش فایل در دسته‌های مشخص (Chunks)
     */
    public function ajax_process_chunk() {
        check_ajax_referer( 'sup_import_nonce', 'security' );

        if ( ! current_user_can( 'manage_options' ) ) {
            wp_send_json_error( array( 'message' => 'عدم دسترسی.' ) );
        }

        global $wpdb;
        $sup_table = $wpdb->prefix . 'user_profile';

        $file_path  = sanitize_text_field( $_POST['file_path'] );
        $offset     = isset( $_POST['offset'] ) ? intval( $_POST['offset'] ) : 1; // شروع از 1 برای رد کردن Header
        $batch_size = 100; // تعداد پردازش در هر درخواست

        if ( ! file_exists( $file_path ) ) {
            wp_send_json_error( array( 'message' => 'فایل موقت یافت نشد.' ) );
        }

        $success_count = 0;
        $error_count   = 0;
        $error_logs    = array();
        $current_row   = 0;
        $processed     = 0;

        if ( ( $handle = fopen( $file_path, "r" ) ) !== FALSE ) {
            while ( ( $data = fgetcsv( $handle, 1000, "," ) ) !== FALSE ) {
                if ( $current_row < $offset ) {
                    $current_row++;
                    continue;
                }

                if ( $processed >= $batch_size ) {
                    break; // پایان دسته فعلی
                }

                // فرض بر ترتیب ستون‌ها در CSV:
                // 0: user_login, 1: user_pass, 2: first_name, 3: last_name, 4: code_melli, 5: mobile_number
                
                $user_login    = sanitize_user( $data[0] );
                $user_pass     = sanitize_text_field( $data[1] );
                $first_name    = sanitize_text_field( $data[2] );
                $last_name     = sanitize_text_field( $data[3] );
                $code_melli     = sanitize_text_field( $data[4] );
                $mobile_number = sanitize_text_field( $data[5] );

                // 1. بررسی تکراری بودن نام کاربری در وردپرس
                if ( username_exists( $user_login ) ) {
                    $error_count++;
                    $error_logs[] = "نام کاربری {$user_login} قبلاً ثبت شده است.";
                    $current_row++;
                    $processed++;
                    continue;
                }

                // 2. بررسی تکراری بودن کدملی در جدول اختصاصی
                $code_exists = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $sup_table WHERE code_melli = %s", $code_melli ) );
                if ( $code_exists ) {
                    $error_count++;
                    $error_logs[] = "کد ملی {$code_melli} قبلاً در سیستم ثبت شده است.";
                    $current_row++;
                    $processed++;
                    continue;
                }

                // 3. ثبت کاربر در هسته وردپرس
                $user_id = wp_insert_user( array(
                    'user_login' => $user_login,
                    'user_pass'  => $user_pass,
                    'first_name' => $first_name,
                    'last_name'  => $last_name,
                    'role'       => 'subscriber'
                ) );

                if ( is_wp_error( $user_id ) ) {
                    $error_count++;
                    $error_logs[] = "خطا در ثبت وردپرس برای {$user_login}: " . $user_id->get_error_message();
                    $current_row++;
                    $processed++;
                    continue;
                }

                // 4. ثبت در جدول اختصاصی
                $inserted = $wpdb->insert(
                    $sup_table,
                    array(
                        'wp_user_id'    => $user_id,
                        'user_login'    => $user_login,
                        'user_pass'     => $user_pass,
                        'first_name'    => $first_name,
                        'last_name'     => $last_name,
                        'code_melli'     => $code_melli,
                        'mobile_number' => $mobile_number,
                        'register_date' => current_time( 'mysql' )
                    ),
                    array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
                );

                if ( ! $inserted ) {
                    // در صورت خطا در جدول اختصاصی، کاربر ساخته شده در وردپرس حذف شود (رول‌بک)
                    require_once( ABSPATH . 'wp-admin/includes/user.php' );
                    wp_delete_user( $user_id );
                    
                    $error_count++;
                    $error_logs[] = "خطا در ثبت جدول اختصاصی برای کدملی {$code_melli}. کاربر حذف شد.";
                } else {
                    $success_count++;
                }

                $current_row++;
                $processed++;
            }
            fclose( $handle );
        }

        // اگر فایل به انتها رسید، فایل موقت حذف شود
        $is_finished = false;
        if ( $processed < $batch_size ) {
            $is_finished = true;
            unlink( $file_path ); 
        }

        wp_send_json_success( array(
            'success_count' => $success_count,
            'error_count'   => $error_count,
            'error_logs'    => $error_logs,
            'next_offset'   => $current_row,
            'is_finished'   => $is_finished
        ) );
    }
}
