@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('brand.dashboard') }}">Home</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('brand.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: {{ $proposal->title }}</h3>
                       <div class="card-tools">
                           @if($proposal->status === 'sent')
                               <button type="button" class="btn btn-success" onclick="acceptProposal({{ $proposal->id }})">
                                   <i class="fas fa-check"></i> Accept
                               </button>
                               <button type="button" class="btn btn-danger" onclick="rejectProposal({{ $proposal->id }})">
                                   <i class="fas fa-times"></i> Reject
                               </button>
                           @elseif($proposal->status === 'accepted')
                               <button type="button" class="btn btn-primary" onclick="sendContract({{ $proposal->id }})">
                                   <i class="fas fa-file-contract"></i> Send Contract
                               </button>
                           @elseif($proposal->status === 'contract_sent')
                               <button type="button" class="btn btn-info" onclick="contractSigned({{ $proposal->id }})">
                                   <i class="fas fa-signature"></i> Contract Signed
                               </button>
                           @elseif($proposal->status === 'contract_signed')
                               <button type="button" class="btn btn-warning" onclick="processPayment({{ $proposal->id }})">
                                   <i class="fas fa-money-bill-wave"></i> Process Payment
                               </button>
                           @elseif($proposal->status === 'payment_made')
                               <button type="button" class="btn btn-success" onclick="markDelivered({{ $proposal->id }})">
                                   <i class="fas fa-truck"></i> Mark Delivered
                               </button>
                           @endif
                           <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>Title:</th>
                                        <td>{{ $proposal->title }}</td>
                                    </tr>
                                    <tr>
                                        <th>Type:</th>
                                        <td>{{ $proposal->type }}</td>
                                    </tr>
                                    <tr>
                                        <th>Status:</th>
                                        <td>
                                            @switch($proposal->status)
                                                @case('sent')
                                                    <span class="badge badge-warning">Sent</span>
                                                    @break
                                                @case('accepted')
                                                    <span class="badge badge-success">Accepted</span>
                                                    @break
                                                @case('rejected')
                                                    <span class="badge badge-danger">Rejected</span>
                                                    @break
                                                @default
                                                    <span class="badge badge-secondary">{{ ucfirst($proposal->status) }}</span>
                                            @endswitch
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Budget:</th>
                                        <td>{{ $proposal->budget ? '$' . number_format($proposal->budget, 2) : 'N/A' }}</td>
                                    </tr>
                                    <tr>
                                        <th>Duration:</th>
                                        <td>{{ $proposal->duration ?? 'N/A' }}</td>
                                    </tr>
                                    <tr>
                                        <th>Date Sent:</th>
                                        <td>{{ $proposal->created_at->format('M j, Y H:i') }}</td>
                                    </tr>
                                </table>
                            </div>
                            
                            <div class="col-md-6">
                                <h5>Creator Information</h5>
                                <table class="table table-borderless">
                                    <tr>
                                        <th>Name:</th>
                                        <td>{{ $proposal->creator->name }}</td>
                                    </tr>
                                    <tr>
                                        <th>Email:</th>
                                        <td>{{ $proposal->creator->email }}</td>
                                    </tr>
                                    <tr>
                                        <th>Influencer Type:</th>
                                        <td>
                                            @if($proposal->creator->influencer_type === 'Other' && $proposal->creator->influencer_type_custom)
                                                {{ $proposal->creator->influencer_type_custom }}
                                            @else
                                                {{ $proposal->creator->influencer_type ?? 'Not specified' }}
                                            @endif
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>Profile:</th>
                                        <td>
                                            <a href="{{ route('brand.creators.show', $proposal->creator) }}" class="btn btn-primary btn-sm">
                                                <i class="fas fa-eye"></i> View Profile
                                            </a>
                                        </td>
                                    </tr>
                                </table>
                            </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>
                        
                        @if($proposal->deliverables)
                            <div class="row mt-4">
                                <div class="col-12">
                                    <h5>Deliverables</h5>
                                    <ul>
                                        @foreach($proposal->deliverables as $deliverable)
                                            <li>{{ $deliverable }}</li>
                                        @endforeach
                                    </ul>
                                </div>
                            </div>
                        @endif
                        
                        @if($proposal->attachment_path)
                            <div class="row mt-4">
                                <div class="col-12">
                                    <h5>Attachment</h5>
                                    <a href="{{ Storage::url($proposal->attachment_path) }}" target="_blank" class="btn btn-info">
                                        <i class="fas fa-file-download"></i> Download Attachment
                                    </a>
                                </div>
                            </div>
                        @endif
                    </div>
                </div>
                
                <!-- Chat Tab -->
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">Discussion</h3>
                    </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('brand.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>
            </div>
        </div>
    </div>
</div>
@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Accept proposal function
    window.acceptProposal = function(proposalId) {
        if (confirm('Are you sure you want to accept this proposal?')) {
            // Create a form and submit it
            var form = document.createElement('form');
            form.method = 'POST';
            form.action = `/brand/proposals/${proposalId}/accept`;
            
            var csrfToken = document.createElement('input');
            csrfToken.type = 'hidden';
            csrfToken.name = '_token';
            csrfToken.value = '{{ csrf_token() }}';
            
            var methodField = document.createElement('input');
            methodField.type = 'hidden';
            methodField.name = '_method';
            methodField.value = 'PUT';
            
            form.appendChild(csrfToken);
            form.appendChild(methodField);
            document.body.appendChild(form);
            form.submit();
        }
    };
    
    // Reject proposal function
   window.rejectProposal = function(proposalId) {
       if (confirm('Are you sure you want to reject this proposal?')) {
           // Create a form and submit it
           var form = document.createElement('form');
           form.method = 'POST';
           form.action = `/brand/proposals/${proposalId}/reject`;
           
           var csrfToken = document.createElement('input');
           csrfToken.type = 'hidden';
           csrfToken.name = '_token';
           csrfToken.value = '{{ csrf_token() }}';
           
           var methodField = document.createElement('input');
           methodField.type = 'hidden';
           methodField.name = '_method';
           methodField.value = 'PUT';
           
           form.appendChild(csrfToken);
           form.appendChild(methodField);
           document.body.appendChild(form);
           form.submit();
       }
   };
   
   // Send contract function
   window.sendContract = function(proposalId) {
       if (confirm('Are you sure you want to send the contract?')) {
           // Create a form and submit it
           var form = document.createElement('form');
           form.method = 'POST';
           form.action = `/brand/proposals/${proposalId}/send-contract`;
           
           var csrfToken = document.createElement('input');
           csrfToken.type = 'hidden';
           csrfToken.name = '_token';
           csrfToken.value = '{{ csrf_token() }}';
           
           form.appendChild(csrfToken);
           document.body.appendChild(form);
           form.submit();
       }
   };
   
   // Contract signed function
   window.contractSigned = function(proposalId) {
       if (confirm('Are you sure you want to mark the contract as signed?')) {
           // Create a form and submit it
           var form = document.createElement('form');
           form.method = 'POST';
           form.action = `/brand/proposals/${proposalId}/contract-signed`;
           
           var csrfToken = document.createElement('input');
           csrfToken.type = 'hidden';
           csrfToken.name = '_token';
           csrfToken.value = '{{ csrf_token() }}';
           
           form.appendChild(csrfToken);
           document.body.appendChild(form);
           form.submit();
       }
   };
   
   // Process payment function
   window.processPayment = function(proposalId) {
       if (confirm('Are you sure you want to process the payment?')) {
           // Create a form and submit it
           var form = document.createElement('form');
           form.method = 'POST';
           form.action = `/brand/proposals/${proposalId}/process-payment`;
           
           var csrfToken = document.createElement('input');
           csrfToken.type = 'hidden';
           csrfToken.name = '_token';
           csrfToken.value = '{{ csrf_token() }}';
           
           form.appendChild(csrfToken);
           document.body.appendChild(form);
           form.submit();
       }
   };
   
   // Mark delivered function
   window.markDelivered = function(proposalId) {
       if (confirm('Are you sure you want to mark the proposal as delivered?')) {
           // Create a form and submit it
           var form = document.createElement('form');
           form.method = 'POST';
           form.action = `/brand/proposals/${proposalId}/mark-delivered`;
           
           var csrfToken = document.createElement('input');
           csrfToken.type = 'hidden';
           csrfToken.name = '_token';
           csrfToken.value = '{{ csrf_token() }}';
           
           form.appendChild(csrfToken);
           document.body.appendChild(form);
           form.submit();
       }
   };
    
    // Load comments
    function loadComments() {
        fetch('{{ route('brand.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