@extends('layouts.portal')

@section('title', 'Will Management')
@section('page_title', 'Will Management')
@section('page_subtitle', 'Manage client wills')

@section('sidebar')
    @include('agent.partials.sidebar', ['active' => 'wills'])
@endsection

{{-- Helper function to safely count values --}}
@php
if (!function_exists('safeCount')) {
    function safeCount($value) {
        if (is_array($value) || ($value instanceof Countable)) {
            return count($value);
        }
        return 0;
    }
}
@endphp

@section('content')
<div class="max-w-7xl mx-auto">
    <div class="bg-white rounded-xl shadow-lg p-6">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-3xl font-bold text-gray-900">Will Management</h1>
            <div class="flex space-x-2">
                <a href="{{ route('agent.clients') }}" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg font-medium inline-flex items-center">
                    <i class="fas fa-plus mr-2" style="color: white !important;"></i>
                    Create New Will
                </a>
                <a href="{{ route('agent.clients') }}" class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg font-medium inline-flex items-center">
                    <i class="fas fa-users mr-2"></i>
                    Manage Clients
                </a>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl p-6 text-white">
                <div class="flex items-center">
                    <div class="w-12 h-12 bg-blue-800 rounded-full flex items-center justify-center">
                        <i class="fas fa-file-contract text-white text-2xl" style="color: white !important;"></i>
                    </div>
                    <div class="ml-4">
                        <h3 class="text-2xl font-bold">{{ $stats['total'] }}</h3>
                        <p class="text-blue-100">Total Wills</p>
                    </div>
                </div>
            </div>

            <div class="bg-gradient-to-br from-green-500 to-green-600 rounded-xl p-6 text-white">
                <div class="flex items-center">
                    <div class="w-12 h-12 bg-green-800 rounded-full flex items-center justify-center">
                        <i class="fas fa-clock text-2xl"></i>
                    </div>
                    <div class="ml-4">
                        <h3 class="text-2xl font-bold">{{ $stats['under_review'] }}</h3>
                        <p class="text-green-100">Pending Review</p>
                    </div>
                </div>
            </div>

            <div class="bg-gradient-to-br from-yellow-500 to-yellow-600 rounded-xl p-6 text-white">
                <div class="flex items-center">
                    <div class="w-12 h-12 bg-yellow-800 rounded-full flex items-center justify-center">
                        <i class="fas fa-edit text-2xl"></i>
                    </div>
                    <div class="ml-4">
                        <h3 class="text-2xl font-bold">{{ $stats['drafting'] }}</h3>
                        <p class="text-yellow-100">Drafting</p>
                    </div>
                </div>
            </div>

            <div class="bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl p-6 text-white">
                <div class="flex items-center">
                    <div class="w-12 h-12 bg-purple-800 rounded-full flex items-center justify-center">
                        <i class="fas fa-check text-2xl"></i>
                    </div>
                    <div class="ml-4">
                        <h3 class="text-2xl font-bold">{{ $stats['stored'] }}</h3>
                        <p class="text-purple-100">Completed</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Wills Table -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-900">All Wills</h3>
            </div>
            
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Will ID</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Client</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Will Type</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Created</th>
                            <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        @forelse ($wills as $will)
                            @php
                                // Check if this is a trust or will based on model class, table, or _source_table attribute
                                // IMPORTANT: Only mark as trust if it's actually from the Trust model/table
                                $isItATrust = (get_class($will) === \App\Models\Trust::class 
                                            || $will->getTable() === 'trusts'
                                            || ($will->_source_table ?? '') === 'trusts');
                                
                                // DEBUG: Log model info for debugging
                                \Log::info("Will #{$will->id}: Model=" . get_class($will) . ", Table=" . $will->getTable() . ", SourceTable=" . ($will->_source_table ?? 'N/A') . ", WillType=" . ($will->will_type ?? 'N/A') . ", IsItATrust=" . ($isItATrust ? 'YES' : 'NO') . ", Status=" . $will->status);
                                
                                
                                // For trusts, calculate progress based on completed sections
                                if ($isItATrust) {
                                    $willType = 'Trust';
                                    
                                    // Check trust sections completion
                                    $hasTrustCreator = !empty($will->trust_creator) || !empty($will->trust_creator_details);
                                    $hasTrustDetails = !empty($will->trust_name) && !empty($will->trust_type) && !empty($will->trust_purpose);
                                    $hasAssets = \DB::table('trust_assets')->where('trust_id', $will->id)->exists();
                                    $hasBeneficiaries = \DB::table('trust_beneficiaries')->where('trust_id', $will->id)->exists();
                                    $hasCaretakers = \DB::table('trust_caretakers')->where('trust_id', $will->id)->exists();
                                    $hasAllowances = \DB::table('trust_allowances')->where('trust_id', $will->id)->exists();
                                    $hasGifts = \DB::table('trust_gifts')->where('trust_id', $will->id)->exists();
                                    
                                    // Final Setup is complete if any of the final setup related tables have data
                                    // (admin allowances, guardian allowances, or donations)
                                    $hasAdminAllowances = \DB::table('trust_administrator_allowances')->where('trust_id', $will->id)->exists();
                                    $hasGuardianAllowances = \DB::table('trust_guardian_allowances')->where('trust_id', $will->id)->exists();
                                    $hasDonations = \DB::table('trust_donations')->where('trust_id', $will->id)->exists();
                                    
                                    // Final setup is considered complete if ANY of these exist, OR if trust is already approved/stored
                                    $hasFinalSetup = $hasAdminAllowances || $hasGuardianAllowances || $hasDonations 
                                                   || in_array($will->status, ['stored', 'approved', 'signed', 'completed']);
                                    
                                    // Count completed sections
                                    $completedSections = 0;
                                    if ($hasTrustCreator) $completedSections++;
                                    if ($hasTrustDetails) $completedSections++;
                                    if ($hasAssets) $completedSections++;
                                    if ($hasBeneficiaries) $completedSections++;
                                    if ($hasCaretakers) $completedSections++;
                                    if ($hasAllowances) $completedSections++;
                                    if ($hasGifts) $completedSections++;
                                    if ($hasFinalSetup) $completedSections++;
                                    
                                    $totalSections = 8; // Trust has 8 main sections
                                    $progressPercentage = ($totalSections > 0) ? ($completedSections / $totalSections) * 100 : 0;
                                    
                                    // Determine resume route - redirect to FIRST incomplete step
                                    if (!$hasTrustCreator || !$hasTrustDetails) {
                                        $resumeRoute = route('agent.trusts.create', ['client' => $will->client_id]);
                                    } elseif (!$hasAssets) {
                                        $resumeRoute = route('agent.trusts.assets.index', $will->id);
                                    } elseif (!$hasBeneficiaries) {
                                        $resumeRoute = route('agent.trusts.beneficiaries.index', $will->id);
                                    } elseif (!$hasCaretakers) {
                                        $resumeRoute = route('agent.trusts.caretakers.index', $will->id);
                                    } elseif (!$hasAllowances) {
                                        $resumeRoute = route('agent.trusts.allowances.index', $will->id);
                                    } elseif (!$hasGifts) {
                                        $resumeRoute = route('agent.trusts.gifts.index', $will->id);
                                    } elseif (!$hasFinalSetup) {
                                        $resumeRoute = route('agent.trusts.final-setup.index', $will->id);
                                    } else {
                                        // All sections complete, go to show/review page
                                        $resumeRoute = route('agent.trusts.show', $will);
                                    }
                                } else {
                                    // Parse instructions - handle both string (JSON) and array formats
                                    $instructions = [];
                                if ($will->instructions) {
                                    if (is_string($will->instructions)) {
                                        $instructions = json_decode($will->instructions, true) ?? [];
                                    } else if (is_array($will->instructions)) {
                                        $instructions = $will->instructions;
                                    }
                                }
                                
                                // Testator sections
                                $testatorDetails = is_array($will->testator_details) 
                                    ? $will->testator_details 
                                    : (json_decode($will->testator_details, true) ?? []);
                                $hasPrimary = !empty($testatorDetails['primary']['full_name']);
                                $hasSecondary = !empty($testatorDetails['secondary']['full_name']);
                                $hasExecutor = !empty($testatorDetails['executor']['full_name']);
                                $hasGuardian = !empty($testatorDetails['guardian']['full_name']);
                                
                                // Other sections - check database tables directly for accurate count
                                $hasBeneficiaries = \DB::table('will_beneficiaries')->where('will_id', $will->id)->exists()
                                    || (!empty($will->beneficiaries) && safeCount($will->beneficiaries) > 0);
                                // Check assets in multiple places: will_assets table, asset_allocations field, or instructions JSON
                                $assetAllocations = is_array($will->asset_allocations) 
                                    ? $will->asset_allocations 
                                    : (json_decode($will->asset_allocations, true) ?? []);
                                $instructionsAssets = is_array($instructions['assets'] ?? null) 
                                    ? $instructions['assets'] 
                                    : (json_decode($instructions['assets'] ?? '[]', true) ?? []);
                                $hasAssets = \DB::table('will_assets')->where('will_id', $will->id)->exists() 
                                    || (!empty($assetAllocations) && safeCount($assetAllocations) > 0)
                                    || (!empty($instructionsAssets) && safeCount($instructionsAssets) > 0);
                                $hasLiabilities = \DB::table('will_liabilities')->where('will_id', $will->id)->exists();
                                // Check existing will - marked complete if either:
                                // 1. User explicitly said "no" to existing will
                                // 2. User said "yes" AND provided the details
                                $hasExistingWill = (!empty($instructions['has_existing_will']) && $instructions['has_existing_will'] === 'no') 
                                    || (!empty($instructions['has_existing_will']) && $instructions['has_existing_will'] === 'yes' && !empty($instructions['existing_will']));
                                // Check database relationships for gifts, donations, witnesses
                                $instructionsGifts = is_array($instructions['gifts'] ?? null) 
                                    ? $instructions['gifts'] 
                                    : (json_decode($instructions['gifts'] ?? '[]', true) ?? []);
                                $instructionsDonations = is_array($instructions['donations'] ?? null) 
                                    ? $instructions['donations'] 
                                    : (json_decode($instructions['donations'] ?? '[]', true) ?? []);
                                $instructionsWitnesses = is_array($instructions['witnesses'] ?? null) 
                                    ? $instructions['witnesses'] 
                                    : (json_decode($instructions['witnesses'] ?? '[]', true) ?? []);
                                $instructionsAllowances = is_array($instructions['allowances'] ?? null) 
                                    ? $instructions['allowances'] 
                                    : (json_decode($instructions['allowances'] ?? '[]', true) ?? []);
                                $instructionsTrustees = is_array($instructions['trustees'] ?? null) 
                                    ? $instructions['trustees'] 
                                    : (json_decode($instructions['trustees'] ?? '[]', true) ?? []);
                                
                                $hasGifts = \DB::table('will_gifts')->where('will_id', $will->id)->exists()
                                    || (!empty($instructionsGifts) && safeCount($instructionsGifts) > 0)
                                    || (!empty($instructions['gifts_section_completed']));
                                $hasDonations = \DB::table('will_donations')->where('will_id', $will->id)->exists()
                                    || (!empty($instructionsDonations) && safeCount($instructionsDonations) > 0)
                                    || (!empty($instructions['donations_section_completed']));
                                $hasWitnesses = \DB::table('will_witnesses')->where('will_id', $will->id)->exists()
                                    || (!empty($instructionsWitnesses) && safeCount($instructionsWitnesses) > 0);
                                $hasAllowances = (!empty($instructionsAllowances) && safeCount($instructionsAllowances) > 0)
                                    || (!empty($instructions['allowances_section_completed']));
                                $hasTrustees = (!empty($instructionsTrustees) && safeCount($instructionsTrustees) > 0)
                                    || (!empty($instructions['trustees_section_completed']));
                                
                                // DEBUG: Log what sections are complete for this will
                                if ($will->id == 207 || $will->id == 208) {
                                    \Log::info("=== DEBUG Will #{$will->id} Sections ===");
                                    \Log::info("hasPrimary: " . ($hasPrimary ? 'YES' : 'NO'));
                                    \Log::info("hasBeneficiaries: " . ($hasBeneficiaries ? 'YES' : 'NO'));
                                    \Log::info("hasAssets: " . ($hasAssets ? 'YES' : 'NO'));
                                    \Log::info("hasLiabilities: " . ($hasLiabilities ? 'YES' : 'NO'));
                                    \Log::info("hasExistingWill: " . ($hasExistingWill ? 'YES' : 'NO'));
                                    \Log::info("hasAllowances: " . ($hasAllowances ? 'YES' : 'NO'));
                                    \Log::info("hasGifts: " . ($hasGifts ? 'YES' : 'NO'));
                                    \Log::info("hasDonations: " . ($hasDonations ? 'YES' : 'NO'));
                                    \Log::info("hasTrustees: " . ($hasTrustees ? 'YES' : 'NO'));
                                    \Log::info("hasWitnesses: " . ($hasWitnesses ? 'YES' : 'NO'));
                                    \Log::info("Instructions type: " . gettype($will->instructions));
                                    \Log::info("Instructions value: " . json_encode($instructions));
                                    \Log::info("Testator Details: ", $testatorDetails);
                                    
                                    // Check database tables
                                    \Log::info("DB Check - Beneficiaries count: " . \DB::table('will_beneficiaries')->where('will_id', $will->id)->count());
                                    \Log::info("DB Check - Assets count: " . \DB::table('will_assets')->where('will_id', $will->id)->count());
                                    \Log::info("DB Check - Liabilities count: " . \DB::table('will_liabilities')->where('will_id', $will->id)->count());
                                    \Log::info("DB Check - Gifts count: " . \DB::table('will_gifts')->where('will_id', $will->id)->count());
                                    \Log::info("DB Check - Donations count: " . \DB::table('will_donations')->where('will_id', $will->id)->count());
                                    \Log::info("DB Check - Witnesses count: " . \DB::table('will_witnesses')->where('will_id', $will->id)->count());
                                }
                                
                                // Calculate completed sections count
                                $completedSections = 0;
                                if ($hasPrimary) $completedSections++;
                                if ($hasBeneficiaries) $completedSections++;
                                if ($hasAssets) $completedSections++;
                                if ($hasLiabilities) $completedSections++;
                                if ($hasExistingWill) $completedSections++;
                                if ($hasAllowances) $completedSections++;
                                if ($hasGifts) $completedSections++;
                                if ($hasDonations) $completedSections++;
                                // Only count trustees for trust wills
                                if ($will->will_type === 'trust' && $hasTrustees) $completedSections++;
                                if ($hasWitnesses) $completedSections++;
                                
                                // Total sections - 9 for individual/joint, 10 for trust wills
                                $totalSections = ($will->will_type === 'trust') ? 10 : 9;
                                
                                // Determine resume route - redirect to FIRST incomplete step
                                $resumeRoute = route('agent.wills.testator', $will);
                                
                                if (!$hasPrimary) {
                                    $resumeRoute = route('agent.wills.testator', $will);
                                } elseif (!$hasBeneficiaries) {
                                    $resumeRoute = route('agent.wills.beneficiaries', $will);
                                } elseif (!$hasAssets) {
                                    $resumeRoute = route('agent.wills.assets', $will);
                                } elseif (!$hasLiabilities) {
                                    $resumeRoute = route('agent.wills.liabilities', $will);
                                } elseif (!$hasExistingWill) {
                                    $resumeRoute = route('agent.wills.existing-will', $will);
                                } elseif (!$hasAllowances) {
                                    $resumeRoute = route('agent.wills.allowances', $will);
                                } elseif (!$hasGifts) {
                                    $resumeRoute = route('agent.wills.gifts', $will);
                                } elseif (!$hasDonations) {
                                    $resumeRoute = route('agent.wills.donations', $will);
                                } elseif ($will->will_type === 'trust' && !$hasTrustees) {
                                    $resumeRoute = route('agent.wills.trustees', $will);
                                } elseif (!$hasWitnesses) {
                                    $resumeRoute = route('agent.wills.witnesses', $will);
                                }
                                
                                // Override if will is already submitted/completed
                                if (in_array($will->status, ['stored', 'under_review', 'approved', 'signed', 'completed'])) {
                                    $completedSections = $totalSections;
                                }
                                
                                $progressPercentage = ($totalSections > 0) ? ($completedSections / $totalSections) * 100 : 0;
                                }
                            @endphp
                            <tr class="hover:bg-gray-50 @if($completedSections == $totalSections) cursor-pointer" onclick="toggleWillPreview({{ $will->id }})" @endif">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
                                        #{{ $will->id }}
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="flex items-center">
                                        <div class="w-8 h-8 bg-[#772B10]/10 rounded-full flex items-center justify-center">
                                            <span class="text-[#772B10] text-sm font-medium">{{ $will->client ? strtoupper(substr($will->client->full_name, 0, 1)) : '?' }}</span>
                                        </div>
                                        <div class="ml-3">
                                            <p class="font-medium text-gray-900">{{ $will->client ? $will->client->full_name : 'Unknown Client' }}</p>
                                            <p class="text-sm text-gray-500">{{ $will->client ? $will->client->email : 'No email' }}</p>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-[#772B10]/10 text-[#772B10]">
                                        @if($isItATrust)
                                            {{ ucfirst($will->trust_type ?? 'Trust') }}
                                        @else
                                            {{ ucfirst($will->will_type) }}
                                        @endif
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium
                                        @if($will->status == 'drafting') bg-yellow-100 text-yellow-800
                                        @elseif($will->status == 'under_review') bg-orange-100 text-orange-800
                                        @elseif($will->status == 'stored') bg-green-100 text-green-800
                                        @elseif($will->status == 'corrections_requested') bg-red-100 text-red-800 border-2 border-red-300
                                        @elseif($will->status == 'completed') bg-blue-100 text-blue-800
                                        @else bg-gray-100 text-gray-800
                                        @endif">
                                            @if($will->status == 'corrections_requested')
                                                <i class="fas fa-exclamation-triangle mr-1"></i>
                                                Corrections Requested
                                            @else
                                                {{ ucfirst(str_replace('_', ' ', $will->status)) }}
                                            @endif
                                    </span>
                                    @if($will->status == 'corrections_requested' && $will->corrections_remarks)
                                        <div class="mt-1 text-xs text-red-600 max-w-xs truncate" title="{{ $will->corrections_remarks }}">
                                            <i class="fas fa-comment mr-1"></i>
                                            {{ Str::limit($will->corrections_remarks, 50) }}
                                        </div>
                                    @endif
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                    {{ $will->created_at->format('M d, Y') }}
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <div class="space-y-2">
                                        <!-- Progress Bar -->
                                        <div class="flex items-center space-x-3">
                                            <div class="flex-1 bg-gray-200 rounded-full h-3 relative overflow-hidden">
                                                <div class="bg-gradient-to-r from-[#772B10] to-[#8B3D15] h-3 rounded-full transition-all duration-500 shadow-sm relative"
                                                     style="width: {{ $progressPercentage }}%">
                                                    <div class="absolute inset-0 flex items-center justify-center">
                                                        <span class="text-xs font-bold text-white bg-black bg-opacity-20 px-2 py-0.5 rounded-full">
                                                            {{ round($progressPercentage) }}%
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="flex items-center space-x-2">
                                                <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-bold
                                                    @if($completedSections == $totalSections) 
                                                        bg-green-100 text-green-800 border-2 border-green-300
                                                    @elseif($progressPercentage >= 50)
                                                        bg-blue-100 text-blue-800 border-2 border-blue-300
                                                    @elseif($progressPercentage >= 25)
                                                        bg-yellow-100 text-yellow-800 border-2 border-yellow-300
                                                    @else
                                                        bg-red-100 text-red-800 border-2 border-red-300
                                                    @endif">
                                                    <i class="fas fa-chart-pie mr-1"></i>
                                                    {{ $completedSections }}/{{ $totalSections }}
                                                </span>
                                                @if($completedSections == $totalSections)
                                                    <span class="inline-flex items-center px-2 py-1 rounded-full bg-green-500 text-white">
                                                        <i class="fas fa-check-circle mr-1"></i>
                                                        Complete
                                                    </span>
                                                @endif
                                            </div>
                                        </div>

                                        <!-- Action Button -->
                                        @if($isItATrust)
                                            {{-- Trust-specific actions --}}
                                            @if(in_array($will->status, ['stored', 'under_review', 'approved', 'signed', 'completed']))
                                                {{-- Trust already approved/stored - show view and edit buttons --}}
                                                <div class="mt-2 space-y-2">
                                                    <div class="space-y-2">
                                                        <div class="flex flex-wrap gap-2">
                                                            <a href="{{ route('agent.documents.view', $will->id) }}" class="inline-flex items-center px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                                                                <i class="fas fa-eye mr-2"></i>
                                                                View Trust (v{{ $will->version ?? 1 }})
                                                            </a>
                                                            <a href="{{ route('agent.trusts.create', ['client' => $will->client_id, 'trust' => $will->id]) }}" class="inline-flex items-center px-3 py-1.5 bg-[#772B10] hover:bg-[#8B3D15] text-white rounded-lg text-sm font-medium transition-colors">
                                                                <i class="fas fa-edit mr-2"></i>
                                                                Edit Trust
                                                            </a>
                                                        </div>
                                                    </div>
                                                    <div class="text-xs text-gray-500">
                                                        Current Version: v{{ $will->version ?? 1 }} | 
                                                        Last Updated: {{ $will->updated_at->format('M d, Y') }}
                                                    </div>
                                                </div>
                                            @else
                                                {{-- Trust in draft/drafting status --}}
                                                <div class="mt-3">
                                                    @if($completedSections == 0)
                                                        {{-- Trust not started yet --}}
                                                        <a href="{{ route('agent.trusts.create', ['client' => $will->client_id]) }}" class="inline-flex items-center px-4 py-2.5 bg-gradient-to-r from-purple-500 to-purple-600 text-white rounded-lg text-sm font-semibold hover:from-purple-600 hover:to-purple-700 transition-all duration-300 shadow-lg hover:shadow-xl transform hover:scale-105 w-full justify-center">
                                                            <i class="fas fa-rocket mr-2"></i>
                                                            Start with Trust Creator Details →
                                                        </a>
                                                    @elseif($completedSections < $totalSections)
                                                        {{-- Trust in progress --}}
                                                        <a href="{{ $resumeRoute }}" class="inline-flex items-center px-4 py-2.5 bg-gradient-to-r from-orange-500 to-orange-600 text-white rounded-lg text-sm font-semibold hover:from-orange-600 hover:to-orange-700 transition-all duration-300 shadow-lg hover:shadow-xl transform hover:scale-105">
                                                            <i class="fas fa-play-circle mr-2"></i>
                                                            Continue Trust Creation
                                                        </a>
                                                    @else
                                                        {{-- Trust completed but not submitted yet --}}
                                                        <button onclick="submitForReview({{ $will->id }})" class="inline-flex items-center px-4 py-2.5 bg-gradient-to-r from-[#772B10] to-[#8B3D15] text-white rounded-lg text-sm font-semibold hover:from-[#8B3D15] hover:to-[#9F4F1A] transition-all duration-300 shadow-lg hover:shadow-xl transform hover:scale-105">
                                                            <i class="fas fa-paper-plane mr-2"></i>
                                                            Submit for Review
                                                        </button>
                                                    @endif
                                                </div>
                                            @endif
                                        @elseif(in_array($will->status, ['drafting', 'draft']))
                                            @if($completedSections == 0)
                                                <div class="mt-3 space-y-2">
                                                    <a href="{{ route('agent.wills.testator', $will) }}" class="inline-flex items-center px-4 py-2.5 bg-gradient-to-r from-green-500 to-green-600 text-white rounded-lg text-sm font-semibold hover:from-green-600 hover:to-green-700 transition-all duration-300 shadow-lg hover:shadow-xl transform hover:scale-105 w-full justify-center">
                                                        <i class="fas fa-rocket mr-2"></i>
                                                        Start with Testator Information →
                                                    </a>
                                                </div>
                                            @elseif($completedSections < $totalSections)
                                                <div class="mt-3">
                                                    <a href="{{ $resumeRoute }}" class="inline-flex items-center px-4 py-2.5 bg-gradient-to-r from-orange-500 to-orange-600 text-white rounded-lg text-sm font-semibold hover:from-orange-600 hover:to-orange-700 transition-all duration-300 shadow-lg hover:shadow-xl transform hover:scale-105">
                                                        <i class="fas fa-play-circle mr-2"></i>
                                                        Continue Will Creation
                                                    </a>
                                                </div>
                                            @else
                                                <div class="mt-3">
                                                    <button onclick="submitForReview({{ $will->id }})" class="inline-flex items-center px-4 py-2.5 bg-gradient-to-r from-[#772B10] to-[#8B3D15] text-white rounded-lg text-sm font-semibold hover:from-[#8B3D15] hover:to-[#9F4F1A] transition-all duration-300 shadow-lg hover:shadow-xl transform hover:scale-105">
                                                        <i class="fas fa-paper-plane mr-2"></i>
                                                        Submit for Review
                                                    </button>
                                                </div>
                                            @endif
                                        @elseif($will->status == 'corrections_requested')
                                            <div class="mt-2 space-y-2">
                                                <div class="bg-red-50 border border-red-200 rounded-lg p-3">
                                                    <div class="flex items-center mb-2">
                                                        <i class="fas fa-exclamation-triangle text-red-600 mr-2"></i>
                                                        <span class="text-sm font-semibold text-red-800">Corrections Required</span>
                                                    </div>
                                                    @if($will->corrections_remarks)
                                                        <p class="text-xs text-red-700 mb-3">{{ $will->corrections_remarks }}</p>
                                                    @endif
                                                    <div class="flex space-x-2">
                                                        <a href="{{ route('agent.wills.testator', $will) }}" class="inline-flex items-center px-3 py-1.5 bg-red-600 hover:bg-red-700 text-white rounded-lg text-sm font-medium transition-colors">
                                                            <i class="fas fa-edit mr-2"></i>
                                                            Edit Corrections
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                        @elseif(in_array($will->status, ['stored', 'under_review', 'approved', 'signed', 'completed']))
                                            <div class="mt-2 space-y-2">
                                                <div class="space-y-2">
                                                    <div class="flex flex-wrap gap-2">
                                                        <a href="{{ route('agent.documents.view', $will->id) }}" class="inline-flex items-center px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-sm font-medium transition-colors">
                                                            <i class="fas fa-eye mr-2"></i>
                                                            View Will (v{{ $will->version ?? 1 }})
                                                        </a>
                                                        <a href="{{ route('agent.wills.testator', $will) }}" class="inline-flex items-center px-3 py-1.5 bg-[#772B10] hover:bg-[#8B3D15] text-white rounded-lg text-sm font-medium transition-colors">
                                                            <i class="fas fa-edit mr-2"></i>
                                                            Edit Will
                                                        </a>
                                                    </div>
                                                </div>
                                                <div class="text-xs text-gray-500">
                                                    Current Version: v{{ $will->version ?? 1 }} | 
                                                    Last Updated: {{ $will->updated_at->format('M d, Y') }}
                                                </div>
                                            </div>
                                        @else
                                            <div class="mt-2">
                                                <span class="inline-flex items-center px-3 py-1.5 rounded-lg text-sm font-medium bg-gradient-to-r from-gray-100 to-gray-200 text-gray-700">
                                                    <i class="fas fa-check mr-2"></i>
                                                    {{ ucfirst(str_replace('_', ' ', $will->status)) }}
                                                </span>
                                            </div>
                                        @endif
                                    </div>
                                </td>
                            </tr>
                        @empty
                            <tr>
                                <td colspan="6" class="px-6 py-4 text-center text-gray-500">
                                    No wills found
                                </td>
                            </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Will Preview Section -->
<!-- <div id="willPreviewContainer" class="hidden mt-6">
    <div class="bg-white rounded-2xl shadow-lg overflow-hidden">
        <div class="bg-gradient-to-r from-blue-600 to-purple-600 p-6">
            <div class="flex justify-between items-center">
                <div>
                    <h3 class="text-2xl font-bold text-white">Will Preview</h3>
                    <p class="text-blue-100 mt-1">Review and manage completed will</p>
                </div>
                <button onclick="closeWillPreview()" class="w-10 h-10 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center transition-colors">
                    <i class="fas fa-times text-white"></i>
                </button>
            </div>
        </div>
        
        <div id="willPreviewContent" class="p-6">
        </div>
    </div>
</div> -->

<!-- Corrections Modal -->
<!-- <div id="correctionsModal" class="fixed inset-0 bg-black/60 hidden items-center justify-center z-50 backdrop-blur-sm">
    <div class="bg-white rounded-2xl p-8 max-w-2xl w-full mx-4 shadow-2xl transform transition-all max-h-[90vh] overflow-y-auto">
        <div class="flex justify-between items-center mb-6">
            <div>
                <h2 class="text-2xl font-bold text-gray-800">Request Corrections</h2>
                <p class="text-sm text-gray-500">Enter corrections needed for this will</p>
            </div>
            <button onclick="closeCorrectionsModal()" class="w-10 h-10 rounded-full bg-gray-100 hover:bg-gray-200 flex items-center justify-center transition-colors">
                <i class="fas fa-times text-gray-600"></i>
            </button>
        </div>

        <form id="correctionsForm" onsubmit="submitCorrections(event)">
            @csrf
            <input type="hidden" id="correctionsWillId" name="will_id">
            
            <div class="space-y-4">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Corrections Details</label>
                    <textarea name="corrections" rows="6" required placeholder="Please describe the corrections needed..."
                              class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-red-500 focus:ring-4 focus:ring-red-100 outline-none transition-all duration-300 resize-none"></textarea>
                </div>

                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">Priority</label>
                    <select name="priority" class="w-full px-4 py-3 border-2 border-gray-200 rounded-xl focus:border-red-500 focus:ring-4 focus:ring-red-100 outline-none transition-all duration-300">
                        <option value="low">Low</option>
                        <option value="medium" selected>Medium</option>
                        <option value="high">High</option>
                        <option value="urgent">Urgent</option>
                    </select>
                </div>

                <div class="bg-yellow-50 border border-yellow-200 rounded-xl p-4">
                    <p class="text-sm text-yellow-800">
                        <i class="fas fa-info-circle mr-2"></i>
                        Corrections will be sent to the admin portal and client portal for review.
                    </p>
                </div>
            </div>

            <div class="flex gap-3 mt-6">
                <button type="button" onclick="closeCorrectionsModal()" 
                        class="flex-1 px-4 py-3 border-2 border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors font-semibold">
                    Cancel
                </button>
                <button type="submit" 
                        class="flex-1 px-4 py-3 bg-red-600 text-white rounded-xl hover:bg-red-700 transition-colors font-semibold flex items-center justify-center">
                    <i class="fas fa-paper-plane mr-2"></i> Send Corrections
                </button>
            </div>
        </form>
    </div>
</div> -->

<script>
let currentWillId = null;

function toggleWillPreview(willId) {
    const container = document.getElementById('willPreviewContainer');
    
    if (currentWillId === willId && !container.classList.contains('hidden')) {
        closeWillPreview();
    } else {
        currentWillId = willId;
        loadWillPreview(willId);
        container.classList.remove('hidden');
        container.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    }
}

function closeWillPreview() {
    document.getElementById('willPreviewContainer').classList.add('hidden');
    currentWillId = null;
}

function loadWillPreview(willId) {
    fetch(`/agent/wills/${willId}/preview-ajax`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('willPreviewContent').innerHTML = data.html;
            } else {
               
            }
        })
        .catch(error => {
            console.error('Error:', error);
            
        });
}

