<?php
/**
 * Dashboard functionality for role-based access
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Define dashboard routes and their corresponding roles
 */
function etiuse_dashboard_routes() {
    return [
        'p/m' => ['Manager'],
        'p/a' => ['Accountant'],
        'p/l' => ['Lab'],
        'p/c' => ['Supervisor'],
        'p/s' => ['Specialist'],
        'p' => ['Client'],
        'p/sign-up' => ['subscriber']
    ];
}

/**
 * Add custom rewrite rules for dashboard URLs
 */
function etiuse_add_dashboard_rewrite_rules() {
    $routes = etiuse_dashboard_routes();
    
    foreach ($routes as $route => $roles) {
        add_rewrite_rule(
            '^' . $route . '/?$',
            'index.php?dashboard_route=' . urlencode($route),
            'top'
        );
    }
    
    // Add rewrite rule for single dental order page: /d/{dental_id}
    add_rewrite_rule(
        '^d/([^/]+)/?$',
        'index.php?dental_order_id=$matches[1]',
        'top'
    );
}
add_action('init', 'etiuse_add_dashboard_rewrite_rules');

/**
 * Add query vars for dashboard routes
 */
function etiuse_add_dashboard_query_vars($vars) {
    $vars[] = 'dashboard_route';
    $vars[] = 'dental_order_id';
    return $vars;
}
add_filter('query_vars', 'etiuse_add_dashboard_query_vars');

/**
 * Handle dashboard template loading
 */
function etiuse_dashboard_template($template) {
    // Check for single dental order page first
    $dental_order_id = get_query_var('dental_order_id');
    
    if ($dental_order_id) {
        // Check if user is logged in
        if (!is_user_logged_in()) {
            // Redirect non-logged-in users to login page
            wp_redirect(home_url('/login'));
            exit;
        }
        
        // Load single dental order template
        $template_path = get_template_directory() . '/templates/dental-order-single.php';
        if (file_exists($template_path)) {
            return $template_path;
        }
        
        // Fallback to 404 if template doesn't exist
        return $template;
    }
    
    // Handle dashboard routes
    $dashboard_route = get_query_var('dashboard_route');
    
    if (!$dashboard_route) {
        return $template;
    }
    
    // Check if user is logged in
    if (!is_user_logged_in()) {
        // Redirect non-logged-in users to login page
        wp_redirect(home_url('/login'));
        exit;
    }
    
    $routes = etiuse_dashboard_routes();
    
    if (!isset($routes[$dashboard_route])) {
        return get_template_directory() . '/templates/access-denied.php';
    }
    
    $allowed_roles = $routes[$dashboard_route];
    $current_user = wp_get_current_user();
    $user_roles = $current_user->roles;
    
    // Check if user has any of the allowed roles
    $has_access = false;
    foreach ($allowed_roles as $role) {
        if (in_array($role, $user_roles)) {
            $has_access = true;
            break;
        }
    }
    
    if (!$has_access) {
        return get_template_directory() . '/templates/access-denied.php';
    }
    
    // Load the appropriate dashboard template
    $template_file = 'dashboard-' . str_replace('/', '-', $dashboard_route) . '.php';
    $template_path = get_template_directory() . '/templates/' . $template_file;
    
    if (file_exists($template_path)) {
        return $template_path;
    }
    
    // Fallback to generic dashboard template
    return get_template_directory() . '/templates/dashboard-template.php';
}
add_filter('template_include', 'etiuse_dashboard_template');

/**
 * Flush rewrite rules on theme activation
 */
function etiuse_flush_rewrite_rules() {
    etiuse_add_dashboard_rewrite_rules();
    flush_rewrite_rules();
}
add_action('after_switch_theme', 'etiuse_flush_rewrite_rules');

/**
 * Get dashboard URL for current user
 */
function etiuse_get_user_dashboard_url() {
    if (!is_user_logged_in()) {
        return home_url('/login');
    }
    
    $current_user = wp_get_current_user();
    $user_roles = $current_user->roles;
    $routes = etiuse_dashboard_routes();
    
    foreach ($routes as $route => $allowed_roles) {
        foreach ($allowed_roles as $role) {
            if (in_array($role, $user_roles)) {
                return home_url('/' . $route);
            }
        }
    }
    
    // Default fallback
    return home_url('/p');
}

/**
 * Check if current user can access a specific dashboard route
 */
function etiuse_can_access_dashboard($route) {
    if (!is_user_logged_in()) {
        return false;
    }
    
    $routes = etiuse_dashboard_routes();
    
    if (!isset($routes[$route])) {
        return false;
    }
    
    $current_user = wp_get_current_user();
    $user_roles = $current_user->roles;
    $allowed_roles = $routes[$route];
    
    foreach ($allowed_roles as $role) {
        if (in_array($role, $user_roles)) {
            return true;
        }
    }
    
    return false;
}

/**
 * Get user role display name
 */
function etiuse_get_role_display_name($role) {
    $role_names = [
        'Manager' => 'مدیر',
        'Accountant' => 'حسابدار',
        'Lab' => 'آزمایشگاه',
        'Supervisor' => 'سرپرست',
        'Specialist' => 'متخصص',
        'Client' => 'مشتری',
        'subscriber' => 'عضو'
    ];
    
    return isset($role_names[$role]) ? $role_names[$role] : $role;
}

/**
 * Get current user's primary role
 */
function etiuse_get_current_user_role() {
    if (!is_user_logged_in()) {
        return false;
    }
    
    $current_user = wp_get_current_user();
    $user_roles = $current_user->roles;
    
    return !empty($user_roles) ? $user_roles[0] : false;
}
