@extends('layouts.admin')

@section('title', 'Preview Quotation')

@section('page-title', 'Design & Finalize Quotation')

@section('content')
<div class="flex-1 overflow-y-auto overflow-x-hidden p-4 md:p-8 bg-gray-50">
    <div class="max-w-7xl mx-auto flex flex-col gap-6 h-full">
        <!-- Header & Progress -->
        <div class="flex flex-col gap-6 md:flex-row md:items-center md:justify-between">
            <div>
                <h1 class="text-2xl md:text-3xl font-bold text-gray-900 tracking-tight" style="font-size: 25px;">Design & Finalize Quotation</h1>
                <p class="text-gray-500 mt-1">
                    Quotation #{{ $data['quotation_number'] ?? 'QUO-2024-001' }} • 
                    <span class="text-emerald-600 font-medium bg-emerald-50 px-2 py-0.5 rounded text-xs">Draft</span>
                </p>
            </div>
            <!-- ProgressBar Component -->
            <div class="flex items-center gap-2 min-w-[300px]">
                <div class="flex flex-col flex-1 gap-2">
                    <div class="flex justify-between text-xs font-medium">
                        <span class="text-emerald-600 flex items-center gap-1">
                            <span class="material-symbols-outlined text-[14px]">check_circle</span> Details
                        </span>
                        <span class="text-primary flex items-center gap-1">Design & Share</span>
                    </div>
                    <div class="h-2 w-full bg-gray-200 rounded-full overflow-hidden flex">
                        <div class="h-full bg-emerald-500 w-1/2"></div>
                        <div class="h-full bg-primary w-1/2 animate-pulse"></div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Split Layout Content -->
        <div class="flex flex-col xl:flex-row gap-6 h-full items-start">
            <!-- LEFT PANEL: Quotation Preview -->
            <div class="flex-1 min-w-0 flex flex-col gap-6">
                <!-- Quotation Preview -->
                <div class="flex-1 min-w-0 bg-gray-200/50 rounded-xl border border-gray-200 p-4 md:p-8 overflow-y-auto flex justify-center items-start shadow-inner" style="width: 750px;">
                <!-- Quotation Paper A4 Ratio Approx -->
                <div class="bg-white w-full max-w-[800px] min-h-[1000px] shadow-lg rounded-sm overflow-auto text-gray-800 transition-all duration-300 origin-top transform scale-[0.85] md:scale-100 lg:scale-[0.85] xl:scale-95 2xl:scale-100" style="max-height: 1200px;">
                    @if(isset($templateView) && view()->exists($templateView))
                        @php
                            try {
                                // Render the template
                                $templateContent = view($templateView, ['quotation' => $quotation ?? null])->render();
                                
                                // Extract styles from head - get all style tags
                                $styles = '';
                                preg_match_all('/<style[^>]*>(.*?)<\/style>/is', $templateContent, $styleMatches);
                                if (!empty($styleMatches[1])) {
                                    $styles = '<style>' . implode('</style><style>', $styleMatches[1]) . '</style>';
                                }
                                
                                // Extract body content - get everything inside body tag
                                $bodyContent = $templateContent;
                                if (preg_match('/<body[^>]*>(.*?)<\/body>/is', $templateContent, $bodyMatches)) {
                                    $bodyContent = $bodyMatches[1];
                                } elseif (preg_match('/<div[^>]*class=["\']quotation-container["\'][^>]*>(.*?)<\/div>\s*<\/body>/is', $templateContent, $containerMatches)) {
                                    // If no body tag, try to get quotation-container div
                                    $bodyContent = $containerMatches[1];
                                } elseif (preg_match('/<div[^>]*class=["\']quotation-container["\'][^>]*>(.*)/is', $templateContent, $containerMatches)) {
                                    // Fallback: get quotation-container content
                                    $bodyContent = $containerMatches[1];
                                }
                            } catch (\Exception $e) {
                                $bodyContent = '<div class="p-8 text-red-500">Error loading template: ' . htmlspecialchars($e->getMessage()) . '<br>Template: ' . htmlspecialchars($templateView ?? 'N/A') . '</div>';
                                $styles = '';
                            }
                        @endphp
                        {!! $styles !!}
                        <div class="quotation-template-wrapper" style="background: white; min-height: 1000px; overflow: visible;">
                            {!! $bodyContent !!}
                        </div>
                    @else
                    <!-- Quotation Header -->
                    <div class="flex justify-between items-start mb-12">
                        <div class="flex flex-col gap-4">
                            <!-- Logo Placeholder -->
                            @if($companySettings->company_logo && \Illuminate\Support\Facades\Storage::disk('public')->exists($companySettings->company_logo))
                                <img src="{{ \Illuminate\Support\Facades\Storage::url($companySettings->company_logo) }}" alt="Company Logo" class="h-12 w-auto">
                            @else
                                <div class="h-12 w-12 bg-primary rounded-lg flex items-center justify-center text-white font-bold text-xl">
                                    {{ strtoupper(substr($companySettings->company_name ?? 'FA', 0, 2)) }}
                                </div>
                            @endif
                            <div class="text-sm text-gray-500">
                                <p class="font-bold text-gray-800">{{ $companySettings->company_name ?? config('app.name', 'ProInvoice') }}</p>
                                @if($companySettings->company_address)
                                    <p>{{ $companySettings->company_address }}</p>
                                @endif
                            </div>
                        </div>
                        <div class="text-right">
                            <h2 class="text-4xl font-light text-gray-900 tracking-tight mb-2">QUOTATION</h2>
                            <p class="text-gray-500 font-medium text-lg">#{{ $data['quotation_number'] ?? 'QUO-2024-001' }}</p>
                            <div class="mt-4 text-sm">
                                <div class="flex justify-end gap-4 mb-1">
                                    <span class="text-gray-400">Issue Date:</span>
                                    <span class="font-medium text-gray-700">{{ \Carbon\Carbon::parse($data['issue_date'] ?? now())->format('M d, Y') }}</span>
                                </div>
                                @if(!empty($data['expiry_date']))
                                <div class="flex justify-end gap-4">
                                    <span class="text-gray-400">Valid Until:</span>
                                    <span class="font-medium text-gray-700">{{ \Carbon\Carbon::parse($data['expiry_date'])->format('M d, Y') }}</span>
                                </div>
                                @endif
                            </div>
                        </div>
                    </div>
                    <!-- Bill To Section -->
                    @if($customer)
                    <div class="mb-12">
                        <p class="text-xs font-bold text-gray-400 uppercase tracking-wider mb-2">Bill To</p>
                        <h3 class="text-xl font-bold text-gray-900">{{ $customer->name }}</h3>
                        @if($customer->email)
                            <p class="text-gray-600">{{ $customer->email }}</p>
                        @endif
                        @if($customer->phone)
                            <p class="text-gray-600">{{ $customer->phone }}</p>
                        @endif
                        @if($customer->address)
                            <p class="text-gray-600">{{ $customer->address }}</p>
                        @endif
                    </div>
                    @endif
                    <!-- Items Table -->
                    <div class="flex-1 mb-8">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="border-b-2 border-gray-100">
                                    <th class="py-3 text-xs font-bold text-gray-400 uppercase tracking-wider w-1/2">Description</th>
                                    <th class="py-3 text-xs font-bold text-gray-400 uppercase tracking-wider text-right">Qty</th>
                                    <th class="py-3 text-xs font-bold text-gray-400 uppercase tracking-wider text-right">Price</th>
                                    <th class="py-3 text-xs font-bold text-gray-400 uppercase tracking-wider text-right">Total</th>
                                </tr>
                            </thead>
                            <tbody class="text-sm">
                                @forelse($items as $item)
                                <tr class="border-b border-gray-50">
                                    <td class="py-4 pr-4">
                                        <p class="font-semibold text-gray-800">{{ $item['description'] }}</p>
                                        @if(!empty($item['notes']))
                                            <p class="text-gray-500 text-xs mt-1">{{ $item['notes'] }}</p>
                                        @endif
                                    </td>
                                    <td class="py-4 text-right text-gray-600">{{ number_format($item['quantity'], 2) }}</td>
                                    <td class="py-4 text-right text-gray-600">{{ $selectedCurrency->symbol ?? '$' }}{{ number_format($item['unit_price'], 2) }}</td>
                                    <td class="py-4 text-right font-medium text-gray-800">{{ $selectedCurrency->symbol ?? '$' }}{{ number_format($item['total'], 2) }}</td>
                                </tr>
                                @empty
                                <tr>
                                    <td colspan="4" class="py-8 text-center text-gray-500">No items added</td>
                                </tr>
                                @endforelse
                            </tbody>
                        </table>
                    </div>
                    <!-- Totals -->
                    <div class="flex justify-end mb-16">
                        <div class="w-1/2 md:w-1/3 flex flex-col gap-3">
                            <div class="flex justify-between text-sm">
                                <span class="text-gray-500">Subtotal</span>
                                <span class="font-medium text-gray-800">{{ $selectedCurrency->symbol ?? '$' }}{{ number_format($subtotal, 2) }}</span>
                            </div>
                            @if($taxAmount > 0)
                            <div class="flex justify-between text-sm">
                                <span class="text-gray-500">Tax</span>
                                <span class="font-medium text-gray-800">{{ $selectedCurrency->symbol ?? '$' }}{{ number_format($taxAmount, 2) }}</span>
                            </div>
                            @endif
                            @if($discount > 0)
                            <div class="flex justify-between text-sm">
                                <span class="text-gray-500">Discount</span>
                                <span class="font-medium text-gray-800">-{{ $selectedCurrency->symbol ?? '$' }}{{ number_format($discount, 2) }}</span>
                            </div>
                            @endif
                            <div class="h-px bg-gray-200 my-1"></div>
                            <div class="flex justify-between text-base">
                                <span class="font-bold text-gray-900">Total</span>
                                <span class="font-bold text-primary text-xl">{{ $selectedCurrency->symbol ?? '$' }}{{ number_format($total, 2) }}</span>
                            </div>
                        </div>
                    </div>
                    <!-- Footer / Notes & Terms -->
                    @if(!empty($data['notes']) || !empty($data['terms']))
                    <div class="flex flex-col items-start justify-center mt-auto mb-8">
                        <div class="w-full max-w-md">
                            @if(!empty($data['notes']))
                            <div class="mb-4">
                                <p class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Notes</p>
                                <p class="text-sm text-gray-600">{{ $data['notes'] }}</p>
                            </div>
                            @endif
                            @if(!empty($data['terms']))
                            <div>
                                <p class="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-2">Terms & Conditions</p>
                                <p class="text-sm text-gray-600">{{ $data['terms'] }}</p>
                            </div>
                            @endif
                        </div>
                    </div>
                    @endif
                    <!-- Brand Strip at Bottom -->
                    <div class="mt-8 pt-4 border-t border-gray-100 flex justify-center">
                        <p class="text-gray-400 text-xs">Powered by {{ config('app.name', 'ProInvoice') }}</p>
                    </div>
                    @endif
                </div>
                </div>
            </div>
            
            <!-- RIGHT PANEL: Share Quotation -->
            <div class="w-full xl:w-[380px] flex-shrink-0 flex flex-col gap-6">
                <!-- Share & Download Card -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="px-5 py-4 border-b border-gray-100">
                        <h3 class="font-bold text-gray-900 flex items-center gap-2">
                            <span class="material-symbols-outlined text-primary text-xl">share</span>
                            Share Quotation
                        </h3>
                    </div>
                    <div class="p-5 flex flex-col gap-4">
                        <div class="h-px bg-gray-100 my-1"></div>
                        <div class="grid grid-cols-2 gap-3">
                            <button onclick="window.print()" class="flex items-center justify-center gap-2 px-4 py-2.5 border border-gray-200 rounded-lg hover:bg-gray-50 text-gray-700 text-sm font-medium transition-colors">
                                <span class="material-symbols-outlined text-[18px]">print</span>
                                Print
                            </button>
                            <button onclick="downloadPdf()" class="flex items-center justify-center gap-2 px-4 py-2.5 border border-gray-200 rounded-lg hover:bg-gray-50 text-gray-700 text-sm font-medium transition-colors">
                                <span class="material-symbols-outlined text-[18px]">download</span>
                                Download PDF
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Sticky Footer Actions -->
<div class="bg-white border-t border-gray-200 p-4 z-20 shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.05)]">
    <div class="max-w-7xl mx-auto flex justify-between items-center">
        <a href="{{ route('admin.quotations.create') }}" class="px-6 py-2.5 text-sm font-medium text-gray-600 hover:text-gray-900 transition-colors flex items-center gap-2">
            <span class="material-symbols-outlined text-[18px]">arrow_back</span>
            Back to Details
        </a>
        <div class="flex gap-4">
            <form method="POST" action="{{ route('admin.quotations.store') }}" id="quotation-form-draft">
                @csrf
                @foreach($data as $key => $value)
                    @if(is_array($value))
                        @foreach($value as $subKey => $subValue)
                            @if(is_array($subValue))
                                @foreach($subValue as $itemKey => $itemValue)
                                    <input type="hidden" name="{{ $key }}[{{ $subKey }}][{{ $itemKey }}]" value="{{ $itemValue }}">
                                @endforeach
                            @else
                                <input type="hidden" name="{{ $key }}[{{ $subKey }}]" value="{{ $subValue }}">
                            @endif
                        @endforeach
                    @else
                        <input type="hidden" name="{{ $key }}" value="{{ $value }}">
                    @endif
                @endforeach
                <input type="hidden" name="status" value="draft">
                <button type="submit" class="px-6 py-2.5 rounded-lg border border-gray-300 text-gray-700 text-sm font-bold hover:bg-gray-50 transition-colors">
                    Save as Draft
                </button>
            </form>
            <form method="POST" action="{{ route('admin.quotations.store') }}" id="quotation-form-final">
                @csrf
                @foreach($data as $key => $value)
                    @if(is_array($value))
                        @foreach($value as $subKey => $subValue)
                            @if(is_array($subValue))
                                @foreach($subValue as $itemKey => $itemValue)
                                    <input type="hidden" name="{{ $key }}[{{ $subKey }}][{{ $itemKey }}]" value="{{ $itemValue }}">
                                @endforeach
                            @else
                                <input type="hidden" name="{{ $key }}[{{ $subKey }}]" value="{{ $subValue }}">
                            @endif
                        @endforeach
                    @else
                        <input type="hidden" name="{{ $key }}" value="{{ $value }}">
                    @endif
                @endforeach
                <input type="hidden" name="status" value="sent">
                <button type="submit" class="px-8 py-2.5 rounded-lg bg-primary text-white text-sm font-bold shadow-lg shadow-primary/30 hover:bg-blue-600 transition-all transform active:scale-95 flex items-center gap-2">
                    <span class="material-symbols-outlined text-[20px]">check</span>
                    Create Quotation
                </button>
            </form>
        </div>
    </div>
</div>

<script>
// Download PDF (for new quotations - would need to save first)
function downloadPdf() {
    alert('Please save the quotation first to download PDF.');
}

// Print function
function printQuotation() {
    window.print();
}
</script>
@endsection
