<?php
/**
 * Arag_Marketer — موتور بازاریابی فروشگاه عرقیات
 *
 * قوانین پورسانت:
 * - فروشگاه تحت بازاریاب (با موبایل بسته‌شده): ۷٪ بازاریاب + ۳٪ توسعه سایت
 * - خرید بدون بازاریاب (مغازه خودش): ۱۰٪ توسعه سایت
 * - پورسانت بازاریاب پس از دریافت پول (paid) قابل تسویه می‌شود
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Arag_Marketer {

    public const PCT_MARKETER = 7.0;
    public const PCT_SITE_WITH_MARKETER = 3.0;
    public const PCT_SITE_DIRECT = 10.0;
    public const DEFAULT_CREDIT_LIMIT = 5000000;

    public static function normalize_phone( string $phone ): string {
        $p = preg_replace( '/\D+/', '', $phone );
        if ( str_starts_with( $p, '98' ) && strlen( $p ) === 12 ) {
            $p = '0' . substr( $p, 2 );
        }
        if ( strlen( $p ) === 10 && str_starts_with( $p, '9' ) ) {
            $p = '0' . $p;
        }
        return $p;
    }

    public static function generate_code(): string {
        global $wpdb;
        do {
            $code = 'AM-' . strtoupper( substr( md5( uniqid( (string) mt_rand(), true ) ), 0, 6 ) );
            $exists = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}arag_marketer_accounts WHERE marketer_code=%s",
                $code
            ) );
        } while ( $exists );
        return $code;
    }

    public static function get_by_id( int $id ): ?array {
        global $wpdb;
        if ( $id <= 0 ) {
            return null;
        }
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_marketer_accounts WHERE id=%d",
            $id
        ), ARRAY_A );
        return $row ?: null;
    }

    public static function get_by_phone( string $phone ): ?array {
        global $wpdb;
        $phone = self::normalize_phone( $phone );
        if ( strlen( $phone ) < 10 ) {
            return null;
        }
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_marketer_accounts WHERE phone=%s",
            $phone
        ), ARRAY_A );
        return $row ?: null;
    }

    public static function get_by_user( int $user_id ): ?array {
        global $wpdb;
        if ( $user_id <= 0 ) {
            return null;
        }
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_marketer_accounts WHERE user_id=%d ORDER BY id DESC LIMIT 1",
            $user_id
        ), ARRAY_A );
        return $row ?: null;
    }

    public static function get_by_code( string $code ): ?array {
        global $wpdb;
        $code = strtoupper( trim( $code ) );
        if ( ! $code ) {
            return null;
        }
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_marketer_accounts WHERE marketer_code=%s AND status='active' LIMIT 1",
            $code
        ), ARRAY_A );
        return $row ?: null;
    }

    public static function ensure_user_for_phone( string $phone, string $display_name = '' ): int {
        $phone = self::normalize_phone( $phone );
        $login = 'm_' . $phone;
        $user  = get_user_by( 'login', $login );
        if ( $user ) {
            if ( $display_name ) {
                wp_update_user( [
                    'ID'           => (int) $user->ID,
                    'display_name' => $display_name,
                ] );
            }
            return (int) $user->ID;
        }
        if ( ! function_exists( 'wp_create_user' ) ) {
            return 0;
        }
        $uid = wp_create_user( $login, wp_generate_password( 16, true ), $login . '@shop.local' );
        if ( is_wp_error( $uid ) ) {
            return 0;
        }
        wp_update_user( [
            'ID'           => (int) $uid,
            'display_name' => $display_name ?: ( 'کاربر ' . substr( $phone, -4 ) ),
            'role'         => 'customer',
        ] );
        update_user_meta( (int) $uid, 'billing_phone', $phone );
        return (int) $uid;
    }

    /** ثبت‌نام بازاریاب — وضعیت pending تا تایید مدیر */
    public static function register( array $data ): array {
        global $wpdb;
        $phone = self::normalize_phone( (string) ( $data['phone'] ?? '' ) );
        if ( strlen( $phone ) < 10 ) {
            return [ 'success' => false, 'message' => 'شماره موبایل معتبر نیست' ];
        }

        $existing = self::get_by_phone( $phone );
        if ( $existing ) {
            return [
                'success' => true,
                'account' => $existing,
                'is_new'  => false,
                'message' => $existing['status'] === 'pending'
                    ? 'درخواست شما قبلاً ثبت شده و منتظر تایید مدیر است'
                    : ( $existing['status'] === 'active'
                        ? 'حساب بازاریاب شما فعال است'
                        : 'وضعیت حساب: ' . $existing['status'] ),
            ];
        }

        $name = sanitize_text_field( $data['display_name'] ?? '' );
        if ( ! $name ) {
            return [ 'success' => false, 'message' => 'نام بازاریاب الزامی است' ];
        }

        $user_id = self::ensure_user_for_phone( $phone, $name );

        $wpdb->insert( "{$wpdb->prefix}arag_marketer_accounts", [
            'user_id'       => $user_id,
            'phone'         => $phone,
            'display_name'  => $name,
            'national_id'   => sanitize_text_field( $data['national_id'] ?? '' ) ?: null,
            'city'          => sanitize_text_field( $data['city'] ?? '' ) ?: null,
            'address'       => sanitize_text_field( $data['address'] ?? '' ) ?: null,
            'bank_sheba'    => sanitize_text_field( $data['bank_sheba'] ?? '' ) ?: null,
            'bank_card'     => sanitize_text_field( $data['bank_card'] ?? '' ) ?: null,
            'bank_name'     => sanitize_text_field( $data['bank_name'] ?? '' ) ?: null,
            'marketer_code' => self::generate_code(),
            'status'        => 'pending',
            'credit_limit'  => self::DEFAULT_CREDIT_LIMIT,
        ] );

        return [
            'success' => true,
            'account' => self::get_by_id( (int) $wpdb->insert_id ),
            'is_new'  => true,
            'message' => 'ثبت‌نام انجام شد. پس از تایید مدیر سیستم فروشگاه می‌توانید فعالیت کنید.',
        ];
    }

    public static function set_status( int $id, string $status, int $admin_id = 0, string $note = '' ): array {
        global $wpdb;
        $allowed = [ 'pending', 'active', 'suspended', 'rejected' ];
        if ( ! in_array( $status, $allowed, true ) ) {
            return [ 'success' => false, 'message' => 'وضعیت نامعتبر' ];
        }
        $acc = self::get_by_id( $id );
        if ( ! $acc ) {
            return [ 'success' => false, 'message' => 'بازاریاب یافت نشد' ];
        }
        $upd = [
            'status'     => $status,
            'admin_note' => $note ?: null,
        ];
        if ( $status === 'active' ) {
            $upd['approved_at'] = current_time( 'mysql' );
            $upd['approved_by'] = $admin_id ?: null;
        }
        $wpdb->update( "{$wpdb->prefix}arag_marketer_accounts", $upd, [ 'id' => $id ] );
        return [ 'success' => true, 'account' => self::get_by_id( $id ) ];
    }

    public static function require_active( int $marketer_id ): ?array {
        $acc = self::get_by_id( $marketer_id );
        if ( ! $acc || $acc['status'] !== 'active' ) {
            return null;
        }
        return $acc;
    }

    /** ثبت / به‌روزرسانی مغازه تحت بازاریاب — یک موبایل = یک حساب مغازه */
    public static function upsert_shop( int $marketer_id, array $data ): array {
        global $wpdb;
        $acc = self::require_active( $marketer_id );
        if ( ! $acc ) {
            return [ 'success' => false, 'message' => 'حساب بازاریاب فعال نیست' ];
        }

        $phone = self::normalize_phone( (string) ( $data['shop_phone'] ?? '' ) );
        if ( strlen( $phone ) < 10 ) {
            return [ 'success' => false, 'message' => 'موبایل فروشگاه معتبر نیست' ];
        }
        if ( $phone === $acc['phone'] ) {
            return [ 'success' => false, 'message' => 'نمی‌توانید موبایل خودتان را به‌عنوان مغازه ثبت کنید' ];
        }

        $shop_name   = sanitize_text_field( $data['shop_name'] ?? '' );
        $owner_name  = sanitize_text_field( $data['owner_name'] ?? '' );
        if ( ! $shop_name ) {
            return [ 'success' => false, 'message' => 'نام مغازه الزامی است' ];
        }

        /* یک حساب کاربری خریدار به‌ازای هر موبایل */
        self::ensure_user_for_phone( $phone, $owner_name ?: $shop_name );

        $existing = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_marketer_shops WHERE shop_phone=%s",
            $phone
        ), ARRAY_A );

        if ( $existing ) {
            if ( (int) $existing['marketer_id'] !== $marketer_id ) {
                return [
                    'success' => false,
                    'message' => 'این فروشگاه قبلاً تحت بازاریابی شخص دیگری ثبت شده است',
                ];
            }
            $wpdb->update( "{$wpdb->prefix}arag_marketer_shops", [
                'shop_name'  => $shop_name,
                'owner_name' => $owner_name,
                'city'       => sanitize_text_field( $data['city'] ?? '' ) ?: null,
                'address'    => sanitize_text_field( $data['address'] ?? '' ) ?: null,
                'notes'      => sanitize_textarea_field( $data['notes'] ?? '' ) ?: null,
                'status'     => 'active',
            ], [ 'id' => (int) $existing['id'] ] );
            return [ 'success' => true, 'shop' => self::get_shop( (int) $existing['id'] ), 'is_new' => false ];
        }

        $wpdb->insert( "{$wpdb->prefix}arag_marketer_shops", [
            'marketer_id' => $marketer_id,
            'shop_phone'  => $phone,
            'shop_name'   => $shop_name,
            'owner_name'  => $owner_name,
            'city'        => sanitize_text_field( $data['city'] ?? '' ) ?: null,
            'address'     => sanitize_text_field( $data['address'] ?? '' ) ?: null,
            'notes'       => sanitize_textarea_field( $data['notes'] ?? '' ) ?: null,
            'status'      => 'active',
        ] );
        $shop_id = (int) $wpdb->insert_id;
        $wpdb->query( $wpdb->prepare(
            "UPDATE {$wpdb->prefix}arag_marketer_accounts SET shops_count = shops_count + 1 WHERE id=%d",
            $marketer_id
        ) );

        return [ 'success' => true, 'shop' => self::get_shop( $shop_id ), 'is_new' => true ];
    }

    public static function get_shop( int $id ): ?array {
        global $wpdb;
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_marketer_shops WHERE id=%d",
            $id
        ), ARRAY_A );
        return $row ?: null;
    }

    public static function shop_by_phone( string $phone ): ?array {
        global $wpdb;
        $phone = self::normalize_phone( $phone );
        if ( strlen( $phone ) < 10 ) {
            return null;
        }
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_marketer_shops WHERE shop_phone=%s AND status='active'",
            $phone
        ), ARRAY_A );
        return $row ?: null;
    }

    /**
     * محاسبه attribution برای سفارش
     * @return array{attribution:string,marketer_id:?int,shop_id:?int,marketer_pct:float,site_pct:float,marketer_amount:float,site_amount:float}
     */
    public static function compute_attribution( float $order_total, string $buyer_phone, ?int $sold_by_marketer_id = null ): array {
        $shop = self::shop_by_phone( $buyer_phone );
        $order_total = max( 0, $order_total );

        if ( $shop ) {
            $mid = (int) $shop['marketer_id'];
            $acc = self::require_active( $mid );
            if ( $acc ) {
                $m_pct = self::PCT_MARKETER;
                $s_pct = self::PCT_SITE_WITH_MARKETER;
                return [
                    'attribution'     => 'marketer_bound',
                    'marketer_id'     => $mid,
                    'shop_id'         => (int) $shop['id'],
                    'marketer_pct'    => $m_pct,
                    'site_pct'        => $s_pct,
                    'marketer_amount' => (float) round( $order_total * $m_pct / 100 ),
                    'site_amount'     => (float) round( $order_total * $s_pct / 100 ),
                ];
            }
        }

        /* فروش مستقیم توسط بازاریاب فعال روی مغازه جدید — باید اول shop ثبت شده باشد؛
           اگر sold_by هست ولی shop نیست، فقط سهم سایت ۱۰٪ (تا مغازه ثبت شود) */
        if ( $sold_by_marketer_id && self::require_active( $sold_by_marketer_id ) ) {
            /* بدون binding رسمی: ۱۰٪ سایت — بازاریاب باید مغازه را ثبت کند */
        }

        $s_pct = self::PCT_SITE_DIRECT;
        return [
            'attribution'     => 'direct_shop',
            'marketer_id'     => null,
            'shop_id'         => null,
            'marketer_pct'    => 0.0,
            'site_pct'        => $s_pct,
            'marketer_amount' => 0.0,
            'site_amount'     => (float) round( $order_total * $s_pct / 100 ),
        ];
    }

    /** اعمال attribution روی سفارش + ردیف کمیسیون (وضعیت pending تا پرداخت) */
    public static function attach_to_order( int $order_id, ?int $sold_by_marketer_id = null ): array {
        global $wpdb;
        $order = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_orders WHERE id=%d",
            $order_id
        ), ARRAY_A );
        if ( ! $order ) {
            return [ 'success' => false, 'message' => 'سفارش یافت نشد' ];
        }

        $total = (float) ( $order['total'] > 0 ? $order['total'] : $order['subtotal'] );
        $attr  = self::compute_attribution( $total, (string) $order['billing_phone'], $sold_by_marketer_id );

        $wpdb->update( "{$wpdb->prefix}arag_orders", [
            'marketer_id'             => $attr['marketer_id'],
            'marketer_shop_id'        => $attr['shop_id'],
            'attribution_type'        => $attr['attribution'],
            'commission_marketer_pct' => $attr['marketer_pct'],
            'commission_site_pct'     => $attr['site_pct'],
            'marketer_commission_amt' => $attr['marketer_amount'],
            'site_commission_amt'     => $attr['site_amount'],
            'sold_by_marketer_id'     => $sold_by_marketer_id,
        ], [ 'id' => $order_id ] );

        $existing = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}arag_marketer_commissions WHERE order_id=%d",
            $order_id
        ) );
        if ( ! $existing ) {
            $wpdb->insert( "{$wpdb->prefix}arag_marketer_commissions", [
                'marketer_id'     => $attr['marketer_id'],
                'shop_id'         => $attr['shop_id'],
                'order_id'        => $order_id,
                'attribution'     => $attr['attribution'],
                'order_total'     => $total,
                'marketer_pct'    => $attr['marketer_pct'],
                'site_pct'        => $attr['site_pct'],
                'marketer_amount' => $attr['marketer_amount'],
                'site_amount'     => $attr['site_amount'],
                'status'          => 'pending',
                'payment_mode'    => $order['payment_method'] ?? null,
            ] );
        }

        if ( $attr['shop_id'] ) {
            $wpdb->update( "{$wpdb->prefix}arag_marketer_shops", [
                'last_order_at' => current_time( 'mysql' ),
            ], [ 'id' => $attr['shop_id'] ] );
            $wpdb->query( $wpdb->prepare(
                "UPDATE {$wpdb->prefix}arag_marketer_shops
                 SET first_order_at = COALESCE(first_order_at, %s) WHERE id=%d",
                current_time( 'mysql' ),
                $attr['shop_id']
            ) );
        }

        return [ 'success' => true, 'attribution' => $attr ];
    }

    /** پس از دریافت پول — پورسانت بازاریاب قابل تسویه می‌شود */
    public static function on_payment_received( int $order_id ): void {
        global $wpdb;
        $comm = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_marketer_commissions WHERE order_id=%d",
            $order_id
        ), ARRAY_A );
        if ( ! $comm || $comm['status'] !== 'pending' ) {
            return;
        }

        $wpdb->update( "{$wpdb->prefix}arag_marketer_commissions", [
            'status'    => 'earned',
            'earned_at' => current_time( 'mysql' ),
        ], [ 'id' => (int) $comm['id'] ] );

        $mid = (int) ( $comm['marketer_id'] ?? 0 );
        $amt = (float) $comm['marketer_amount'];
        $tot = (float) $comm['order_total'];

        if ( $mid > 0 && $amt > 0 ) {
            $wpdb->query( $wpdb->prepare(
                "UPDATE {$wpdb->prefix}arag_marketer_accounts SET
                    total_earned = total_earned + %f,
                    balance_pending = balance_pending + %f,
                    balance_payable = balance_payable + %f,
                    total_sales = total_sales + %f,
                    orders_count = orders_count + 1
                 WHERE id=%d",
                $amt, $amt, $amt, $tot, $mid
            ) );
        }

        $sid = (int) ( $comm['shop_id'] ?? 0 );
        if ( $sid > 0 ) {
            $wpdb->query( $wpdb->prepare(
                "UPDATE {$wpdb->prefix}arag_marketer_shops SET
                    total_orders = total_orders + 1,
                    total_sales = total_sales + %f
                 WHERE id=%d",
                $tot, $sid
            ) );
        }
    }

    /* ── اعتبار بازاریاب ── */
    public static function credit_topup( int $marketer_id, float $amount, int $by = 0, string $note = '' ): array {
        global $wpdb;
        $acc = self::get_by_id( $marketer_id );
        if ( ! $acc ) {
            return [ 'success' => false, 'message' => 'بازاریاب یافت نشد' ];
        }
        $amount = abs( $amount );
        if ( $amount <= 0 ) {
            return [ 'success' => false, 'message' => 'مبلغ نامعتبر' ];
        }
        $new_bal = (float) $acc['credit_balance'] + $amount;
        $limit   = (float) $acc['credit_limit'];
        if ( $new_bal > $limit ) {
            return [
                'success' => false,
                'message' => 'سقف اعتبار ' . number_format( $limit ) . ' تومان است. موجودی پس از شارژ از سقف بیشتر می‌شود.',
            ];
        }
        $wpdb->update( "{$wpdb->prefix}arag_marketer_accounts", [
            'credit_balance' => $new_bal,
        ], [ 'id' => $marketer_id ] );
        $wpdb->insert( "{$wpdb->prefix}arag_marketer_credit_ledger", [
            'marketer_id'   => $marketer_id,
            'entry_type'    => 'topup',
            'amount'        => $amount,
            'balance_after' => $new_bal,
            'note'          => $note ?: 'شارژ اعتبار',
            'created_by'    => $by ?: null,
        ] );
        return [ 'success' => true, 'credit_balance' => $new_bal, 'credit_limit' => $limit ];
    }

    public static function set_credit_limit( int $marketer_id, float $limit ): array {
        global $wpdb;
        $limit = max( 0, $limit );
        $acc = self::get_by_id( $marketer_id );
        if ( ! $acc ) {
            return [ 'success' => false, 'message' => 'بازاریاب یافت نشد' ];
        }
        if ( (float) $acc['credit_balance'] > $limit ) {
            return [ 'success' => false, 'message' => 'سقف نمی‌تواند کمتر از موجودی فعلی باشد' ];
        }
        $wpdb->update( "{$wpdb->prefix}arag_marketer_accounts", [
            'credit_limit' => $limit,
        ], [ 'id' => $marketer_id ] );
        return [ 'success' => true, 'credit_limit' => $limit ];
    }

    public static function use_credit( int $marketer_id, float $amount, int $order_id, string $note = '' ): array {
        global $wpdb;
        $acc = self::require_active( $marketer_id );
        if ( ! $acc ) {
            return [ 'success' => false, 'message' => 'حساب بازاریاب فعال نیست' ];
        }
        $amount = abs( $amount );
        $bal    = (float) $acc['credit_balance'];
        if ( $amount > $bal ) {
            return [
                'success' => false,
                'message' => 'موجودی اعتبار کافی نیست (موجودی: ' . number_format( $bal ) . ' تومان)',
            ];
        }
        $new_bal = $bal - $amount;
        $wpdb->update( "{$wpdb->prefix}arag_marketer_accounts", [
            'credit_balance' => $new_bal,
        ], [ 'id' => $marketer_id ] );
        $wpdb->insert( "{$wpdb->prefix}arag_marketer_credit_ledger", [
            'marketer_id'   => $marketer_id,
            'entry_type'    => 'sale_debit',
            'amount'        => -$amount,
            'balance_after' => $new_bal,
            'order_id'      => $order_id,
            'note'          => $note ?: ( 'فروش اعتباری سفارش #' . $order_id ),
        ] );
        return [ 'success' => true, 'credit_balance' => $new_bal ];
    }

    public static function request_payout( int $marketer_id, float $amount ): array {
        global $wpdb;
        $acc = self::require_active( $marketer_id );
        if ( ! $acc ) {
            return [ 'success' => false, 'message' => 'حساب فعال نیست' ];
        }
        $amount = abs( $amount );
        $payable = (float) $acc['balance_payable'];
        if ( $amount <= 0 || $amount > $payable ) {
            return [ 'success' => false, 'message' => 'مبلغ تسویه از موجودی قابل‌پرداخت بیشتر است' ];
        }
        $wpdb->insert( "{$wpdb->prefix}arag_marketer_payouts", [
            'marketer_id'   => $marketer_id,
            'amount'        => $amount,
            'status'        => 'requested',
            'bank_snapshot' => wp_json_encode( [
                'sheba' => $acc['bank_sheba'],
                'card'  => $acc['bank_card'],
                'bank'  => $acc['bank_name'],
                'name'  => $acc['display_name'],
            ], JSON_UNESCAPED_UNICODE ),
        ] );
        $wpdb->query( $wpdb->prepare(
            "UPDATE {$wpdb->prefix}arag_marketer_accounts
             SET balance_payable = balance_payable - %f, balance_pending = GREATEST(0, balance_pending - %f)
             WHERE id=%d",
            $amount, $amount, $marketer_id
        ) );
        return [ 'success' => true, 'payout_id' => (int) $wpdb->insert_id ];
    }

    public static function process_payout( int $payout_id, string $status, int $admin_id = 0, string $note = '' ): array {
        global $wpdb;
        $row = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_marketer_payouts WHERE id=%d",
            $payout_id
        ), ARRAY_A );
        if ( ! $row || $row['status'] !== 'requested' ) {
            return [ 'success' => false, 'message' => 'درخواست یافت نشد یا قبلاً پردازش شده' ];
        }
        if ( ! in_array( $status, [ 'paid', 'rejected' ], true ) ) {
            return [ 'success' => false, 'message' => 'وضعیت نامعتبر' ];
        }
        $wpdb->update( "{$wpdb->prefix}arag_marketer_payouts", [
            'status'       => $status,
            'admin_note'   => $note ?: null,
            'processed_at' => current_time( 'mysql' ),
            'processed_by' => $admin_id ?: null,
        ], [ 'id' => $payout_id ] );

        $mid = (int) $row['marketer_id'];
        $amt = (float) $row['amount'];
        if ( $status === 'paid' ) {
            $wpdb->query( $wpdb->prepare(
                "UPDATE {$wpdb->prefix}arag_marketer_accounts SET balance_paid = balance_paid + %f WHERE id=%d",
                $amt, $mid
            ) );
            $wpdb->query( $wpdb->prepare(
                "UPDATE {$wpdb->prefix}arag_marketer_commissions
                 SET status='paid', paid_at=%s
                 WHERE marketer_id=%d AND status='earned'
                 ORDER BY id ASC LIMIT 1000",
                current_time( 'mysql' ), $mid
            ) );
        } else {
            $wpdb->query( $wpdb->prepare(
                "UPDATE {$wpdb->prefix}arag_marketer_accounts
                 SET balance_payable = balance_payable + %f, balance_pending = balance_pending + %f
                 WHERE id=%d",
                $amt, $amt, $mid
            ) );
        }
        return [ 'success' => true ];
    }

    public static function dashboard( int $marketer_id ): array {
        global $wpdb;
        $acc = self::get_by_id( $marketer_id );
        if ( ! $acc ) {
            return [ 'success' => false, 'message' => 'یافت نشد' ];
        }
        $pre = $wpdb->prefix;

        $shops = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$pre}arag_marketer_shops WHERE marketer_id=%d ORDER BY id DESC LIMIT 200",
            $marketer_id
        ), ARRAY_A ) ?: [];

        $orders = $wpdb->get_results( $wpdb->prepare(
            "SELECT id, order_number, billing_name, billing_phone, billing_city, total, subtotal,
                    payment_status, order_status, shipping_method, payment_method,
                    marketer_commission_amt, site_commission_amt, attribution_type, created_at
             FROM {$pre}arag_orders
             WHERE marketer_id=%d OR sold_by_marketer_id=%d
             ORDER BY id DESC LIMIT 100",
            $marketer_id, $marketer_id
        ), ARRAY_A ) ?: [];

        $comms = $wpdb->get_results( $wpdb->prepare(
            "SELECT c.*, o.order_number, o.payment_status, o.order_status, o.billing_name, s.shop_name
             FROM {$pre}arag_marketer_commissions c
             LEFT JOIN {$pre}arag_orders o ON o.id = c.order_id
             LEFT JOIN {$pre}arag_marketer_shops s ON s.id = c.shop_id
             WHERE c.marketer_id=%d
             ORDER BY c.id DESC LIMIT 100",
            $marketer_id
        ), ARRAY_A ) ?: [];

        $ledger = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$pre}arag_marketer_credit_ledger WHERE marketer_id=%d ORDER BY id DESC LIMIT 50",
            $marketer_id
        ), ARRAY_A ) ?: [];

        $payouts = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$pre}arag_marketer_payouts WHERE marketer_id=%d ORDER BY id DESC LIMIT 30",
            $marketer_id
        ), ARRAY_A ) ?: [];

        $pipeline = [
            'pending'    => 0,
            'processing' => 0,
            'shipped'    => 0,
            'completed'  => 0,
            'cancelled'  => 0,
        ];
        foreach ( $orders as $o ) {
            $st = $o['order_status'] ?? 'pending';
            if ( isset( $pipeline[ $st ] ) ) {
                $pipeline[ $st ]++;
            } else {
                $pipeline['processing']++;
            }
        }

        return [
            'success' => true,
            'data'    => [
                'account'      => $acc,
                'rates'        => [
                    'marketer_pct' => self::PCT_MARKETER,
                    'site_pct'     => self::PCT_SITE_WITH_MARKETER,
                    'direct_pct'   => self::PCT_SITE_DIRECT,
                ],
                'shops'        => $shops,
                'orders'       => $orders,
                'commissions'  => $comms,
                'credit_ledger'=> $ledger,
                'payouts'      => $payouts,
                'pipeline'     => $pipeline,
                'catalog_url'  => ACC_URL . 'shop-marketer.php',
            ],
        ];
    }

    public static function admin_list( string $status = '' ): array {
        global $wpdb;
        $sql = "SELECT * FROM {$wpdb->prefix}arag_marketer_accounts";
        if ( $status ) {
            $sql .= $wpdb->prepare( ' WHERE status=%s', $status );
        }
        $sql .= ' ORDER BY FIELD(status,"pending","active","suspended","rejected"), id DESC LIMIT 300';
        return $wpdb->get_results( $sql, ARRAY_A ) ?: [];
    }
}
