@extends('adminlte::page')

@section('title', 'Proposal Details')

@section('content')
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Proposal Details</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="{{ route('creator.dashboard') }}">Home</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('creator.proposals.index') }}">Proposals</a></li>
                    <li class="breadcrumb-item active">Details</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->title }}</h3>
                        <div class="card-tools">
                            <span class="badge 
                                @if($proposal->status === 'sent') badge-warning
                                @elseif($proposal->status === 'accepted') badge-success
                                @elseif($proposal->status === 'rejected') badge-danger
                                @endif">
                                {{ ucfirst($proposal->status) }}
                            </span>
                            <button type="button" class="btn btn-tool" data-card-widget="collapse">
                                <i class="fas fa-minus"></i>
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h5>Proposal Information</h5>
                                <table class="table table-borderless">
                                    <tr>
                                        <th>Brand:</th>
                                        <td>{{ $proposal->brand->name }}</td>
                                    </tr>
                                    <tr>
                                        <th>Type:</th>
                                        <td>{{ $proposal->type }}</td>
                                    </tr>
                                    <tr>
                                        <th>Budget:</th>
                                        <td>{{ $proposal->budget ? '$' . number_format($proposal->budget, 2) : 'Not specified' }}</td>
                                    </tr>
                                    <tr>
                                        <th>Duration:</th>
                                        <td>{{ $proposal->duration ?? 'Not specified' }}</td>
                                    </tr>
                                    <tr>
                                        <th>Date Sent:</th>
                                        <td>{{ $proposal->created_at->format('M j, Y H:i') }}</td>
                                    </tr>
                                    <tr>
                                        <th>Last Updated:</th>
                                        <td>{{ $proposal->updated_at->format('M j, Y H:i') }}</td>
                                    </tr>
                                </table>
                            </div>
                            
                            <div class="col-md-6">
                                <h5>Deliverables</h5>
                                @if($proposal->deliverables)
                                    <ul>
                                        @foreach($proposal->deliverables as $deliverable)
                                            <li>{{ $deliverable }}</li>
                                        @endforeach
                                    </ul>
                                @else
                                    <p>No deliverables specified.</p>
                                @endif
                                
                                @if($proposal->attachment_path)
                                <h5>Attachment</h5>
                                <p>
                                    <a href="{{ Storage::url($proposal->attachment_path) }}" target="_blank" class="btn btn-info">
                                        <i class="fas fa-download"></i> Download Attachment
                                    </a>
                                </p>
                                @endif
                            </div>
                        </div>
                        
                        <div class="row mt-4">
                            <div class="col-12">
                                <h5>Message</h5>
                                <div class="p-3 bg-light rounded">
                                    {{ $proposal->message }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-footer">
                        <a href="{{ route('creator.proposals.index') }}" class="btn btn-secondary">
                            <i class="fas fa-arrow-left"></i> Back to Proposals
                        </a>
                        
                        @if($proposal->status === 'sent')
                        <button type="button" class="btn btn-warning" disabled>
                            <i class="fas fa-clock"></i> Awaiting Response
                        </button>
                        @elseif($proposal->status === 'accepted')
                        <button type="button" class="btn btn-success" disabled>
                            <i class="fas fa-check"></i> Accepted
                        </button>
                        @elseif($proposal->status === 'rejected')
                        <button type="button" class="btn btn-danger" disabled>
                            <i class="fas fa-times"></i> Rejected
                        </button>
                        @endif
                    </div>
                </div>
                
                <!-- Chat Tab -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Discussion</h3>
                        @if($proposal->thread)
                            <a href="{{ route('messages.show', $proposal->thread) }}" class="btn btn-info btn-sm float-right">
                                <i class="fas fa-comments"></i> Open Chat
                            </a>
                        @else
                            <button type="button" class="btn btn-info btn-sm float-right" data-toggle="modal" data-target="#startChatModal">
                                <i class="fas fa-plus"></i> Start Chat
                            </button>
                        @endif
                    </div>
                    <div class="card-body">
                        <!-- Comments Container -->
                        <div id="comments-container">
                            <!-- Comments will be loaded here via AJAX -->
                        </div>
                        
                        <!-- Add Comment Form -->
                        <div class="mt-4">
                            <h5>Add a Comment</h5>
                            <form id="comment-form" action="{{ route('creator.proposals.comments.store', $proposal) }}" method="POST" enctype="multipart/form-data">
                                @csrf
                                <div class="form-group">
                                    <textarea name="message" class="form-control" rows="3" placeholder="Type your comment here..." required></textarea>
                                </div>
                                <div class="form-group">
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" id="attachment" name="attachment">
                                        <label class="custom-file-label" for="attachment">Choose file (optional)</label>
                                    </div>
                                </div>
                                <button type="submit" class="btn btn-primary">Post Comment</button>
                            </form>
                        </div>
                    </div>
                </div>
                
                <!-- Start Chat Modal -->
                <div class="modal fade" id="startChatModal" tabindex="-1" role="dialog">
                    <div class="modal-dialog" role="document">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title">Start Chat with Brand</h5>
                                <button type="button" class="close" data-dismiss="modal">
                                    <span>&times;</span>
                                </button>
                            </div>
                            <form action="{{ route('threads.create') }}" method="POST">
                                @csrf
                                <input type="hidden" name="recipient_id" value="{{ $proposal->brand->user_id ?? $proposal->brand->id }}">
                                <input type="hidden" name="proposal_id" value="{{ $proposal->id }}">
                                <div class="modal-body">
                                    <div class="form-group">
                                        <label for="message">Message</label>
                                        <textarea name="body" class="form-control" rows="3" placeholder="Type your message here..." required></textarea>
                                    </div>
                                    <div class="form-group">
                                        <label for="attachment">Attachment (optional)</label>
                                        <div class="custom-file">
                                            <input type="file" class="custom-file-input" id="modal-attachment" name="attachment" accept=".pdf,.jpg,.jpeg,.png,.docx">
                                            <label class="custom-file-label" for="modal-attachment">Choose file</label>
                                        </div>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                    <button type="submit" class="btn btn-primary">Start Chat</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
@parent
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Load comments
    function loadComments() {
        fetch('{{ route('creator.proposals.comments.index', $proposal) }}')
            .then(response => response.json())
            .then(comments => {
                const container = document.getElementById('comments-container');
                container.innerHTML = '';
                
                if (comments.length === 0) {
                    container.innerHTML = '<p class="text-muted">No comments yet.</p>';
                    return;
                }
                
                comments.forEach(comment => {
                    const commentElement = document.createElement('div');
                    commentElement.className = 'direct-chat-msg';
                    commentElement.innerHTML = `
                        <div class="direct-chat-infos clearfix">
                            <span class="direct-chat-name float-left">${comment.user.name}</span>
                            <span class="direct-chat-timestamp float-right">${comment.created_at}</span>
                        </div>
                        <img class="direct-chat-img" src="${comment.user.avatar}" alt="User Avatar">
                        <div class="direct-chat-text">
                            ${comment.message}
                            ${comment.attachment_path ? `<div class="mt-2"><a href="/storage/${comment.attachment_path}" target="_blank" class="btn btn-sm btn-outline-primary"><i class="fas fa-paperclip"></i> Attachment</a></div>` : ''}
                        </div>
                    `;
                    container.appendChild(commentElement);
                    
                    // Add replies
                    if (comment.replies && comment.replies.length > 0) {
                        const repliesContainer = document.createElement('div');
                        repliesContainer.className = 'ml-5';
                        
                        comment.replies.forEach(reply => {
                            const replyElement = document.createElement('div');
                            replyElement.className = 'direct-chat-msg';
                            replyElement.innerHTML = `
                                <div class="direct-chat-infos clearfix">
                                    <span class="direct-chat-name float-left">${reply.user.name}</span>
                                    <span class="direct-chat-timestamp float-right">${reply.created_at}</span>
                                </div>
                                <img class="direct-chat-img" src="${reply.user.avatar}" alt="User Avatar">
                                <div class="direct-chat-text">
                                    ${reply.message}
                                    ${reply.attachment_path ? `<div class="mt-2"><a href="/storage/${reply.attachment_path}" target="_blank" class="btn btn-sm btn-outline-primary"><i class="fas fa-paperclip"></i> Attachment</a></div>` : ''}
                                </div>
                            `;
                            repliesContainer.appendChild(replyElement);
                        });
                        
                        container.appendChild(repliesContainer);
                    }
                });
            })
            .catch(error => {
                console.error('Error loading comments:', error);
            });
    }
    
    // Handle form submission
    document.getElementById('comment-form').addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        
        fetch(this.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        })
        .then(response => {
            if (response.ok) {
                // Reset form
                this.reset();
                document.querySelector('.custom-file-label').innerHTML = 'Choose file (optional)';
                
                // Reload comments
                loadComments();
                
                // Show success message
                alert('Comment added successfully!');
            } else {
                alert('Error adding comment. Please try again.');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Error adding comment. Please try again.');
        });
    });
    
    // Update file input label when file is selected
    document.getElementById('attachment').addEventListener('change', function() {
        const fileName = this.value.split('\\').pop();
        document.querySelector('.custom-file-label').innerHTML = fileName;
    });
    
    // Load comments when page loads
    loadComments();
});
</script>
@endsection