<?php
/**
 * Growth_Controller — API پورتال رشدگاه / سفیران
 */
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

require_once ACC_PATH . 'includes/helpers/growth-platform.php';

class Growth_Controller {

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

        register_rest_route( $ns, '/growth/meta', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'meta' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/growth/orders', [
            'methods' => 'POST', 'callback' => [ __CLASS__, 'create_order' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/growth/ambassador/signup', [
            'methods' => 'POST', 'callback' => [ __CLASS__, 'ambassador_signup' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/growth/referral/validate', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'validate_ref' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/growth/sessions', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'sessions' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/growth/demo-users', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'demo_users' ], 'permission_callback' => $pub,
        ] );

        register_rest_route( $ns, '/growth/me', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'me' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/growth/dashboard/customer', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'dash_customer' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/growth/dashboard/ambassador', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'dash_ambassador' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/growth/dashboard/admin', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'dash_admin' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/growth/leads', [
            'methods' => 'POST', 'callback' => [ __CLASS__, 'add_lead' ], 'permission_callback' => $jwt,
        ] );
        register_rest_route( $ns, '/growth/orders/(?P<id>\d+)/confirm', [
            'methods' => 'POST', 'callback' => [ __CLASS__, 'confirm_order' ], 'permission_callback' => $jwt,
        ] );
    }

    private static function uid(): int {
        return (int) get_current_user_id();
    }

    private static function ok( $data, int $code = 200 ): WP_REST_Response {
        return new WP_REST_Response( is_array( $data ) ? $data : [ 'data' => $data ], $code );
    }

    private static function err( string $msg, int $code = 400 ): WP_REST_Response {
        return new WP_REST_Response( [ 'success' => false, 'message' => $msg ], $code );
    }

    public static function user_role( int $uid ): string {
        if ( $uid <= 0 ) {
            return 'guest';
        }
        if ( function_exists( 'acl_user_is_super_admin' ) && acl_user_is_super_admin( $uid ) ) {
            return 'admin';
        }
        if ( function_exists( 'acl_user_can' ) && acl_user_can( $uid, 'growth.admin' ) ) {
            return 'admin';
        }
        $login = '';
        if ( (int) get_current_user_id() === $uid ) {
            $login = (string) ( wp_get_current_user()->user_login ?? '' );
        } else {
            global $wpdb;
            $login = (string) $wpdb->get_var( $wpdb->prepare(
                "SELECT user_login FROM {$wpdb->users} WHERE ID = %d", $uid
            ) );
        }
        if ( in_array( $login, [ 'ostadowner', 'growth_admin' ], true ) ) {
            return 'admin';
        }
        $amb = Growth_Platform::get_ambassador_by_user( $uid );
        if ( $amb ) {
            return $amb['path'] === 'device_referral' ? 'referral' : 'ambassador';
        }
        if ( function_exists( 'acl_user_can' ) && acl_user_can( $uid, 'growth.ambassador' ) ) {
            return 'ambassador';
        }
        return 'customer';
    }

    public static function meta(): WP_REST_Response {
        return self::ok( Growth_Platform::public_meta() );
    }

    public static function sessions(): WP_REST_Response {
        return self::ok( [ 'sessions' => Growth_Platform::list_open_sessions() ] );
    }

    public static function validate_ref( WP_REST_Request $req ): WP_REST_Response {
        $code = (string) $req->get_param( 'code' );
        $amb  = Growth_Platform::find_ambassador_by_code( $code );
        if ( ! $amb ) {
            return self::err( 'کد ارجاع نامعتبر است', 404 );
        }
        return self::ok( [
            'valid'         => true,
            'referral_code' => $amb['referral_code'],
            'display_name'  => $amb['display_name'],
            'path'          => $amb['path'],
        ] );
    }

    public static function create_order( WP_REST_Request $req ): WP_REST_Response {
        $body = $req->get_json_params() ?: [];
        $uid  = self::uid();
        if ( $uid > 0 ) {
            $body['user_id'] = $uid;
        }
        $res = Growth_Platform::create_order( $body );
        return new WP_REST_Response( $res, empty( $res['success'] ) ? 400 : 200 );
    }

