<?php
/**
 * SR_Marketer_Controller — API بازاریابی خدمات HVAC
 */
if ( ! defined( 'ABSPATH' ) ) exit;

require_once ACC_PATH . 'includes/helpers/svc-marketer.php';

class SR_Marketer_Controller {

    public static function register_routes(): void {
        $ns  = 'acc/v1';
        $pub = '__return_true';
        $staff = [ self::class, 'perm_staff' ];

        register_rest_route( $ns, '/service/marketer/register', [
            'methods' => 'POST', 'callback' => [ self::class, 'register' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/service/marketer/me', [
            'methods' => 'GET', 'callback' => [ self::class, 'get_me' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/service/marketer/leads', [
            'methods' => 'POST', 'callback' => [ self::class, 'add_lead' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/service/marketer/payout', [
            'methods' => 'POST', 'callback' => [ self::class, 'request_payout' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/service/marketer/leaderboard', [
            'methods' => 'GET', 'callback' => [ self::class, 'leaderboard' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/service/marketer/validate', [
            'methods' => 'GET', 'callback' => [ self::class, 'validate_code' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/service/marketer/admin/payouts', [
            'methods' => 'GET', 'callback' => [ self::class, 'admin_payouts' ], 'permission_callback' => $staff,
        ] );
        register_rest_route( $ns, '/service/marketer/admin/payout/(?P<id>\d+)', [
            'methods' => 'POST', 'callback' => [ self::class, 'admin_process_payout' ], 'permission_callback' => $staff,
        ] );
    }

    public static function perm_staff(): bool {
        return is_user_logged_in() && acl_user_can( acl_current_user_id(), 'service.view' );
    }

    public static function register( WP_REST_Request $req ): WP_REST_Response {
        $result = Svc_Marketer::register( [
            'phone'        => $req->get_param( 'phone' ),
            'display_name' => $req->get_param( 'display_name' ) ?? $req->get_param( 'name' ),
            'email'        => $req->get_param( 'email' ),
            'city'         => $req->get_param( 'city' ),
        ] );

        if ( empty( $result['success'] ) ) {
            return new WP_REST_Response( $result, 400 );
        }

        $id = (int) $result['account']['id'];
        return new WP_REST_Response( [
            'success'    => true,
            'is_new'     => $result['is_new'] ?? false,
            'marketer_id'=> $id,
            'session'    => self::_session_token( $id ),
            'data'       => Svc_Marketer::dashboard( $id ),
        ] );
    }

    public static function get_me( WP_REST_Request $req ): WP_REST_Response {
        $id = self::_resolve_marketer_id( $req );
        if ( ! $id ) {
            return new WP_REST_Response( [ 'message' => 'احراز هویت لازم است' ], 401 );
        }
        return new WP_REST_Response( [ 'data' => Svc_Marketer::dashboard( $id ) ] );
    }

    public static function add_lead( WP_REST_Request $req ): WP_REST_Response {
        $id = self::_resolve_marketer_id( $req );
        if ( ! $id ) {
            return new WP_REST_Response( [ 'message' => 'احراز هویت لازم است' ], 401 );
        }

        $result = Svc_Marketer::introduce_lead( $id, [
            'customer_name'    => $req->get_param( 'customer_name' ) ?? $req->get_param( 'name' ),
            'customer_phone'   => $req->get_param( 'customer_phone' ) ?? $req->get_param( 'phone' ),
            'customer_city'    => $req->get_param( 'customer_city' ) ?? $req->get_param( 'city' ),
            'service_interest' => $req->get_param( 'service_interest' ),
            'notes'            => $req->get_param( 'notes' ),
        ] );

        if ( empty( $result['success'] ) ) {
            return new WP_REST_Response( $result, 400 );
        }

        $result['data'] = Svc_Marketer::dashboard( $id );
        return new WP_REST_Response( $result );
    }

    public static function request_payout( WP_REST_Request $req ): WP_REST_Response {
        $id = self::_resolve_marketer_id( $req );
        if ( ! $id ) {
            return new WP_REST_Response( [ 'message' => 'احراز هویت لازم است' ], 401 );
        }

        $result = Svc_Marketer::request_payout( $id, [
            'holder' => $req->get_param( 'holder' ),
            'iban'   => $req->get_param( 'iban' ),
            'bank'   => $req->get_param( 'bank' ),
            'card'   => $req->get_param( 'card' ),
        ] );

        if ( empty( $result['success'] ) ) {
            return new WP_REST_Response( $result, 400 );
        }

        $result['data'] = Svc_Marketer::dashboard( $id );
        return new WP_REST_Response( $result );
    }

    public static function leaderboard(): WP_REST_Response {
        return new WP_REST_Response( [ 'data' => Svc_Marketer::leaderboard() ] );
    }

    public static function validate_code( WP_REST_Request $req ): WP_REST_Response {
        $code = strtoupper( sanitize_text_field( $req->get_param( 'code' ) ?? $req->get_param( 'mkt' ) ?? '' ) );
        $m = Svc_Marketer::get_by_code( $code );
        if ( ! $m ) {
            return new WP_REST_Response( [ 'valid' => false, 'message' => 'کد بازاریاب نامعتبر' ], 404 );
        }
        return new WP_REST_Response( [
            'valid' => true,
            'marketer_name' => $m['display_name'],
            'code'  => $m['marketer_code'],
        ] );
    }

    public static function admin_payouts(): WP_REST_Response {
        global $wpdb;
        $rows = $wpdb->get_results(
            "SELECT p.*, a.display_name, a.phone, a.marketer_code
             FROM {$wpdb->prefix}svc_marketer_payouts p
             JOIN {$wpdb->prefix}svc_marketer_accounts a ON a.id = p.marketer_id
             WHERE p.status IN ('requested','processing')
             ORDER BY p.created_at ASC LIMIT 100",
            ARRAY_A
        );
        return new WP_REST_Response( [ 'data' => $rows ?: [] ] );
    }

    public static function admin_process_payout( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        $id = (int) $req['id'];
        $action = sanitize_key( $req->get_param( 'action' ) ?? 'pay' );
        $note = sanitize_text_field( $req->get_param( 'note' ) ?? '' );

        $payout = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}svc_marketer_payouts WHERE id=%d", $id
        ), ARRAY_A );
        if ( ! $payout ) {
            return new WP_REST_Response( [ 'message' => 'درخواست یافت نشد' ], 404 );
        }

        if ( $action === 'reject' ) {
            $wpdb->update( "{$wpdb->prefix}svc_marketer_payouts", [
                'status'      => 'rejected',
                'admin_note'  => $note,
                'processed_at'=> current_time( 'mysql' ),
            ], [ 'id' => $id ] );
            return new WP_REST_Response( [ 'success' => true ] );
        }

        $wpdb->update( "{$wpdb->prefix}svc_marketer_payouts", [
            'status'       => 'paid',
            'admin_note'   => $note,
            'processed_at' => current_time( 'mysql' ),
        ], [ 'id' => $id ] );

        $wpdb->query( $wpdb->prepare(
            "UPDATE {$wpdb->prefix}svc_marketer_commissions SET status='paid', paid_at=%s
             WHERE marketer_id=%d AND status IN ('pending','approved')",
            current_time( 'mysql' ), (int) $payout['marketer_id']
        ) );

        Svc_Marketer::sync_balances( (int) $payout['marketer_id'] );

        return new WP_REST_Response( [ 'success' => true ] );
    }

    private static function _resolve_marketer_id( WP_REST_Request $req ): int {
        $hdr = $req->get_header( 'x-marketer-session' ) ?? '';
        if ( $hdr && str_starts_with( $hdr, 'mk_' ) && function_exists( 'acc_resolve_opaque_token' ) ) {
            $id = acc_resolve_opaque_token( 'mk_', $hdr );
            if ( $id > 0 ) {
                return $id;
            }
        }
        // marketer_id خام از کلاینت دیگر پذیرفته نمی‌شود (جلوگیری از جعل هویت)
        return 0;
    }

    private static function _session_token( int $marketer_id ): string {
        if ( function_exists( 'acc_issue_opaque_token' ) ) {
            return acc_issue_opaque_token( 'mk_', $marketer_id, 7 * DAY_IN_SECONDS );
        }
        return 'mk_' . bin2hex( random_bytes( 32 ) );
    }
}
