<?php

namespace MovieEngine\Frontend\Users;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class UserAccess {

    public function __construct() {
        add_action('admin_init', [$this, 'redirect_non_admin_users']);
        add_action('after_setup_theme', [$this, 'hide_admin_bar']);
        add_filter('login_redirect', [$this, 'custom_login_redirect'], 10, 3);
    }

    public function redirect_non_admin_users() {

        if ((defined('DOING_AJAX') && DOING_AJAX) || (function_exists('wp_doing_ajax') && wp_doing_ajax())) {
            return;
        }

        if (isset($_SERVER['REQUEST_URI'])) {
            $uri = esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']));
            if (
                strpos($uri, 'admin-ajax.php') !== false ||
                strpos($uri, 'admin-post.php') !== false ||
                strpos($uri, 'async-upload.php') !== false ||
                strpos($uri, 'wp-login.php') !== false ||
                strpos($uri, 'upgrade.php') !== false ||
                strpos($uri, 'post.php') !== false ||
                strpos($uri, 'edit.php') !== false ||
                strpos($uri, 'admin.php') !== false ||
                strpos($uri, 'index.php') !== false
            ) {
                return;
            }
        }

        $general_settings = get_option('movie_engine_general_settings', []);
        $block_wp_admin = isset($general_settings['block_wp_admin']) ? (bool)$general_settings['block_wp_admin'] : true;

        if (!$block_wp_admin) {
            return;
        }

        if (!is_admin()) {
            return;
        }

        $user = wp_get_current_user();

        if (!$user || !$user->ID) {
            return;
        }

        if (current_user_can('manage_options') || current_user_can('edit_posts')) {
            return;
        }

        if (defined('MOVIE_ENGINE_REDIRECTING')) return;
        define('MOVIE_ENGINE_REDIRECTING', true);

        $redirect_url = self::get_login_redirect_url($user);

        if (isset($_SERVER['REQUEST_URI']) && strpos($redirect_url, esc_url_raw(wp_unslash($_SERVER['REQUEST_URI']))) !== false) {
            return;
        }

        nocache_headers();
        wp_safe_redirect($redirect_url);
        exit;
    }

    public function hide_admin_bar() {
        if (!current_user_can('administrator') && !current_user_can('editor')) {
            show_admin_bar(false);
        }
    }

    public function custom_login_redirect($redirect_to, $request, $user) {
        return self::get_login_redirect_url($user, $redirect_to);
    }

    public static function get_login_redirect_url($user = null, $fallback = '') {
        if (!$user) {
            $user = wp_get_current_user();
        }

        if (is_wp_error($user) || !($user instanceof \WP_User)) {
            return $fallback;
        }

        if (user_can($user, 'manage_options') || user_can($user, 'edit_posts')) {
            if (!empty($fallback) && strpos($fallback, 'wp-admin') !== false) {
                return $fallback;
            }
            return esc_url(admin_url());
        }

        if (!empty($fallback) && strpos($fallback, 'wp-admin') === false) {
            $fallback = wp_validate_redirect($fallback, home_url('/'));
            return $fallback;
        }

        $general_settings = get_option('movie_engine_general_settings', []);
        $redirect_type = isset($general_settings['login_redirect']) ? $general_settings['login_redirect'] : 'dashboard';

        switch ($redirect_type) {
            case 'home':
                return home_url('/');
            case 'previous':
                return !empty($fallback) ? $fallback : home_url('/');
            case 'dashboard':
            default:
                $design_settings = get_option('movie_engine_design_settings', []);
                $dashboard_id = isset($design_settings['dashboard_page']) ? intval($design_settings['dashboard_page']) : 0;
                return $dashboard_id ? get_permalink($dashboard_id) : home_url('/dashboard/');
        }
    }
}
