<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class ACC_DashboardController {

    public static function get_dashboard_data( \WP_REST_Request $request ) {

        $user_id = get_current_user_id();

        if ( $user_id <= 0 ) {
            return new \WP_REST_Response( [
                'success' => false,
                'message' => 'User not logged in',
            ], 401 );
        }

        $current_user = get_userdata( $user_id );

        return new \WP_REST_Response( [
            'success' => true,
            'user'    => [
                'id'           => $user_id,
                'username'     => $current_user->user_login,
                'email'        => $current_user->user_email,
                'display_name' => $current_user->display_name,
            ],
            'message' => 'ACC dashboard data',
        ], 200 );
    }

    public static function get_menus( \WP_REST_Request $request ) {

        global $wpdb;

        $user_id = get_current_user_id();

        if ( $user_id <= 0 ) {
            return new \WP_REST_Response( [ 'success' => false, 'message' => 'Unauthorized' ], 401 );
        }

        $roles = $wpdb->get_col( $wpdb->prepare(
            "SELECT role_id FROM {$wpdb->prefix}accj_user_roles WHERE user_id = %d",
            $user_id
        ) );

        if ( empty( $roles ) ) {
            return [ 'success' => true, 'items' => [], 'message' => 'No menus assigned' ];
        }

        $role_placeholders = implode( ',', array_fill( 0, count( $roles ), '%d' ) );
        $allowed_ids = $wpdb->get_col( $wpdb->prepare(
            "SELECT DISTINCT menu_id FROM {$wpdb->prefix}accj_menu_permissions WHERE role_id IN ({$role_placeholders}) AND can_view = 1",
            $roles
        ) );

        if ( empty( $allowed_ids ) ) {
            return [ 'success' => true, 'items' => [], 'message' => 'No menus found' ];
        }

        $id_placeholders = implode( ',', array_fill( 0, count( $allowed_ids ), '%d' ) );
        $rows = $wpdb->get_results(
            $wpdb->prepare(
                "SELECT id, parent_id, title, description, icon, route
                 FROM {$wpdb->prefix}accj_menus
                 WHERE id IN ({$id_placeholders}) AND is_active = 1
                 ORDER BY menu_order ASC",
                $allowed_ids
            ),
            ARRAY_A
        );

        return [
            'success' => true,
            'items'   => $rows,
            'message' => 'ACC menus loaded successfully',
        ];
    }

    public static function get_menus_rbac_v2( \WP_REST_Request $request ) {
        global $wpdb;

        $user_id = acc_jwt_get_user_from_request();

        if ( ! $user_id || $user_id <= 0 ) {
            return new \WP_REST_Response( [
                'success' => false,
                'error'   => 'Not authenticated',
            ], 401 );
        }

        $query = $wpdb->prepare(
            "SELECT m.id, m.parent_id, m.title, m.route, m.icon, m.description
             FROM {$wpdb->prefix}accj_menus m
             JOIN {$wpdb->prefix}accj_menu_permissions p ON m.id = p.menu_id
             JOIN {$wpdb->prefix}accj_user_roles ur ON p.role_id = ur.role_id
             WHERE ur.user_id = %d
               AND p.can_view = 1
               AND m.is_active = 1
             GROUP BY m.id
             ORDER BY m.menu_order ASC",
            $user_id
        );

        $results = $wpdb->get_results( $query, ARRAY_A );

        return [
            'success' => true,
            'count'   => count( $results ),
            'items'   => $results ? $results : [],
            'source'  => 'rbac_v2',
        ];
    }

    public static function get_wp_menus( \WP_REST_Request $request ) {
        $menus = wp_get_nav_menus();
        $out   = [];

        foreach ( $menus as $menu ) {
            $items = wp_get_nav_menu_items( $menu->term_id ) ?: [];

            $mapped = array_map( function ( $item ) {
                return [
                    'id'          => (int) $item->ID,
                    'title'       => (string) ( $item->title ?? '' ),
                    'type'        => (string) ( $item->type ?? '' ),
                    'type_label'  => (string) ( $item->type_label ?? '' ),
                    'url'         => (string) ( $item->url ?? '' ),
                    'target'      => (string) ( $item->target ?? '' ),
                    'description' => (string) ( $item->description ?? '' ),
                    'attr_title'  => (string) ( $item->attr_title ?? '' ),
                    'classes'     => is_array( $item->classes ?? null ) ? array_values( $item->classes ) : [],
                    'xfn'         => (string) ( $item->xfn ?? '' ),
                    'parent'      => (int) ( $item->menu_item_parent ?? 0 ),
                    'object'      => (string) ( $item->object ?? '' ),
                    'object_id'   => isset( $item->object_id ) ? (int) $item->object_id : 0,
                ];
            }, $items );

            $out[] = [
                'id'    => (int) $menu->term_id,
                'name'  => (string) $menu->name,
                'slug'  => (string) $menu->slug,
                'count' => (int) $menu->count,
                'items' => array_values( $mapped ),
            ];
        }

        return rest_ensure_response( [
            'success' => true,
            'items'   => array_values( $out ),
            'message' => 'WordPress menus with full items loaded',
        ] );
    }

    public static function update_wp_menu_item( \WP_REST_Request $request ) {

        if ( ! current_user_can( 'edit_theme_options' ) ) {
            return new \WP_REST_Response( [ 'message' => 'مجوز ندارید' ], 403 );
        }

        $item_id = (int) $request->get_param( 'menu_item_id' );

        $args = [
            'menu-item-title' => sanitize_text_field( $request->get_param( 'title' ) ),
            'menu-item-url'   => esc_url_raw( $request->get_param( 'url' ) ),
        ];

        $result = wp_update_nav_menu_item( 0, $item_id, $args );

        if ( is_wp_error( $result ) ) {
            return new \WP_REST_Response( [ 'success' => false, 'message' => $result->get_error_message() ], 500 );
        }

        return [ 'success' => true, 'message' => 'بروزرسانی انجام شد' ];
    }
}
