<?php
/**
 * Arag_Marketer_Controller — API بازاریاب فروشگاه
 *
 * Public:
 *   POST /public/arag/marketer/register
 *   POST /public/arag/marketer/auth/send-otp
 *   POST /public/arag/marketer/auth/verify-otp
 * JWT marketer:
 *   GET  /public/arag/marketer/me
 *   GET  /public/arag/marketer/dashboard
 *   GET  /public/arag/marketer/products
 *   POST /public/arag/marketer/shops
 *   GET  /public/arag/marketer/shops
 *   POST /public/arag/marketer/orders/create
 *   POST /public/arag/marketer/payout/request
 *   PUT  /public/arag/marketer/profile
 * Admin (shop.manage):
 *   GET  /arag/admin/marketers
 *   PUT  /arag/admin/marketers/{id}/status
 *   POST /arag/admin/marketers/{id}/credit
 *   PUT  /arag/admin/marketers/{id}/credit-limit
 *   GET  /arag/admin/marketer-payouts
 *   PUT  /arag/admin/marketer-payouts/{id}
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

require_once ACC_PATH . 'includes/helpers/arag-shop.php';
require_once ACC_PATH . 'includes/helpers/arag-marketer.php';
require_once ACC_PATH . 'includes/helpers/acc-sms.php';

class Arag_Marketer_Controller {

    public static function register_routes(): void {
        $ns  = 'acc/v1';
        $jwt = 'acc_jwt_check_permission';

        register_rest_route( $ns, '/public/arag/marketer/register', [
            'methods' => 'POST', 'callback' => [ self::class, 'register' ],
            'permission_callback' => '__return_true',
        ] );
        register_rest_route( $ns, '/public/arag/marketer/auth/send-otp', [
            'methods' => 'POST', 'callback' => [ self::class, 'send_otp' ],
            'permission_callback' => '__return_true',
        ] );
        register_rest_route( $ns, '/public/arag/marketer/auth/verify-otp', [
            'methods' => 'POST', 'callback' => [ self::class, 'verify_otp' ],
            'permission_callback' => '__return_true',
        ] );

        register_rest_route( $ns, '/public/arag/marketer/me', [
            'methods' => 'GET', 'callback' => [ self::class, 'me' ],
            'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/public/arag/marketer/dashboard', [
            'methods' => 'GET', 'callback' => [ self::class, 'dashboard' ],
            'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/public/arag/marketer/products', [
            'methods' => 'GET', 'callback' => [ self::class, 'products' ],
            'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/public/arag/marketer/shops', [
            [ 'methods' => 'GET',  'callback' => [ self::class, 'list_shops' ], 'permission_callback' => $jwt ],
            [ 'methods' => 'POST', 'callback' => [ self::class, 'save_shop' ],  'permission_callback' => $jwt ],
        ] );
        register_rest_route( $ns, '/public/arag/marketer/orders/create', [
            'methods' => 'POST', 'callback' => [ self::class, 'create_sale' ],
            'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/public/arag/marketer/payout/request', [
            'methods' => 'POST', 'callback' => [ self::class, 'payout_request' ],
            'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/public/arag/marketer/profile', [
            'methods' => 'PUT', 'callback' => [ self::class, 'update_profile' ],
            'permission_callback' => $jwt,
        ] );

        register_rest_route( $ns, '/arag/admin/marketers', [
            'methods' => 'GET', 'callback' => [ self::class, 'admin_list' ],
            'permission_callback' => [ self::class, 'admin_perm' ],
        ] );
        register_rest_route( $ns, '/arag/admin/marketers/(?P<id>\d+)/status', [
            'methods' => 'PUT', 'callback' => [ self::class, 'admin_set_status' ],
            'permission_callback' => [ self::class, 'admin_perm' ],
        ] );
        register_rest_route( $ns, '/arag/admin/marketers/(?P<id>\d+)/credit', [
            'methods' => 'POST', 'callback' => [ self::class, 'admin_credit_topup' ],
            'permission_callback' => [ self::class, 'admin_perm' ],
        ] );
        register_rest_route( $ns, '/arag/admin/marketers/(?P<id>\d+)/credit-limit', [
            'methods' => 'PUT', 'callback' => [ self::class, 'admin_credit_limit' ],
            'permission_callback' => [ self::class, 'admin_perm' ],
        ] );
        register_rest_route( $ns, '/arag/admin/marketer-payouts', [
            'methods' => 'GET', 'callback' => [ self::class, 'admin_payouts' ],
            'permission_callback' => [ self::class, 'admin_perm' ],
        ] );
        register_rest_route( $ns, '/arag/admin/marketer-payouts/(?P<id>\d+)', [
            'methods' => 'PUT', 'callback' => [ self::class, 'admin_process_payout' ],
            'permission_callback' => [ self::class, 'admin_perm' ],
        ] );
    }

    public static function admin_perm(): bool {
        return Arag_Shop::admin_can();
    }

    private static function _current_marketer(): ?array {
        $uid = get_current_user_id();
        if ( $uid <= 0 ) {
            return null;
        }
        $acc = Arag_Marketer::get_by_user( $uid );
        if ( $acc ) {
            return $acc;
        }
        $phone = (string) get_user_meta( $uid, 'billing_phone', true );
        if ( $phone ) {
            return Arag_Marketer::get_by_phone( $phone );
        }
        return null;
    }

    private static function _require_marketer( bool $need_active = true ): array {
        $acc = self::_current_marketer();
        if ( ! $acc ) {
            return [ 'ok' => false, 'response' => new WP_REST_Response( [
                'success' => false, 'message' => 'حساب بازاریاب یافت نشد. ابتدا ثبت‌نام کنید.',
            ], 403 ) ];
        }
        if ( $need_active && $acc['status'] !== 'active' ) {
            $msg = match ( $acc['status'] ) {
                'pending'   => 'حساب شما هنوز توسط مدیر تایید نشده است.',
                'suspended' => 'حساب شما تعلیق شده است.',
                'rejected'  => 'درخواست شما رد شده است.',
                default     => 'حساب فعال نیست.',
            };
            return [ 'ok' => false, 'response' => new WP_REST_Response( [
                'success' => false, 'message' => $msg, 'account' => $acc,
            ], 403 ) ];
        }
        return [ 'ok' => true, 'account' => $acc ];
    }

    public static function register( WP_REST_Request $req ): WP_REST_Response {
        $r = Arag_Marketer::register( [
            'phone'        => (string) $req->get_param( 'phone' ),
            'display_name' => (string) $req->get_param( 'display_name' ),
            'national_id'  => (string) $req->get_param( 'national_id' ),
            'city'         => (string) $req->get_param( 'city' ),
            'address'      => (string) $req->get_param( 'address' ),
            'bank_sheba'   => (string) $req->get_param( 'bank_sheba' ),
            'bank_card'    => (string) $req->get_param( 'bank_card' ),
            'bank_name'    => (string) $req->get_param( 'bank_name' ),
        ] );
        return new WP_REST_Response( $r, ! empty( $r['success'] ) ? 200 : 400 );
    }

    public static function send_otp( WP_REST_Request $req ): WP_REST_Response {
        require_once ACC_PATH . 'includes/controllers/Arag_Shop_Controller.php';
        return Arag_Shop_Controller::send_otp( $req );
    }

    public static function verify_otp( WP_REST_Request $req ): WP_REST_Response {
        require_once ACC_PATH . 'includes/controllers/Arag_Shop_Controller.php';
        $resp = Arag_Shop_Controller::verify_otp( $req );
        $data = $resp->get_data();
        $status = method_exists( $resp, 'get_status' ) ? (int) $resp->get_status() : 200;
        if ( is_array( $data ) && ! empty( $data['success'] ) ) {
            $phone = Arag_Marketer::normalize_phone( (string) $req->get_param( 'phone' ) );
            $data['marketer'] = Arag_Marketer::get_by_phone( $phone );
            return new WP_REST_Response( $data, $status ?: 200 );
        }
        return $resp;
    }

    public static function me( WP_REST_Request $req ): WP_REST_Response {
        $g = self::_require_marketer( false );
        if ( ! $g['ok'] ) {
            return $g['response'];
        }
        return new WP_REST_Response( [ 'success' => true, 'account' => $g['account'] ] );
    }

    public static function dashboard( WP_REST_Request $req ): WP_REST_Response {
        $g = self::_require_marketer( false );
        if ( ! $g['ok'] ) {
            return $g['response'];
        }
        $dash = Arag_Marketer::dashboard( (int) $g['account']['id'] );
        return new WP_REST_Response( $dash, ! empty( $dash['success'] ) ? 200 : 400 );
    }

    public static function products( WP_REST_Request $req ): WP_REST_Response {
        $g = self::_require_marketer( true );
        if ( ! $g['ok'] ) {
            return $g['response'];
        }
        $families = Arag_Shop::list_families_public();
        $out      = [];
        foreach ( $families as $f ) {
            $detail = Arag_Shop::get_family_by_id( (int) $f['id'] );
            if ( $detail ) {
                $out[] = $detail;
            }
        }
        return new WP_REST_Response( [
            'success' => true,
            'data'    => $out,
            'rates'   => [
                'marketer_pct' => Arag_Marketer::PCT_MARKETER,
                'site_pct'     => Arag_Marketer::PCT_SITE_WITH_MARKETER,
            ],
        ] );
    }

    public static function list_shops( WP_REST_Request $req ): WP_REST_Response {
        $g = self::_require_marketer( true );
        if ( ! $g['ok'] ) {
            return $g['response'];
        }
        global $wpdb;
        $rows = $wpdb->get_results( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}arag_marketer_shops WHERE marketer_id=%d ORDER BY id DESC",
            (int) $g['account']['id']
        ), ARRAY_A ) ?: [];
        return new WP_REST_Response( [ 'success' => true, 'data' => $rows ] );
    }

    public static function save_shop( WP_REST_Request $req ): WP_REST_Response {
        $g = self::_require_marketer( true );
        if ( ! $g['ok'] ) {
            return $g['response'];
        }
        $r = Arag_Marketer::upsert_shop( (int) $g['account']['id'], [
            'shop_phone'  => (string) $req->get_param( 'shop_phone' ),
            'shop_name'   => (string) $req->get_param( 'shop_name' ),
            'owner_name'  => (string) $req->get_param( 'owner_name' ),
            'city'        => (string) $req->get_param( 'city' ),
            'address'     => (string) $req->get_param( 'address' ),
            'notes'       => (string) $req->get_param( 'notes' ),
        ] );
        return new WP_REST_Response( $r, ! empty( $r['success'] ) ? 200 : 400 );
    }

    /**
     * فروش توسط بازاریاب — باید shop_phone ثبت‌شده باشد
     * payment_method: zarinpal|cod|bank|demo|marketer_credit
     */
    public static function create_sale( WP_REST_Request $req ): WP_REST_Response {
        $g = self::_require_marketer( true );
        if ( ! $g['ok'] ) {
            return $g['response'];
        }
        $mid = (int) $g['account']['id'];

        $shop_phone = Arag_Marketer::normalize_phone( (string) $req->get_param( 'shop_phone' ) );
        $shop       = Arag_Marketer::shop_by_phone( $shop_phone );
        if ( ! $shop || (int) $shop['marketer_id'] !== $mid ) {
            /* ثبت سریع اگر مشخصات آمده */
            if ( $req->get_param( 'shop_name' ) ) {
                $up = Arag_Marketer::upsert_shop( $mid, [
                    'shop_phone' => $shop_phone,
                    'shop_name'  => (string) $req->get_param( 'shop_name' ),
                    'owner_name' => (string) ( $req->get_param( 'owner_name' ) ?: $req->get_param( 'billing_name' ) ),
                    'city'       => (string) ( $req->get_param( 'city' ) ?: $req->get_param( 'billing_city' ) ),
                    'address'    => (string) ( $req->get_param( 'address' ) ?: $req->get_param( 'billing_address' ) ),
                    'notes'      => (string) $req->get_param( 'notes' ),
                ] );
                if ( empty( $up['success'] ) ) {
                    return new WP_REST_Response( $up, 400 );
                }
                $shop = $up['shop'];
            } else {
                return new WP_REST_Response( [
                    'success' => false,
                    'message' => 'ابتدا فروشگاه را با موبایل و مشخصات کامل ثبت کنید',
                ], 400 );
            }
        }

        $billing = (array) ( $req->get_param( 'billing' ) ?? [] );
        if ( empty( $billing['phone'] ) ) {
            $billing['phone'] = $shop['shop_phone'];
        }
        if ( empty( $billing['name'] ) ) {
            $billing['name'] = $shop['owner_name'] ?: $shop['shop_name'];
        }
        if ( empty( $billing['city'] ) ) {
            $billing['city'] = $shop['city'] ?? '';
        }
        if ( empty( $billing['address'] ) ) {
            $billing['address'] = $shop['address'] ?? '';
        }

        $payment_method = sanitize_key( $req->get_param( 'payment_method' ) ?? 'cod' );
        $use_credit     = ( $payment_method === 'marketer_credit' );

        /* ساخت سفارش از طریق کنترلر فروشگاه */
        require_once ACC_PATH . 'includes/controllers/Arag_Shop_Controller.php';
        $inner = new WP_REST_Request( 'POST', '/acc/v1/public/arag/orders/create' );
        $inner->set_param( 'items', $req->get_param( 'items' ) );
        $inner->set_param( 'billing', $billing );
        $inner->set_param( 'shipping_method', $req->get_param( 'shipping_method' ) ?? 'post' );
        $inner->set_param( 'payment_method', $use_credit ? 'cod' : $payment_method );
        $inner->set_param( 'note', (string) ( $req->get_param( 'note' ) ?? '' ) . ' [فروش بازاریاب ' . $g['account']['marketer_code'] . ']' );
        $inner->set_param( 'user_id', Arag_Marketer::ensure_user_for_phone( $shop['shop_phone'], $billing['name'] ) );
        $inner->set_param( 'coupon_code', $req->get_param( 'coupon_code' ) );
        $inner->set_param( 'sold_by_marketer_id', $mid );

        $resp = Arag_Shop_Controller::create_order( $inner );
        $body = $resp->get_data();
        if ( empty( $body['success'] ) ) {
            return $resp;
        }

        $order_id = (int) ( $body['data']['order_id'] ?? 0 );
        if ( $order_id > 0 ) {
            Arag_Marketer::attach_to_order( $order_id, $mid );

            if ( $use_credit ) {
                $total = (float) ( $body['data']['total'] ?? 0 );
                $cr    = Arag_Marketer::use_credit( $mid, $total, $order_id );
                if ( empty( $cr['success'] ) ) {
                    global $wpdb;
                    $wpdb->update( "{$wpdb->prefix}arag_orders", [
                        'payment_status' => 'failed',
                        'order_status'   => 'cancelled',
                        'customer_note'  => 'لغو به‌دلیل کمبود اعتبار بازاریاب',
                    ], [ 'id' => $order_id ] );
                    return new WP_REST_Response( $cr, 400 );
                }
                global $wpdb;
                $wpdb->update( "{$wpdb->prefix}arag_orders", [
                    'payment_method' => 'marketer_credit',
                    'payment_status' => 'paid',
                    'order_status'   => 'processing',
                    'ref_id'         => 'CR-' . $mid . '-' . $order_id,
                ], [ 'id' => $order_id ] );
                Arag_Marketer::on_payment_received( $order_id );
                if ( file_exists( ACC_PATH . 'includes/helpers/arag-erp.php' ) ) {
                    require_once ACC_PATH . 'includes/helpers/arag-erp.php';
                    Arag_Erp::on_order_confirmed( $order_id );
                }
                $body['data']['payment_method'] = 'marketer_credit';
                $body['data']['payment_status'] = 'paid';
                $body['data']['credit_balance'] = $cr['credit_balance'];
            }
        }

        $body['data']['shop'] = $shop;
        return new WP_REST_Response( $body, 201 );
    }

    public static function payout_request( WP_REST_Request $req ): WP_REST_Response {
        $g = self::_require_marketer( true );
        if ( ! $g['ok'] ) {
            return $g['response'];
        }
        $amount = (float) ( $req->get_param( 'amount' ) ?? 0 );
        if ( $amount <= 0 ) {
            $amount = (float) $g['account']['balance_payable'];
        }
        $r = Arag_Marketer::request_payout( (int) $g['account']['id'], $amount );
        return new WP_REST_Response( $r, ! empty( $r['success'] ) ? 200 : 400 );
    }

    public static function update_profile( WP_REST_Request $req ): WP_REST_Response {
        $g = self::_require_marketer( false );
        if ( ! $g['ok'] ) {
            return $g['response'];
        }
        global $wpdb;
        $upd = [];
        foreach ( [ 'display_name', 'city', 'address', 'bank_sheba', 'bank_card', 'bank_name', 'national_id' ] as $k ) {
            $v = $req->get_param( $k );
            if ( $v !== null ) {
                $upd[ $k ] = sanitize_text_field( (string) $v );
            }
        }
        if ( $upd ) {
            $wpdb->update( "{$wpdb->prefix}arag_marketer_accounts", $upd, [ 'id' => (int) $g['account']['id'] ] );
        }
        return new WP_REST_Response( [
            'success' => true,
            'account' => Arag_Marketer::get_by_id( (int) $g['account']['id'] ),
        ] );
    }

    /* ── Admin ── */
    public static function admin_list( WP_REST_Request $req ): WP_REST_Response {
        $status = sanitize_key( (string) ( $req->get_param( 'status' ) ?? '' ) );
        return new WP_REST_Response( [
            'success' => true,
            'data'    => Arag_Marketer::admin_list( $status ),
        ] );
    }

    public static function admin_set_status( WP_REST_Request $req ): WP_REST_Response {
        $r = Arag_Marketer::set_status(
            (int) $req['id'],
            sanitize_key( (string) $req->get_param( 'status' ) ),
            get_current_user_id(),
            (string) ( $req->get_param( 'note' ) ?? '' )
        );
        return new WP_REST_Response( $r, ! empty( $r['success'] ) ? 200 : 400 );
    }

    public static function admin_credit_topup( WP_REST_Request $req ): WP_REST_Response {
        $r = Arag_Marketer::credit_topup(
            (int) $req['id'],
            (float) $req->get_param( 'amount' ),
            get_current_user_id(),
            (string) ( $req->get_param( 'note' ) ?? 'شارژ توسط مدیر' )
        );
        return new WP_REST_Response( $r, ! empty( $r['success'] ) ? 200 : 400 );
    }

    public static function admin_credit_limit( WP_REST_Request $req ): WP_REST_Response {
        $r = Arag_Marketer::set_credit_limit( (int) $req['id'], (float) $req->get_param( 'limit' ) );
        return new WP_REST_Response( $r, ! empty( $r['success'] ) ? 200 : 400 );
    }

    public static function admin_payouts( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $rows = $wpdb->get_results(
            "SELECT p.*, a.display_name, a.phone, a.marketer_code
             FROM {$wpdb->prefix}arag_marketer_payouts p
             INNER JOIN {$wpdb->prefix}arag_marketer_accounts a ON a.id = p.marketer_id
             ORDER BY FIELD(p.status,'requested','paid','rejected'), p.id DESC
             LIMIT 200",
            ARRAY_A
        ) ?: [];
        return new WP_REST_Response( [ 'success' => true, 'data' => $rows ] );
    }

    public static function admin_process_payout( WP_REST_Request $req ): WP_REST_Response {
        $r = Arag_Marketer::process_payout(
            (int) $req['id'],
            sanitize_key( (string) $req->get_param( 'status' ) ),
            get_current_user_id(),
            (string) ( $req->get_param( 'note' ) ?? '' )
        );
        return new WP_REST_Response( $r, ! empty( $r['success'] ) ? 200 : 400 );
    }
}