function openCorrectionsModal(willId) {
    document.getElementById('correctionsWillId').value = willId;
    document.getElementById('correctionsModal').classList.remove('hidden');
    document.getElementById('correctionsModal').classList.add('flex');
    document.body.style.overflow = 'hidden';
}

function closeCorrectionsModal() {
    document.getElementById('correctionsModal').classList.add('hidden');
    document.getElementById('correctionsModal').classList.remove('flex');
    document.getElementById('correctionsForm').reset();
    document.body.style.overflow = '';
}

function submitCorrections(e) {
    e.preventDefault();
    const formData = new FormData(e.target);
    
    fetch('/agent/wills/request-corrections', {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json',
        },
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Corrections sent successfully!');
            closeCorrectionsModal();
            location.reload();
        } else {
            alert('Error: ' + (data.message || 'Failed to send corrections'));
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Error sending corrections. Please try again.');
    });
}

function scheduleAppointment(willId) {
    // Redirect to appointments page with pre-filled will context
    window.location.href = `/agent/appointments?will_id=${willId}`;
}

function verifyWill(willId) {
    if (!confirm('Mark this will as verified?')) return;
    
    fetch(`/agent/wills/${willId}/verify`, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
            'Accept': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Will verified successfully!');
            loadWillPreview(willId);
        } else {
            alert('Error: ' + (data.message || 'Failed to verify will'));
        }
    });
}

// Close modals on outside click
document.getElementById('correctionsModal').addEventListener('click', function(e) {
    if (e.target === this) closeCorrectionsModal();
});

// Keyboard shortcuts
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeCorrectionsModal();
        closeWillPreview();
    }
});
</script>
@endsection
