<?php
/**
 * Wholesale_Controller — پورتال B2B عمده‌فروشی قشم
 */
if ( ! defined( 'ABSPATH' ) ) exit;

class Wholesale_Controller {

    public static function register_routes(): void {
        $ns = 'acc/v1';
        $pub = static fn() => true;

        register_rest_route( $ns, '/public/wholesale/meta', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'get_meta' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/public/wholesale/catalog', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'get_public_catalog' ], 'permission_callback' => $pub,
        ] );
        register_rest_route( $ns, '/public/wholesale/apply', [
            'methods' => 'POST', 'callback' => [ __CLASS__, 'submit_application' ], 'permission_callback' => $pub,
        ] );

        $buy = [ __CLASS__, 'perm_buyer' ];
        register_rest_route( $ns, '/wholesale/me', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'get_me' ], 'permission_callback' => $buy,
        ] );
        register_rest_route( $ns, '/wholesale/catalog', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'get_buyer_catalog' ], 'permission_callback' => $buy,
        ] );
        register_rest_route( $ns, '/wholesale/orders', [
            [ 'methods' => 'GET',  'callback' => [ __CLASS__, 'get_orders' ], 'permission_callback' => $buy ],
            [ 'methods' => 'POST', 'callback' => [ __CLASS__, 'place_order' ], 'permission_callback' => $buy ],
        ] );

        $adm = [ __CLASS__, 'perm_manage' ];
        register_rest_route( $ns, '/wholesale/admin/applications', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'admin_applications' ], 'permission_callback' => $adm,
        ] );
        register_rest_route( $ns, '/wholesale/admin/applications/(?P<id>\d+)/approve', [
            'methods' => 'POST', 'callback' => [ __CLASS__, 'admin_approve' ], 'permission_callback' => $adm,
        ] );
        register_rest_route( $ns, '/wholesale/admin/orders', [
            'methods' => 'GET', 'callback' => [ __CLASS__, 'admin_orders' ], 'permission_callback' => $adm,
        ] );
        register_rest_route( $ns, '/wholesale/admin/orders/(?P<id>\d+)/status', [
            'methods' => 'PUT', 'callback' => [ __CLASS__, 'admin_order_status' ], 'permission_callback' => $adm,
        ] );
    }

    public static function perm_buyer(): bool {
        if ( ! is_user_logged_in() ) return false;
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        return Qeshm_Wholesale::can_buyer( acl_current_user_id() );
    }

    public static function perm_manage(): bool {
        if ( ! is_user_logged_in() ) return false;
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        return Qeshm_Wholesale::can_manage( acl_current_user_id() );
    }

    public static function get_meta(): WP_REST_Response {
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        return new WP_REST_Response( [
            'data' => [
                'tiers'          => Qeshm_Wholesale::TIERS,
                'zones'          => Qeshm_Wholesale::ZONES,
                'incoterms'      => Qeshm_Wholesale::INCOTERMS,
                'payment_terms'  => Qeshm_Wholesale::PAYMENT_TERMS,
                'order_status'   => Qeshm_Wholesale::ORDER_STATUS,
                'categories'     => Qeshm_Wholesale::category_counts(),
                'stats'          => Qeshm_Wholesale::stats(),
            ],
        ] );
    }

    public static function get_public_catalog( WP_REST_Request $req ): WP_REST_Response {
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        $result = Qeshm_Wholesale::search_catalog( null, [
            'category'  => $req->get_param( 'category' ),
            'q'         => $req->get_param( 'q' ),
            'sort'      => $req->get_param( 'sort' ),
            'page'      => $req->get_param( 'page' ),
            'per_page'  => $req->get_param( 'per_page' ),
            'origin'    => $req->get_param( 'origin' ),
            'in_stock'  => $req->get_param( 'in_stock' ),
        ] );
        foreach ( $result['items'] as &$it ) {
            unset( $it['prices'], $it['your_price'], $it['price_breaks'] );
            $it['price_hidden'] = true;
        }
        return new WP_REST_Response( [
            'data'  => $result['items'],
            'meta'  => [
                'total'    => $result['total'],
                'page'     => $result['page'],
                'per_page' => $result['per_page'],
                'pages'    => $result['pages'],
            ],
        ] );
    }

    public static function submit_application( WP_REST_Request $req ): WP_REST_Response {
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        $res = Qeshm_Wholesale::create_application( (array) $req->get_json_params() );
        return new WP_REST_Response( $res, ! empty( $res['success'] ) ? 201 : 400 );
    }

    public static function get_me(): WP_REST_Response {
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        global $wpdb;
        $uid = acl_current_user_id();
        $user = $wpdb->get_row( $wpdb->prepare(
            "SELECT ID, display_name, user_login FROM {$wpdb->users} WHERE ID = %d", $uid
        ), ARRAY_A );
        return new WP_REST_Response( [
            'data' => [
                'user'    => [
                    'id'           => $uid,
                    'display_name' => $user['display_name'] ?? '',
                    'login'        => $user['user_login'] ?? '',
                ],
                'account'    => Qeshm_Wholesale::get_account_by_user( $uid ),
                'can_manage' => Qeshm_Wholesale::can_manage( $uid ),
            ],
        ] );
    }

    public static function get_buyer_catalog( WP_REST_Request $req ): WP_REST_Response {
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        $acc = Qeshm_Wholesale::get_account_by_user( acl_current_user_id() );
        $tier = $acc['tier'] ?? 'retailer';
        $result = Qeshm_Wholesale::search_catalog( $tier, [
            'category'  => $req->get_param( 'category' ),
            'q'         => $req->get_param( 'q' ),
            'sort'      => $req->get_param( 'sort' ),
            'page'      => $req->get_param( 'page' ),
            'per_page'  => $req->get_param( 'per_page' ),
            'origin'    => $req->get_param( 'origin' ),
            'in_stock'  => $req->get_param( 'in_stock' ),
        ] );
        return new WP_REST_Response( [
            'data' => $result['items'],
            'meta' => [
                'total'    => $result['total'],
                'page'     => $result['page'],
                'per_page' => $result['per_page'],
                'pages'    => $result['pages'],
                'tier'     => $tier,
            ],
        ] );
    }

    public static function place_order( WP_REST_Request $req ): WP_REST_Response {
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        $res = Qeshm_Wholesale::create_order( acl_current_user_id(), (array) $req->get_json_params() );
        return new WP_REST_Response( $res, ! empty( $res['success'] ) ? 201 : 400 );
    }

    public static function get_orders(): WP_REST_Response {
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        return new WP_REST_Response( [
            'data' => Qeshm_Wholesale::list_orders( acl_current_user_id() ),
        ] );
    }

    public static function admin_applications(): WP_REST_Response {
        global $wpdb;
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        $rows = $wpdb->get_results(
            "SELECT * FROM " . Qeshm_Wholesale::applications_table() . " ORDER BY id DESC LIMIT 100",
            ARRAY_A
        ) ?: [];
        return new WP_REST_Response( [ 'data' => $rows ] );
    }

    public static function admin_approve( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        $id = (int) $req['id'];
        $app = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM " . Qeshm_Wholesale::applications_table() . " WHERE id = %d", $id
        ), ARRAY_A );
        if ( ! $app ) {
            return new WP_REST_Response( [ 'message' => 'درخواست یافت نشد' ], 404 );
        }

        $body = (array) $req->get_json_params();
        $login = sanitize_user( $body['username'] ?? ( 'ws_' . sanitize_title( $app['business_name'] ) ) );
        $tier  = sanitize_key( $body['tier'] ?? ( $app['business_type'] === 'distributor' ? 'distributor' : 'retailer' ) );

        $uid = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT ID FROM {$wpdb->users} WHERE user_login = %s", $login
        ) );
        if ( ! $uid ) {
            $max = (int) $wpdb->get_var( "SELECT COALESCE(MAX(ID),0) FROM {$wpdb->users}" );
            $uid = $max + 1;
            $pass = $body['password'] ?? 'Wholesale1234';
            $wpdb->insert( "{$wpdb->users}", [
                'ID' => $uid, 'user_login' => $login,
                'user_pass' => wp_hash_password( $pass ),
                'user_nicename' => sanitize_title( $login ),
                'user_email' => $app['email'] ?: $login . '@wholesale.test',
                'user_registered' => current_time( 'mysql' ),
                'display_name' => $app['business_name'],
                'user_status' => 0,
            ] );
        }

        $role_slug = 'wholesale_buyer';
        $role_id = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}acl_roles WHERE slug = %s", $role_slug
        ) );
        if ( $role_id ) {
            $exists = (int) $wpdb->get_var( $wpdb->prepare(
                "SELECT COUNT(*) FROM {$wpdb->prefix}acl_user_roles WHERE user_id=%d AND role_id=%d", $uid, $role_id
            ) );
            if ( ! $exists ) {
                $wpdb->insert( "{$wpdb->prefix}acl_user_roles", [
                    'user_id' => $uid, 'role_id' => $role_id,
                    'scope_type' => 'global', 'scope_id' => null, 'granted_by' => acl_current_user_id(),
                ] );
            }
        }

        $acc_exists = (int) $wpdb->get_var( $wpdb->prepare(
            "SELECT id FROM " . Qeshm_Wholesale::accounts_table() . " WHERE user_id = %d", $uid
        ) );
        $acc_data = [
            'user_id'       => $uid,
            'business_name' => $app['business_name'],
            'business_type' => $app['business_type'],
            'tier'          => $tier,
            'zone'          => $app['zone'],
            'city'          => $app['city'],
            'phone'         => $app['phone'],
            'email'         => $app['email'],
            'tax_id'        => $app['tax_id'],
            'address'       => $app['address'],
            'status'        => 'approved',
            'credit_limit'  => (float) ( $body['credit_limit'] ?? 0 ),
            'updated_at'    => current_time( 'mysql' ),
        ];
        if ( $acc_exists ) {
            $wpdb->update( Qeshm_Wholesale::accounts_table(), $acc_data, [ 'id' => $acc_exists ] );
        } else {
            $acc_data['created_at'] = current_time( 'mysql' );
            $wpdb->insert( Qeshm_Wholesale::accounts_table(), $acc_data );
        }

        $wpdb->update( Qeshm_Wholesale::applications_table(), [
            'status'      => 'approved',
            'user_id'     => $uid,
            'reviewed_at' => current_time( 'mysql' ),
        ], [ 'id' => $id ] );

        return new WP_REST_Response( [
            'success'  => true,
            'user_id'  => $uid,
            'username' => $login,
            'password' => $body['password'] ?? 'Wholesale1234',
        ] );
    }

    public static function admin_orders(): WP_REST_Response {
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        return new WP_REST_Response( [
            'data' => Qeshm_Wholesale::list_orders( acl_current_user_id(), true ),
        ] );
    }

    public static function admin_order_status( WP_REST_Request $req ): WP_REST_Response {
        global $wpdb;
        require_once ACC_PATH . 'includes/helpers/qeshm-wholesale.php';
        $status = sanitize_key( $req->get_param( 'status' ) ?? '' );
        if ( ! isset( Qeshm_Wholesale::ORDER_STATUS[ $status ] ) ) {
            return new WP_REST_Response( [ 'message' => 'وضعیت نامعتبر' ], 400 );
        }
        $wpdb->update( Qeshm_Wholesale::orders_table(), [
            'status'     => $status,
            'updated_at' => current_time( 'mysql' ),
        ], [ 'id' => (int) $req['id'] ] );
        return new WP_REST_Response( [ 'success' => true ] );
    }
}