    public static function ambassador_signup( WP_REST_Request $req ): WP_REST_Response {
        $body = $req->get_json_params() ?: [];
        $uid  = self::uid();
        if ( $uid > 0 ) {
            $body['user_id'] = $uid;
            $u = wp_get_current_user();
            if ( empty( $body['display_name'] ) ) {
                $body['display_name'] = $u->display_name;
            }
            if ( empty( $body['email'] ) ) {
                $body['email'] = $u->user_email;
            }
        }
        $res = Growth_Platform::register_ambassador( $body );
        return new WP_REST_Response( $res, empty( $res['success'] ) ? 400 : 200 );
    }

    public static function me(): WP_REST_Response {
        $uid = self::uid();
        $amb = Growth_Platform::get_ambassador_by_user( $uid );
        $u   = wp_get_current_user();
        global $wpdb;
        $display = (string) ( $u->display_name ?? '' );
        if ( $display === '' && $uid > 0 ) {
            $display = (string) $wpdb->get_var( $wpdb->prepare(
                "SELECT display_name FROM {$wpdb->users} WHERE ID = %d", $uid
            ) );
        }
        return self::ok( [
            'user_id'     => $uid,
            'role'        => self::user_role( $uid ),
            'display'     => $display ?: ( $u->user_login ?? '' ),
            'username'    => $u->user_login ?? '',
            'ambassador'  => $amb ? [
                'id'            => (int) $amb['id'],
                'referral_code' => $amb['referral_code'],
                'path'          => $amb['path'],
                'tier'          => $amb['tier'],
            ] : null,
        ] );
    }

    public static function dash_customer(): WP_REST_Response {
        $uid = self::uid();
        return self::ok( [
            'orders' => Growth_Platform::customer_orders( $uid ),
            'role'   => self::user_role( $uid ),
        ] );
    }

    public static function dash_ambassador(): WP_REST_Response {
        $uid = self::uid();
        $amb = Growth_Platform::get_ambassador_by_user( $uid );
        if ( ! $amb ) {
            return self::err( 'حساب سفیر یافت نشد — ابتدا ثبت‌نام کنید', 404 );
        }
        return self::ok( Growth_Platform::ambassador_dashboard( (int) $amb['id'] ) );
    }

    public static function dash_admin(): WP_REST_Response {
        $uid = self::uid();
        if ( self::user_role( $uid ) !== 'admin' ) {
            return self::err( 'دسترسی ادمین لازم است', 403 );
        }
        return self::ok( Growth_Platform::admin_dashboard() );
    }

    public static function add_lead( WP_REST_Request $req ): WP_REST_Response {
        $uid = self::uid();
        $amb = Growth_Platform::get_ambassador_by_user( $uid );
        if ( ! $amb ) {
            return self::err( 'حساب سفیر یافت نشد', 404 );
        }
        $body = $req->get_json_params() ?: [];
        $res  = Growth_Platform::add_lead( (int) $amb['id'], $body );
        if ( ! empty( $res['success'] ) ) {
            $res['dashboard'] = Growth_Platform::ambassador_dashboard( (int) $amb['id'] );
        }
        return new WP_REST_Response( $res, empty( $res['success'] ) ? 400 : 200 );
    }

    public static function confirm_order( WP_REST_Request $req ): WP_REST_Response {
        $uid = self::uid();
        if ( self::user_role( $uid ) !== 'admin' ) {
            return self::err( 'دسترسی ادمین لازم است', 403 );
        }
        $id  = (int) $req->get_param( 'id' );
        $res = Growth_Platform::confirm_order( $id, $uid );
        return new WP_REST_Response( $res, empty( $res['success'] ) ? 400 : 200 );
    }

    public static function demo_users(): WP_REST_Response {
        if ( ! function_exists( 'acc_demo_endpoints_allowed' ) || ! acc_demo_endpoints_allowed() ) {
            return new WP_REST_Response( [ 'success' => false, 'message' => 'غیرفعال' ], 404 );
        }
        return self::ok( [
            'password' => 'Growth1234',
            'users'    => [
                [ 'login' => 'ostadowner',          'role' => 'admin',      'label' => 'مدیر (ostadowner)' ],
                [ 'login' => 'growth_admin',         'role' => 'admin',      'label' => 'مدیر رشدگاه' ],
                [ 'login' => 'growth_ambassador',    'role' => 'ambassador', 'label' => 'سفیر همسایه' ],
                [ 'login' => 'growth_referral',      'role' => 'referral',   'label' => 'معرف دستگاه' ],
                [ 'login' => 'growth_customer',      'role' => 'customer',   'label' => 'مشتری' ],
            ],
        ] );
    }
}
