<?php
namespace Atlasly\Core;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Permissions {
    
    public static function init() {
        add_action('init', [self::class, 'add_capabilities']);
    }
    
    public static function add_capabilities() {
        $admin = get_role('administrator');
        $editor = get_role('editor');
        
        $caps = [
            'atlasly_manage_types',
            'atlasly_edit_entries',
            'atlasly_delete_entries',
            'atlasly_view_dashboard'
        ];
        
        foreach($caps as $cap) {
            if($admin) $admin->add_cap($cap);
            if($editor && in_array($cap, ['atlasly_edit_entries', 'atlasly_view_dashboard'])) {
                $editor->add_cap($cap);
            }
        }
    }
    
    public static function can_manage_types($request = null) {
        return current_user_can('atlasly_manage_types');
    }
    
    public static function can_edit_entries($request = null) {
        if (current_user_can('atlasly_edit_entries')) {
            return true;
        }
        // Allow public read access for GET requests
        if ($request && $request->get_method() === 'GET') {
            return true;
        }
        return false;
    }

    public static function can_submit_entries($request) {
        if (current_user_can('atlasly_edit_entries')) {
            return true;
        }

        if (!$request) {
            return false;
        }

        $validation = \Atlasly\Core\ApiSecurity::validate_request(null, null, $request);
        return !is_wp_error($validation);
    }
    
    public static function can_delete_entries($request = null) {
        return current_user_can('atlasly_delete_entries');
    }
    
    public static function can_view_dashboard($request = null) {
        return current_user_can('atlasly_view_dashboard');
    }
}
