#!/bin/bash

# Script to hide Create, Edit, and Delete actions for Super Admin users
# Usage: bash hide_admin_actions.sh /path/to/laravel/project

PROJECT_PATH="${1:-.}"

echo "=========================================="
echo "Hide Admin Actions Script"
echo "=========================================="
echo "Project Path: $PROJECT_PATH"
echo ""

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Counter
count_list=0
count_table=0

echo -e "${BLUE}Step 1: Updating access rules helper${NC}"
echo "=========================================="

HELPER_FILE="$PROJECT_PATH/app/Helpers/__removed__.php"

if [ -f "$HELPER_FILE" ]; then
    # Backup original file
    cp "$HELPER_FILE" "$HELPER_FILE.backup"
    echo -e "${GREEN}✓ Created backup: helper.backup${NC}"
    
    # Update canViewAny method
    sed -i.tmp '/public static function canViewAny/,/return true;/c\
    /**\
     * تحقق من إمكانية عرض قائمة السجلات\
     * Super Admin يمكنه فقط عرض: Tenants, Users, Roles\
     */\
    public static function canViewAny(string $resourceClass): bool\
    {\
        $user = auth()->user();\
\
        if (!$user) {\
            return false;\
        }\
\
        // Tenant Owner له صلاحيات كاملة\
        if ($user->is_tenant_owner) {\
            return true;\
        }\
\
        // Super Admin يمكنه فقط عرض هذه الـ Resources\
        if ($user->is_system_admin) {\
            $allowedResources = [\
                '\''TenantResource'\'',\
                '\''UserResource'\'',\
                '\''RoleResource'\'',\
                '\''ActivityResource'\'', // للـ Activity Log\
            ];\
\
            $resourceName = class_basename($resourceClass);\
            return in_array($resourceName, $allowedResources);\
        }\
\
        return true;\
    }' "$HELPER_FILE"
    
    echo -e "${GREEN}✓ Updated access helper${NC}"
else
    echo -e "${YELLOW}⚠ Access helper file not found${NC}"
fi

echo ""
echo -e "${BLUE}Step 2: Updating List Pages${NC}"
echo "=========================================="

# Find all List*.php files in Resources
find "$PROJECT_PATH/app/Filament/Resources" -type f -name "List*.php" | while read file; do
    # Skip Users and Tenants
    if [[ "$file" == *"ListUsers.php"* ]] || [[ "$file" == *"ListTenants.php"* ]]; then
        continue
    fi
    
    # Check if file contains getHeaderActions
    if grep -q "protected function getHeaderActions" "$file"; then
        # Backup
        cp "$file" "$file.backup"
        
        # Check if already has the condition
        if ! grep -q "is_system_admin && !.*is_tenant_owner" "$file"; then
            # Add condition before return statement
            perl -i -pe 's/(protected function getHeaderActions\(\): array\s*\{)(\s*return \[)/$1\n        \/\/ إخفاء زر الإضافة للـ Super Admin (يظهر فقط للـ Tenant Owner)\n        if (auth()->user()?->is_system_admin && !auth()->user()?->is_tenant_owner) {\n            return [];\n        }\n$2/g' "$file"
            
            echo -e "${GREEN}✓ Updated: $(basename $file)${NC}"
            ((count_list++))
        fi
    fi
done

echo -e "${GREEN}Total List Pages Updated: $count_list${NC}"

echo ""
echo -e "${BLUE}Step 3: Updating Table Files${NC}"
echo "=========================================="

# Find all *Table.php files in Resources
find "$PROJECT_PATH/app/Filament/Resources" -type f -name "*Table.php" | while read file; do
    # Skip Users and Tenants Tables
    if [[ "$file" == *"UsersTable.php"* ]] || [[ "$file" == *"TenantsTable.php"* ]]; then
        continue
    fi
    
    # Check if file contains EditAction or DeleteAction
    if grep -q "EditAction\|DeleteAction" "$file"; then
        # Backup
        cp "$file" "$file.backup"
        
        # Check if already has visible condition
        if ! grep -q "->visible(fn() => !auth" "$file"; then
            # Add visible to EditAction
            sed -i.tmp 's/EditAction::make(),/EditAction::make()\n                    ->visible(fn() => !auth()->user()?->is_system_admin || auth()->user()?->is_tenant_owner),/g' "$file"
            
            # Add visible to DeleteAction
            sed -i.tmp 's/DeleteAction::make(),/DeleteAction::make()\n                    ->visible(fn() => !auth()->user()?->is_system_admin || auth()->user()?->is_tenant_owner),/g' "$file"
            
            # Clean up .tmp files
            rm -f "$file.tmp"
            
            echo -e "${GREEN}✓ Updated: $(basename $file)${NC}"
            ((count_table++))
        fi
    fi
done

echo -e "${GREEN}Total Table Files Updated: $count_table${NC}"

echo ""
echo -e "${BLUE}Step 4: Clearing Cache${NC}"
echo "=========================================="

cd "$PROJECT_PATH"
php artisan optimize:clear
php artisan filament:optimize

echo ""
echo -e "${GREEN}=========================================="
echo "✓ Script Completed Successfully!"
echo "=========================================="
echo "Summary:"
echo "  - List Pages Updated: $count_list"
echo "  - Table Files Updated: $count_table"
echo "  - Backup files created with .backup extension"
echo ""
echo "To restore backups, run:"
echo "  find . -name '*.backup' -exec sh -c 'mv \"\$1\" \"\${1%.backup}\"' _ {} \;"
echo "==========================================${NC}"
