@extends('layouts.app')

@section('title', 'Lead Listing')

@section('content')
    <div class="portal-page-header d-flex justify-content-between align-items-start flex-wrap gap-2">
        <div>
            <h1 class="h4 mb-0">Lead Listing</h1>
            <p class="subtitle">Unopened leads appear first, then by fair start date. Assign leads to the marketing team for follow-up.</p>
        </div>
        @if(can_access_module('leads.create'))
            <a href="{{ route('leads.create') }}" class="btn btn-portal-primary">+ Add Lead</a>
        @endif
    </div>

    <div class="portal-card">
        <div class="portal-table-wrap">
            <table class="table portal-table mb-0">
                <thead>
                <tr>
                    <th>Fair Name</th>
                    <th>Venue</th>
                    <th>Budget</th>
                    <th>Area</th>
                    <th>Email</th>
                    <th>Phone</th>
                    <th>Status</th>
                    <th>Marketing</th>
                    <th class="text-end">Actions</th>
                </tr>
                </thead>
                <tbody>
                @forelse($leads as $lead)
                    @php $unread = $lead->leadViews->isEmpty(); @endphp
                    <tr class="{{ $unread ? 'row-unread' : '' }}">
                        <td>
                            @if(can_access_module('leads.view'))
                                <a href="{{ route('leads.show', $lead) }}" class="lead-link">{{ $lead->displayFairName() ?: '—' }}</a>
                                @if($unread)
                                    <span class="portal-badge portal-badge-costing ms-1" style="font-size:0.6rem;">New</span>
                                @endif
                            @else
                                {{ $lead->displayFairName() ?: '—' }}
                            @endif
                        </td>
                        <td>{{ $lead->displayVenue() }}</td>
                        <td>{{ $lead->lead_budget !== null ? number_format($lead->lead_budget, 0) : '—' }}</td>
                        <td>{{ $lead->displayArea() }}</td>
                        <td class="text-muted">{{ $lead->maskedEmail() }}</td>
                        <td class="text-muted">{{ $lead->maskedPhone() }}</td>
                        <td>@include('partials.lead-status-badge', ['status' => $lead->clean_lead_status])</td>
                        <td>
                            @if($lead->assignedTo)
                                <span class="small">{{ $lead->assignedTo->name }}</span>
                                @if($lead->assigned_at)
                                    <br><span class="text-muted" style="font-size:0.7rem;">{{ $lead->assigned_at->format('M d, Y') }}</span>
                                @endif
                            @else
                                <span class="text-muted">—</span>
                            @endif
                        </td>
                        <td class="text-end">
                            <div class="portal-actions justify-content-end">
                                @if($canAssign)
                                    <button type="button"
                                            class="btn btn-portal-outline btn-assign-marketing"
                                            data-bs-toggle="modal"
                                            data-bs-target="#assignMarketingModal"
                                            data-lead-id="{{ $lead->id }}"
                                            data-lead-name="{{ $lead->displayFairName() ?: 'Lead #' . $lead->id }}"
                                            data-assigned-to="{{ $lead->assigned_to_user_id }}">
                                        Assign
                                    </button>
                                @endif
                                @if(can_access_module('leads.view'))
                                    <a href="{{ route('leads.show', $lead) }}" class="btn btn-portal-primary">View</a>
                                @endif
                                @if(can_access_module('leads.edit'))
                                    <a href="{{ route('leads.edit', $lead) }}" class="btn btn-portal-outline">Edit</a>
                                @endif
                                @if(can_access_module('leads.delete'))
                                    <form method="POST" action="{{ route('leads.destroy', $lead) }}" class="d-inline" onsubmit="return confirm('Delete this lead?');">
                                        @csrf
                                        @method('DELETE')
                                        <button type="submit" class="btn btn-portal-danger">Delete</button>
                                    </form>
                                @endif
                            </div>
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="9">
                            <div class="portal-empty">No leads found. @if(can_access_module('leads.create'))<a href="{{ route('leads.create') }}">Create your first lead</a>.@endif</div>
                        </td>
                    </tr>
                @endforelse
                </tbody>
            </table>
        </div>
    </div>

    @if($canAssign)
        <div class="modal fade" id="assignMarketingModal" tabindex="-1" aria-labelledby="assignMarketingModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-dialog-centered">
                <div class="modal-content border-0 shadow">
                    <form method="POST" id="assignMarketingForm" action="">
                        @csrf
                        <div class="modal-header border-0 pb-0">
                            <h5 class="modal-title fw-bold" id="assignMarketingModalLabel">Assign to marketing</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <p class="text-muted small mb-3">Lead: <strong id="assignLeadName">—</strong></p>
                            @if($marketingUsers->isEmpty())
                                <div class="alert alert-warning mb-0 small">
                                    No marketing users found. Create users in the <strong>Marketing</strong> department first.
                                </div>
                            @else
                                <label class="form-label fw-semibold small">Marketing team member</label>
                                <select name="assigned_to_user_id" id="assignMarketingUser" class="form-select" required>
                                    <option value="">— Select user —</option>
                                    @foreach($marketingUsers as $mu)
                                        <option value="{{ $mu->id }}">{{ $mu->name }} ({{ $mu->email }})</option>
                                    @endforeach
                                </select>
                            @endif
                        </div>
                        <div class="modal-footer border-0 pt-0">
                            <button type="button" class="btn btn-portal-outline" data-bs-dismiss="modal">Cancel</button>
                            @if($marketingUsers->isNotEmpty())
                                <button type="submit" class="btn btn-portal-primary">Assign task</button>
                            @endif
                        </div>
                    </form>
                </div>
            </div>
        </div>
    @endif
@endsection

@if($canAssign)
@push('scripts')
<script>
(function () {
    var modal = document.getElementById('assignMarketingModal');
    if (!modal) return;

    var form = document.getElementById('assignMarketingForm');
    var nameEl = document.getElementById('assignLeadName');
    var userSel = document.getElementById('assignMarketingUser');
    var assignBase = @json(url('/leads'));

    document.querySelectorAll('.btn-assign-marketing').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var leadId = btn.getAttribute('data-lead-id');
            var leadName = btn.getAttribute('data-lead-name');
            var assignedTo = btn.getAttribute('data-assigned-to');

            if (form) {
                form.action = assignBase + '/' + leadId + '/assign-marketing';
            }
            if (nameEl) {
                nameEl.textContent = leadName || 'Lead';
            }
            if (userSel && assignedTo) {
                userSel.value = assignedTo;
            } else if (userSel) {
                userSel.value = '';
            }
        });
    });
})();
</script>
@endpush
@endif
