@extends('layouts.admin')

@section('title', 'Edit User: ' . $user->name)
@section('header_title', 'Edit User')

@section('content')
<div class="max-w-2xl mx-auto bg-white dark:bg-gray-800 p-6 lg:p-8 rounded-lg shadow-xl">
    <h1 class="text-2xl font-semibold text-gray-800 dark:text-gray-200 mb-6">Edit User: {{ $user->name }}</h1>

    <form action="{{ route('admin.users.update', $user) }}" method="POST">
        @csrf
        @method('PUT')

        <div class="mb-4">
            <label for="name" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Name</label>
            <input type="text" name="name" id="name" value="{{ old('name', $user->name) }}" required
                   class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200">
            @error('name') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
        </div>

        <div class="mb-4">
            <label for="email" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Email</label>
            <input type="email" name="email" id="email" value="{{ old('email', $user->email) }}" required
                   class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200">
            @error('email') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
        </div>

        <div class="mb-4">
            <label for="role" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Role</label>
            <select name="role" id="role" required {{-- This is for your simple 'role' column (super_admin, admin, user). --}} {{ Auth::user()->isSuperAdmin() ? '' : 'disabled' }}
                    class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200 {{ Auth::user()->isSuperAdmin() ? '' : 'bg-gray-100 dark:bg-gray-600 cursor-not-allowed' }}">
                @foreach($roles as $roleValue => $roleName)
                    <option value="{{ $roleValue }}" {{ old('role', $user->role) == $roleValue ? 'selected' : '' }}>
                        {{ $roleName }}
                    </option>
                @endforeach
            </select>
            @if(!Auth::user()->isSuperAdmin())
                <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Only Super Admins can change roles.</p>
            @endif
            @error('role') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
        </div>

        <!-- Spatie Roles Assignment (for Super Admins) -->
        @if(Auth::user()->isSuperAdmin() && isset($assignableRoles))
        <div class="mb-4">
            <label for="spatie_roles" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Detailed System Roles (Permissions)</label>
            <select name="spatie_roles[]" id="spatie_roles" multiple
                    class="mt-1 block w-full border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-300 focus:border-indigo-500 dark:focus:border-indigo-600 focus:ring-indigo-500 dark:focus:ring-indigo-600 rounded-md shadow-sm h-32">
                @foreach($assignableRoles as $spatieRole)
                    <option value="{{ $spatieRole->name }}"
                        {{ (is_array(old('spatie_roles')) && in_array($spatieRole->name, old('spatie_roles'))) || (!is_array(old('spatie_roles')) && $userRoles->contains($spatieRole->name)) ? 'selected' : '' }}>
                        {{ $spatieRole->name }}
                    </option>
                @endforeach
            </select>
            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Hold Ctrl (or Cmd on Mac) to select multiple roles. These grant specific feature permissions.</p>
            @error('spatie_roles') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
        </div>
        @endif

        @if(Auth::user()->isSuperAdmin() && $user->role === 'admin')
           <div class="mb-6 p-4 border border-yellow-400 dark:border-yellow-600 rounded-md bg-yellow-50 dark:bg-gray-700/50">
                <h4 class="text-md font-semibold text-yellow-800 dark:text-yellow-300 mb-2">Manage 'Admin' Role Module Permissions</h4>
                <p class="text-xs text-yellow-700 dark:text-yellow-400 mb-3">
                    <span class="font-bold">Warning:</span> Changes made below will affect permissions for <strong class="underline">all users</strong> who have the 'Admin' role, not just '{{ $user->name }}'.
                </p>
                <div class="flex items-center mb-3">
                    <input id="update_admin_role_modules_trigger" name="update_admin_role_modules" type="checkbox" value="1"
                           class="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600">
                    <label for="update_admin_role_modules_trigger" class="ml-2 block text-sm font-medium text-gray-700 dark:text-gray-300">
                        Confirm update of module permissions for the 'Admin' role?
                    </label>
                </div>
                <div class="space-y-2 max-h-60 overflow-y-auto border dark:border-gray-600 p-3 rounded-md bg-white dark:bg-gray-800">
                    @forelse($modules as $module)
                        <div class="flex items-center">
                            <input id="module_{{ $module->getLowerName() }}" name="modules[]" type="checkbox" value="{{ $module->getName() }}"
                                   {{ in_array($module->getName(), old('modules', $assignedModules)) ? 'checked' : '' }}
                                   class="h-4 w-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500 dark:bg-gray-700 dark:border-gray-600">
                            <label for="module_{{ $module->getLowerName() }}" class="ml-2 block text-sm text-gray-900 dark:text-gray-300">
                                {{ $module->getName() }} <span class="text-xs text-gray-500 dark:text-gray-400">({{ $module->get('description', 'No description') }})</span>
                            </label>
                        </div>
                    @empty
                        <p class="text-sm text-gray-500 dark:text-gray-400">No modules available to assign permissions.</p>
                    @endforelse
                </div>
            </div>
        @endif


        <div class="mb-6">
            <label for="password" class="block text-sm font-medium text-gray-700 dark:text-gray-300">New Password (optional)</label>
            <input type="password" name="password" id="password"
                   class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200">
            @error('password') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
        </div>

        <div class="mb-6">
            <label for="password_confirmation" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Confirm New Password</label>
            <input type="password" name="password_confirmation" id="password_confirmation"
                   class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200">
        </div>

        <div class="flex items-center justify-end mt-6">
            <a href="{{ route('admin.users.index') }}" class="text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 mr-4">Cancel</a>
            <button type="submit" class="inline-flex items-center px-4 py-2 bg-blue-600 hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition ease-in-out duration-150">
                Update User
            </button>
        </div>
    </form>

    @if(Auth::user()->isSuperAdmin())
    <div class="mt-12 pt-8 border-t border-gray-200 dark:border-gray-700">
        <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-6">Manage User Subscription</h2>

        @if($currentSubscription)
            <div class="mb-6 p-4 bg-blue-50 dark:bg-gray-700/50 rounded-lg border border-blue-300 dark:border-blue-600">
                <h4 class="font-semibold text-gray-700 dark:text-gray-200">Current Active Subscription:</h4>
                <p class="text-sm text-gray-600 dark:text-gray-300">
                    <strong>Plan:</strong> {{ $currentSubscription->plan->name ?? 'N/A' }} <br>
                    <strong>Status:</strong> <span class="capitalize">{{ $currentSubscription->status }}</span> <br>
                    <strong>Ends At:</strong> {{ $currentSubscription->ends_at ? $currentSubscription->ends_at->toFormattedDateString() : 'N/A' }} <br>
                    <strong>Gateway:</strong> <span class="capitalize">{{ str_replace('_', ' ', $currentSubscription->payment_gateway) }}</span>
                </p>
                <form action="{{ route('admin.users.subscription.remove', $user) }}" method="POST" class="mt-3" onsubmit="return confirm('Are you sure you want to cancel this user\'s current active subscription?');">
                    @csrf
                    <button type="submit" class="text-xs text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-300 underline">
                        Cancel This Subscription
                    </button>
                </form>
            </div>
        @else
            <p class="mb-4 text-sm text-gray-500 dark:text-gray-400">This user does not currently have an active subscription.</p>
        @endif

        <form action="{{ route('admin.users.subscription.update', $user) }}" method="POST">
            @csrf
            <div class="mb-4">
                <label for="subscription_plan_id" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Assign New Subscription Plan</label>
                <select name="subscription_plan_id" id="subscription_plan_id" required
                        class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200">
                    <option value="">Select a Plan</option>
                    @foreach($subscriptionPlans as $plan)
                        <option value="{{ $plan->id }}" {{ (old('subscription_plan_id') == $plan->id) ? 'selected' : '' }}>
                            {{ $plan->name }} ({{ number_format($plan->price, 2) }} {{ $plan->currency }} / {{ $plan->interval_count }} {{ Str::plural($plan->interval, $plan->interval_count) }})
                        </option>
                    @endforeach
                </select>
                @error('subscription_plan_id') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
            </div>

            {{-- Optional: Add fields for custom start/end dates if needed --}}
            {{--
            <div class="mb-4">
                <label for="custom_ends_at" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Custom End Date (Optional)</label>
                <input type="date" name="custom_ends_at" id="custom_ends_at" value="{{ old('custom_ends_at') }}"
                       class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200">
                @error('custom_ends_at') <span class="text-red-500 text-xs">{{ $message }}</span> @enderror
            </div>
            --}}

            <div class="flex items-center justify-start mt-4">
                <button type="submit" class="inline-flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 dark:bg-green-500 dark:hover:bg-green-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition ease-in-out duration-150">
                    Assign/Update Subscription
                </button>
            </div>
        </form>
    </div>
    @endif

    {{-- Credit Balance Management --}}
    @if(Auth::user()->isSuperAdmin() && function_exists('setting') && setting('credits_system_enabled', '0') == '1')
    <div class="mt-12 pt-8 border-t border-gray-200 dark:border-gray-700">
        <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-6">Credit Balance Management</h2>
        <div class="p-4 bg-slate-50 dark:bg-gray-700/50 rounded-lg border border-slate-300 dark:border-slate-600">
            <p class="mb-2 text-sm text-gray-700 dark:text-gray-300">Current Credit Balance: <span class="font-semibold">{{ $user->credit_balance ?? 0 }} credits</span></p>
            <form action="{{ route('admin.users.credits.adjust', $user->id) }}" method="POST" class="space-y-4">
                @csrf
                <div>
                    <label for="credit_adjustment_amount" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Adjustment Amount</label>
                    <input type="number" name="credit_adjustment_amount" id="credit_adjustment_amount" required
                           class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200"
                           placeholder="e.g., 100 to add, -50 to deduct">
                    @error('credit_adjustment_amount') <p class="mt-1 text-xs text-red-500">{{ $message }}</p> @enderror
                </div>
                <div>
                    <label for="credit_adjustment_description" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Reason/Description</label>
                    <input type="text" name="credit_adjustment_description" id="credit_adjustment_description" required
                           class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200"
                           placeholder="e.g., Manual award for support issue">
                    @error('credit_adjustment_description') <p class="mt-1 text-xs text-red-500">{{ $message }}</p> @enderror
                </div>
                <div class="flex justify-end">
                    <button type="submit" class="inline-flex items-center px-4 py-2 bg-green-600 hover:bg-green-700 dark:bg-green-500 dark:hover:bg-green-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition ease-in-out duration-150">
                        Adjust Credits
                    </button>
                </div>
            </form>
        </div>
    </div>
    @endif

    {{-- Wallet Balance Management --}}
    @if(Auth::user()->isSuperAdmin() && function_exists('setting') && setting('wallet_system_enabled', '0') == '1')
    <div class="mt-8 pt-8 border-t border-gray-200 dark:border-gray-700">
        <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-6">Wallet Balance Management</h2>
        <div class="p-4 bg-slate-50 dark:bg-gray-700/50 rounded-lg border border-slate-300 dark:border-slate-600">
            <p class="mb-2 text-sm text-gray-700 dark:text-gray-300">Current Wallet Balance: <span class="font-semibold">${{ number_format($user->wallet_balance ?? 0, 2) }}</span></p>
            <form action="{{ route('admin.users.wallet.adjust', $user->id) }}" method="POST" class="space-y-4">
                @csrf
                <div>
                    <label for="wallet_adjustment_amount" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Adjustment Amount ($)</label>
                    <input type="number" step="0.01" name="wallet_adjustment_amount" id="wallet_adjustment_amount" required
                           class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200"
                           placeholder="e.g., 10.50 to add, -5.00 to deduct">
                    @error('wallet_adjustment_amount') <p class="mt-1 text-xs text-red-500">{{ $message }}</p> @enderror
                </div>
                <div>
                    <label for="wallet_adjustment_description" class="block text-sm font-medium text-gray-700 dark:text-gray-300">Reason/Description</label>
                    <input type="text" name="wallet_adjustment_description" id="wallet_adjustment_description" required
                           class="mt-1 block w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 sm:text-sm dark:bg-gray-700 dark:text-gray-200"
                           placeholder="e.g., Refund for order #123">
                    @error('wallet_adjustment_description') <p class="mt-1 text-xs text-red-500">{{ $message }}</p> @enderror
                </div>
                <div class="flex justify-end">
                    <button type="submit" class="inline-flex items-center px-4 py-2 bg-purple-600 hover:bg-purple-700 dark:bg-purple-500 dark:hover:bg-purple-600 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-offset-2 dark:focus:ring-offset-gray-800 transition ease-in-out duration-150">
                        Adjust Wallet Balance
                    </button>
                </div>
            </form>
        </div>
    </div>
    @endif
</div>
@endsection
