@extends('layouts.app')
@section('title','Leads — HIGHRA CRM')
@section('header','Lead Management')

@section('content')
<div class="row" style="margin-bottom: 20px;">
    <div>
        <h1 style="margin: 0;">Lead Management</h1>
        <p style="color: #8e9ab4; margin: 4px 0 0;">Track, manage, and filter your sales pipeline prospects.</p>
    </div>
    <div style="display: flex; gap: 8px;">
        @if(auth()->user()?->hasPermission('leads.export'))
            <a href="{{ route('exports.leads') }}" class="btn btn-secondary">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
                Export CSV
            </a>
        @endif
        @if(auth()->user()?->hasPermission('leads.create'))
            <a href="{{ route('leads.create') }}" class="btn">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                New Lead
            </a>
        @endif
    </div>
</div>

<!-- FILTER & SEARCH FORM -->
<form id="leadFilterForm" method="GET" action="{{ route('leads.index') }}">

    <!-- ALIGNED FILTER TOOLBAR -->
    <div class="filter-toolbar">
        <div class="filter-grid" style="grid-template-columns: repeat(auto-fit, minmax(170px, 1fr));">
            <!-- 1. Search Keyword -->
            <div class="filter-group" style="grid-column: span 2;">
                <label>Search Lead</label>
                <input type="text" name="search" value="{{ request('search') }}" placeholder="Search name, phone, email, or code...">
            </div>

            <!-- 2. Status Filter -->
            <div class="filter-group">
                <label>Status</label>
                <select name="status" onchange="this.form.submit()">
                    <option value="">All Statuses</option>
                    <option value="new" {{ request('status') == 'new' ? 'selected' : '' }}>New</option>
                    <option value="contacted" {{ request('status') == 'contacted' ? 'selected' : '' }}>Contacted</option>
                    <option value="qualified" {{ request('status') == 'qualified' ? 'selected' : '' }}>Qualified</option>
                    <option value="won" {{ request('status') == 'won' ? 'selected' : '' }}>Won</option>
                    <option value="lost" {{ request('status') == 'lost' ? 'selected' : '' }}>Lost</option>
                </select>
            </div>

            <!-- 3. Source Filter -->
            <div class="filter-group">
                <label>Source</label>
                <select name="source" onchange="this.form.submit()">
                    <option value="">All Sources</option>
                    <option value="manual" {{ request('source') == 'manual' ? 'selected' : '' }}>Manual</option>
                    <option value="facebook" {{ request('source') == 'facebook' ? 'selected' : '' }}>Facebook</option>
                    <option value="instagram" {{ request('source') == 'instagram' ? 'selected' : '' }}>Instagram</option>
                    <option value="website" {{ request('source') == 'website' ? 'selected' : '' }}>Website</option>
                    <option value="whatsapp" {{ request('source') == 'whatsapp' ? 'selected' : '' }}>WhatsApp</option>
                    <option value="referral" {{ request('source') == 'referral' ? 'selected' : '' }}>Referral</option>
                </select>
            </div>

            <!-- 4. Assigned To Filter -->
            <div class="filter-group">
                <label>Assigned Executive</label>
                <select name="assigned_to" onchange="this.form.submit()">
                    <option value="">All Executives</option>
                    @if(isset($users))
                        @foreach($users as $user)
                            <option value="{{ $user->id }}" {{ request('assigned_to') == $user->id ? 'selected' : '' }}>
                                {{ $user->name }}
                            </option>
                        @endforeach
                    @endif
                </select>
            </div>

            <!-- 5. Filter Actions -->
            <div class="filter-group filter-actions">
                <button type="submit" class="btn btn-secondary btn-sm" style="padding: 9px 16px;">Filter</button>
                @if(request('search') || request('status') || request('source') || request('assigned_to') || request('sort') || request('per_page'))
                    <a href="{{ route('leads.index') }}" class="btn btn-secondary btn-sm" style="padding: 9px 12px; text-decoration: none;" title="Reset all filters">Reset</a>
                @endif
            </div>
        </div>
    </div>

    <!-- LEADS TABLE PANEL -->
    <div class="panel" style="margin-top: 0;">
        <table>
            <thead>
                <tr>
                    <!-- Lead Name Column Sort -->
                    <th class="sortable">
                        @php
                            $nextNameSort = ($sortBy ?? '') == 'name_asc' ? 'name_desc' : 'name_asc';
                            $isNameActive = in_array(($sortBy ?? ''), ['name_asc', 'name_desc']);
                        @endphp
                        <a href="{{ request()->fullUrlWithQuery(['sort' => $nextNameSort]) }}" title="Sort by Lead Name">
                            Lead Name
                            <span class="sort-icon">
                                <span class="{{ ($sortBy ?? '') == 'name_asc' ? 'active-arrow' : '' }}">▲</span>
                                <span class="{{ ($sortBy ?? '') == 'name_desc' ? 'active-arrow' : '' }}">▼</span>
                            </span>
                        </a>
                    </th>

                    <th>Contact Info</th>

                    <!-- Source Column Sort -->
                    <th class="sortable">
                        @php
                            $nextSourceSort = ($sortBy ?? '') == 'source_asc' ? 'source_desc' : 'source_asc';
                        @endphp
                        <a href="{{ request()->fullUrlWithQuery(['sort' => $nextSourceSort]) }}" title="Sort by Source">
                            Source
                            <span class="sort-icon">
                                <span class="{{ ($sortBy ?? '') == 'source_asc' ? 'active-arrow' : '' }}">▲</span>
                                <span class="{{ ($sortBy ?? '') == 'source_desc' ? 'active-arrow' : '' }}">▼</span>
                            </span>
                        </a>
                    </th>

                    <!-- Expected Value Column Sort -->
                    <th class="sortable">
                        @php
                            $nextValueSort = ($sortBy ?? '') == 'value_desc' ? 'value_asc' : 'value_desc';
                        @endphp
                        <a href="{{ request()->fullUrlWithQuery(['sort' => $nextValueSort]) }}" title="Sort by Expected Value">
                            Expected Value
                            <span class="sort-icon">
                                <span class="{{ ($sortBy ?? '') == 'value_asc' ? 'active-arrow' : '' }}">▲</span>
                                <span class="{{ ($sortBy ?? '') == 'value_desc' ? 'active-arrow' : '' }}">▼</span>
                            </span>
                        </a>
                    </th>

                    <!-- Status Column Sort -->
                    <th class="sortable">
                        @php
                            $nextStatusSort = ($sortBy ?? '') == 'status_asc' ? 'status_desc' : 'status_asc';
                        @endphp
                        <a href="{{ request()->fullUrlWithQuery(['sort' => $nextStatusSort]) }}" title="Sort by Status">
                            Status
                            <span class="sort-icon">
                                <span class="{{ ($sortBy ?? '') == 'status_asc' ? 'active-arrow' : '' }}">▲</span>
                                <span class="{{ ($sortBy ?? '') == 'status_desc' ? 'active-arrow' : '' }}">▼</span>
                            </span>
                        </a>
                    </th>

                    <!-- Assigned Executive Column Sort -->
                    <th class="sortable">
                        @php
                            $nextAssigneeSort = ($sortBy ?? '') == 'assignee_asc' ? 'assignee_desc' : 'assignee_asc';
                        @endphp
                        <a href="{{ request()->fullUrlWithQuery(['sort' => $nextAssigneeSort]) }}" title="Sort by Assigned Executive">
                            Assigned To
                            <span class="sort-icon">
                                <span class="{{ ($sortBy ?? '') == 'assignee_asc' ? 'active-arrow' : '' }}">▲</span>
                                <span class="{{ ($sortBy ?? '') == 'assignee_desc' ? 'active-arrow' : '' }}">▼</span>
                            </span>
                        </a>
                    </th>

                    <th style="text-align: right;">Actions</th>
                </tr>
            </thead>
            <tbody>
                @forelse($leads as $lead)
                <tr>
                    <td>
                        <strong style="color: #fff; display: block; font-size: 15px;">{{ $lead->name }}</strong>
                        <small style="color: #8e9ab4;">{{ $lead->lead_code ?? 'LD-#'.$lead->id }}</small>
                    </td>
                    <td>
                        <div style="font-size: 13px;">
                            @if($lead->phone)
                                <div style="color: #edf1ff;">📞 {{ $lead->phone }}</div>
                            @endif
                            @if($lead->email)
                                <div style="color: #8e9ab4;">✉️ {{ $lead->email }}</div>
                            @endif
                            @if(!$lead->phone && !$lead->email)
                                <span style="color: #64748b;">No contact info</span>
                            @endif
                        </div>
                    </td>
                    <td>
                        <span style="background: #162038; border: 1px solid #28375c; color: #a5b4fc; padding: 3px 8px; border-radius: 6px; font-size: 12px; text-transform: capitalize;">
                            {{ $lead->source }}
                        </span>
                    </td>
                    <td>
                        <strong style="color: #6ee7b7; font-size: 14px;">
                            {{ $lead->expected_value ? format_inr($lead->expected_value) : '—' }}
                        </strong>
                    </td>
                    <td>
                        @php
                            $statusClass = match(strtolower($lead->status)) {
                                'new' => 'badge-active',
                                'contacted' => 'badge-manager',
                                'qualified' => 'badge-admin',
                                'won' => 'badge-sales',
                                'lost' => 'badge-inactive',
                                default => 'badge-secondary'
                            };
                        @endphp
                        <span class="badge {{ $statusClass }}">
                            {{ ucfirst($lead->status) }}
                        </span>
                    </td>
                    <td>
                        <span style="color: #cbd5e1; font-size: 13px;">
                            {{ $lead->assignee->name ?? 'Unassigned' }}
                        </span>
                    </td>
                    <td style="text-align: right;">
                        <div style="display: inline-flex; gap: 6px;">
                            <a href="{{ route('leads.show', $lead) }}" class="btn btn-secondary btn-sm">View</a>
                            @if(auth()->user()?->hasPermission('leads.edit'))
                                <a href="{{ route('leads.edit', $lead) }}" class="btn btn-secondary btn-sm">Edit</a>
                            @endif
                            @if(auth()->user()?->hasPermission('leads.delete'))
                                <form method="POST" action="{{ route('leads.destroy', $lead) }}" onsubmit="return confirm('Delete lead {{ $lead->name }}?');" style="display:inline;">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn btn-danger btn-sm" style="padding: 4px 7px;" title="Delete Lead">✕</button>
                                </form>
                            @endif
                        </div>
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="7" style="text-align: center; padding: 36px; color: #8e9ab4;">
                        No leads found matching your selected filters.
                    </td>
                </tr>
                @endforelse
            </tbody>
        </table>

        <!-- PAGINATION & SHOW ENTRIES FOOTER -->
        <div class="pagination-wrapper">
            <div class="pagination-left">
                <!-- Bottom Entries Selector -->
                <div class="entries-select-wrapper">
                    <span>Show</span>
                    <select name="per_page" onchange="this.form.submit()">
                        <option value="10" {{ ($perPageInput ?? '20') == '10' ? 'selected' : '' }}>10</option>
                        <option value="20" {{ ($perPageInput ?? '20') == '20' ? 'selected' : '' }}>20</option>
                        <option value="50" {{ ($perPageInput ?? '20') == '50' ? 'selected' : '' }}>50</option>
                        <option value="100" {{ ($perPageInput ?? '20') == '100' ? 'selected' : '' }}>100</option>
                        <option value="all" {{ ($perPageInput ?? '20') == 'all' ? 'selected' : '' }}>All</option>
                    </select>
                    <span>entries</span>
                </div>

                <!-- Record Count Statistics -->
                @if($leads->total() > 0)
                    <div style="margin-left: 10px;">
                        @if(($perPageInput ?? '20') === 'all')
                            Showing all <strong>{{ $leads->total() }}</strong> leads
                        @else
                            Showing <strong>{{ $leads->firstItem() }}</strong> to <strong>{{ $leads->lastItem() }}</strong> of <strong>{{ $leads->total() }}</strong> leads
                        @endif
                    </div>
                @endif
            </div>

            <!-- Page Number Links (hidden if 'all' selected) -->
            @if(($perPageInput ?? '20') !== 'all' && $leads->hasPages())
                <div class="pagination-container">
                    {{ $leads->links() }}
                </div>
            @endif
        </div>
    </div>
</form>
@endsection
