@extends('adminlte::page')

@section('title', 'AI Generated Proposal')

@section('content')
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">AI Generated Proposal</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{ route('brand.dashboard') }}">Home</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('brand.proposals.index') }}">Proposals</a></li>
                    <li class="breadcrumb-item active">AI Generated Proposal</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<div class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Proposal Preview</h3>
                        <div class="card-tools">
                            <span class="badge 
                                @if($aiJob->status === 'queued') badge-warning
                                @elseif($aiJob->status === 'generating') badge-info
                                @elseif($aiJob->status === 'ready') badge-success
                                @elseif($aiJob->status === 'accepted') badge-primary
                                @elseif($aiJob->status === 'failed') badge-danger
                                @else badge-secondary
                                @endif">
                                {{ ucfirst(str_replace('_', ' ', $aiJob->status)) }}
                            </span>
                        </div>
                    </div>
                    <div class="card-body">
                        @if($aiJob->status === 'failed')
                            <div class="alert alert-danger">
                                <h4>Error Generating Proposal</h4>
                                <p>{{ $aiJob->error_message ?? 'An unknown error occurred during proposal generation.' }}</p>
                            </div>
                        @elseif($aiJob->status === 'queued' || $aiJob->status === 'generating')
                            <div class="text-center py-5">
                                <div class="spinner-border" role="status">
                                    <span class="sr-only">Loading...</span>
                                </div>
                                <p class="mt-3">Your proposal is being generated. This may take a few moments.</p>
                            </div>
                        @elseif($aiJob->status === 'ready' || $aiJob->status === 'accepted')
                            <form id="proposalForm">
                                @csrf
                                @method('PUT')
                                
                                <input type="hidden" name="job_id" value="{{ $aiJob->job_id }}">
                                
                                <div class="form-group">
                                    <label for="title">Proposal Title</label>
                                    <input type="text" name="title" id="title" class="form-control" value="{{ $aiJob->result_meta['title'] ?? '' }}" required>
                                </div>
                                
                                <div class="form-group">
                                    <label for="price_estimate">Price Estimate</label>
                                    <input type="number" name="price_estimate" id="price_estimate" class="form-control" 
                                           value="{{ $aiJob->result_meta['price_estimate'] ?? '' }}" step="0.01" min="0" required>
                                </div>
                                
                                <h4>Proposal Sections</h4>
                                <div id="sections-container">
                                    @if(isset($aiJob->result_meta['sections']) && is_array($aiJob->result_meta['sections']))
                                        @foreach($aiJob->result_meta['sections'] as $index => $section)
                                            <div class="card mb-3 section-card" data-section-index="{{ $index }}">
                                                <div class="card-header">
                                                    <input type="text" name="sections[{{ $index }}][title]" 
                                                           class="form-control section-title" 
                                                           value="{{ $section['title'] ?? 'Section ' . ($index + 1) }}" required>
                                                </div>
                                                <div class="card-body">
                                                    <textarea name="sections[{{ $index }}][content]" 
                                                              class="form-control section-content" 
                                                              rows="5" required>{{ $section['content'] ?? '' }}</textarea>
                                                    <input type="hidden" name="sections[{{ $index }}][order]" value="{{ $index }}">
                                                </div>
                                            </div>
                                        @endforeach
                                    @else
                                        <div class="card mb-3 section-card" data-section-index="0">
                                            <div class="card-header">
                                                <input type="text" name="sections[0][title]" 
                                                       class="form-control section-title" 
                                                       value="Introduction" required>
                                            </div>
                                            <div class="card-body">
                                                <textarea name="sections[0][content]" 
                                                          class="form-control section-content" 
                                                          rows="5" required></textarea>
                                                <input type="hidden" name="sections[0][order]" value="0">
                                            </div>
                                        </div>
                                    @endif
                                </div>
                                
                                <div class="form-group">
                                    <button type="button" id="add-section" class="btn btn-outline-secondary btn-sm">Add Section</button>
                                </div>
                                
                                <div class="form-group">
                                    <button type="button" id="save-draft" class="btn btn-secondary">Save Draft</button>
                                    <button type="button" id="regenerate" class="btn btn-warning">Regenerate</button>
                                    <button type="button" id="accept-send" class="btn btn-success">Accept & Send</button>
                                </div>
                            </form>
                        @endif
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Add section button
    document.getElementById('add-section').addEventListener('click', function() {
        const container = document.getElementById('sections-container');
        const sectionCount = container.querySelectorAll('.section-card').length;
        const newSection = document.createElement('div');
        newSection.className = 'card mb-3 section-card';
        newSection.dataset.sectionIndex = sectionCount;
        newSection.innerHTML = `
            <div class="card-header">
                <input type="text" name="sections[${sectionCount}][title]" 
                       class="form-control section-title" 
                       value="Section ${sectionCount + 1}" required>
            </div>
            <div class="card-body">
                <textarea name="sections[${sectionCount}][content]" 
                          class="form-control section-content" 
                          rows="5" required></textarea>
                <input type="hidden" name="sections[${sectionCount}][order]" value="${sectionCount}">
            </div>
        `;
        container.appendChild(newSection);
    });
    
    // Save draft button
    document.getElementById('save-draft').addEventListener('click', function() {
        submitForm('save_draft');
    });
    
    // Regenerate button
    document.getElementById('regenerate').addEventListener('click', function() {
        if (confirm('Are you sure you want to regenerate this proposal? All current edits will be lost.')) {
            submitForm('regenerate');
        }
    });
    
    // Accept & Send button
    document.getElementById('accept-send').addEventListener('click', function() {
        submitForm('accept');
    });
    
    // Form submission
    function submitForm(action) {
        const form = document.getElementById('proposalForm');
        const formData = new FormData(form);
        formData.append('action', action);
        
        fetch('{{ route('brand.ai-proposals.update', $aiJob->job_id) }}', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'X-HTTP-Method-Override': 'PUT'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(data.message);
                if (data.redirect) {
                    window.location.href = data.redirect;
                } else {
                    // Reload the page to show updated status
                    window.location.reload();
                }
            } else {
                alert('Error: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred while processing your request.');
        });
    }
    
    // Poll for status updates if still generating
    @if($aiJob->status === 'queued' || $aiJob->status === 'generating')
        const pollInterval = setInterval(function() {
            fetch('{{ route('brand.ai-proposals.show', $aiJob->job_id) }}', {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.text())
            .then(html => {
                // Check if status has changed to ready
                if (html.includes('Proposal Preview') && !html.includes('Loading...')) {
                    clearInterval(pollInterval);
                    window.location.reload();
                }
            })
            .catch(error => {
                console.error('Polling error:', error);
            });
        }, 5000); // Poll every 5 seconds
    @endif
});
</script>
@endsection