@extends('layouts.master')

@section('title', 'Add Client - Prolex Law Firm')

@section('content')
<style>
    .container {
        max-width: 1200px;
        margin: 40px auto;
        background-color: #f8fafc;
        padding: 30px;
        border-radius: 12px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }

    h1 {
        text-align: center;
        color: #1e40af;
        margin-bottom: 30px;
        font-size: 2.5rem;
        font-weight: 700;
    }

    .form-section {
        background: white;
        border-radius: 8px;
        padding: 25px;
        margin-bottom: 25px;
        border: 1px solid #e2e8f0;
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
    }

    .section-title {
        color: #2d3748;
        font-size: 1.5rem;
        font-weight: 600;
        margin-bottom: 20px;
        border-bottom: 2px solid #e2e8f0;
        padding-bottom: 10px;
    }

    .form-group {
        margin-bottom: 20px;
    }

    .form-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
        gap: 20px;
    }

    label {
        display: block;
        margin-bottom: 8px;
        font-weight: 600;
        color: #4a5568;
        font-size: 0.95rem;
    }

    input, select, textarea {
        width: 100%;
        padding: 12px 16px;
        border: 2px solid #e2e8f0;
        border-radius: 6px;
        font-size: 1rem;
        transition: all 0.3s ease;
        background-color: #ffffff;
    }

    input:focus, select:focus, textarea:focus {
        outline: none;
        border-color: #3b82f6;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
    }

    textarea {
        resize: vertical;
        min-height: 100px;
    }

    .required::after {
        content: ' *';
        color: #e53e3e;
    }

    .submit-btn {
        background: linear-gradient(135deg, #3b82f6, #1d4ed8);
        color: white;
        padding: 15px 40px;
        border: none;
        border-radius: 8px;
        font-size: 1.1rem;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4px 6px rgba(59, 130, 246, 0.3);
    }

    .submit-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(59, 130, 246, 0.4);
    }

    .submit-btn:active {
        transform: translateY(0);
    }

    .refresh-btn {
        background: linear-gradient(135deg, #6b7280, #4b5563);
        color: white;
        padding: 15px 40px;
        border: none;
        border-radius: 8px;
        font-size: 1.1rem;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4px 6px rgba(107, 114, 128, 0.3);
    }

    .refresh-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 12px rgba(107, 114, 128, 0.4);
    }

    .refresh-btn:active {
        transform: translateY(0);
    }

    .lawyer-dropdown {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        background: white;
        border: 1px solid #e2e8f0;
        border-radius: 6px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        max-height: 200px;
        overflow-y: auto;
        z-index: 1000;
        display: none;
    }

    .lawyer-item {
        padding: 10px 16px;
        cursor: pointer;
        border-bottom: 1px solid #f1f5f9;
        transition: background-color 0.2s ease;
    }

    .lawyer-item:hover {
        background-color: #f8fafc;
    }

    .lawyer-item:last-child {
        border-bottom: none;
    }

    .lawyer-search {
        position: relative;
    }

    @media (max-width: 768px) {
        .container {
            margin: 20px;
            padding: 20px;
        }

        .form-row {
            grid-template-columns: 1fr;
        }

        h1 {
            font-size: 2rem;
        }
    }
</style>

<div class="container">
    <h1>Add New Client</h1>

    @if(session('success'))
        <div style="background-color: #d1fae5; color: #065f46; padding: 15px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #a7f3d0;">
            {{ session('success') }}
        </div>
    @endif

    @if($errors->any())
        <div style="background-color: #fee2e2; color: #991b1b; padding: 15px; border-radius: 6px; margin-bottom: 20px; border: 1px solid #fecaca;">
            <ul style="margin: 0; padding-left: 20px;">
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form id="clientForm" action="{{ route('clients.store') }}" method="POST" enctype="multipart/form-data" novalidate>
        @csrf
        <!-- Core Identifiers -->
        <div class="form-section">
            <h2 class="section-title">Core Identifiers</h2>
            <div class="form-row">
                <div class="form-group">
                    <label for="client_id" class="required">Client ID</label>
                    <input type="text" id="client_id" name="client_id" style="background-color: #ffffff;" required>
                </div>
                <div class="form-group">
                    <label for="first_name" class="required">First Name</label>
                    <input type="text" id="first_name" name="first_name" required>
                </div>
                <div class="form-group">
                    <label for="last_name" class="required">Last Name</label>
                    <input type="text" id="last_name" name="last_name" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="national_id_passport">National ID / Passport Number</label>
                    <input type="text" id="national_id_passport" name="national_id_passport">
                </div>
                <div class="form-group">
                    <label for="date_of_birth">Date of Birth</label>
                    <input type="date" id="date_of_birth" name="date_of_birth">
                </div>
                <div class="form-group">
                    <label for="gender">Gender</label>
                    <select id="gender" name="gender">
                        <option value="">Select Gender</option>
                        <option value="Male">Male</option>
                        <option value="Female">Female</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Contact Information -->
        <div class="form-section">
            <h2 class="section-title">Contact Information</h2>
            <div class="form-row">
                <div class="form-group">
                    <label for="phone_primary">Phone Number (Primary)</label>
                    <input type="tel" id="phone_primary" name="phone_primary" placeholder="+263 123 456 789">
                </div>
                <div class="form-group">
                    <label for="email">Email Address</label>
                    <input type="email" id="email" name="email" placeholder="client@example.com">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="address_street">Street Address</label>
                    <input type="text" id="address_street" name="address_street" placeholder="123 Main Street">
                </div>
                <div class="form-group">
                    <label for="address_city">City</label>
                    <input type="text" id="address_city" name="address_city" placeholder="Harare">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="address_state">State / Province</label>
                    <input type="text" id="address_state" name="address_state" placeholder="Mashonaland East">
                </div>
                <div class="form-group">
                    <label for="address_country">Country</label>
                    <input type="text" id="address_country" name="address_country" placeholder="Zimbabwe">
                </div>
            </div>
        </div>

        <!-- Professional / Legal Context -->
        <div class="form-section">
            <h2 class="section-title">Professional / Legal Context</h2>
            <div class="form-row">
                <div class="form-group">
                    <label for="occupation_company"> Employer name</label>
                    <input type="text" id="occupation_company" name="occupation_company" placeholder="Software Engineer or ABC Corporation">
                </div>
                <div class="form-group">
                    <label for="position_role">Position / Role</label>
                    <input type="text" id="position_role" name="position_role" placeholder="Senior Developer or CEO">
                </div>
                <div class="form-group">
                    <label for="client_type">Client Type</label>
                    <select id="client_type" name="client_type">
                        <option value="">Select Client Type</option>
                        <option value="IND">IND – Individual clients</option>
                        <option value="CORP">CORP – Corporate clients</option>
                        <option value="GOVT">GOVT – Government clients</option>
                        <option value="NGO">NGO – Non-Governmental Organizations</option>
                        <option value="SME">SME – Small and Medium Enterprises</option>
                        <option value="FIN">FIN – Financial institutions / banks</option>
                        <option value="REAL">REAL – Real estate clients</option>
                        <option value="LEG">LEG – Legal entity clients (trusts, estates)</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="client_category">Client Category</label>
                    <select id="client_category" name="client_category">
                        <option value="">Select Client Category</option>
                        @foreach($categories as $category)
                            <option value="{{ $category->category_code }}">{{ $category->category_description }}</option>
                        @endforeach
                    </select>
                </div>
            </div>
        </div>

        <!-- Engagement Details -->
        <div class="form-section">
            <h2 class="section-title">Engagement Details</h2>
            <div class="form-row">
                <div class="form-group">
                    <label for="date_onboarding">Date of Onboarding</label>
                    <input type="date" id="date_onboarding" name="date_onboarding" value="{{ date('Y-m-d') }}">
                </div>
                <div class="form-group">
                    <label for="assigned_lawyer_case_manager_display">Assigned Lawyer / Case Manager</label>
                    <div class="lawyer-search">
                        <input type="text" id="assigned_lawyer_case_manager_display" name="assigned_lawyer_case_manager_display" placeholder="Search for lawyer..." autocomplete="off">
                        <input type="hidden" id="assigned_lawyer_case_manager" name="assigned_lawyer_case_manager" value="">
                        <div class="lawyer-dropdown" id="assigned_lawyer_dropdown"></div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="referred_lawyer_display">Referred Lawyer</label>
                    <div class="lawyer-search">
                        <input type="text" id="referred_lawyer_display" name="referred_lawyer_display" placeholder="Search for lawyer..." autocomplete="off">
                        <input type="hidden" id="referred_lawyer_hidden" name="referred_lawyer" value="">
                        <div class="lawyer-dropdown" id="referred_lawyer_dropdown"></div>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label for="notes_remarks">Notes / Remarks</label>
                <textarea id="notes_remarks" name="notes_remarks" placeholder="Additional notes about the client..."></textarea>
            </div>
        </div>

        <div style="display: flex; justify-content: center; gap: 20px; margin-top: 30px;">
            <button type="submit" class="submit-btn">Save</button>
            <button type="button" class="refresh-btn" onclick="document.getElementById('clientForm').reset(); document.getElementById('client_id').value = generateClientId();">Refresh</button>
            <button type="button" class="refresh-btn" onclick="window.location.href='{{ route('modules.edit.clients') }}'">Back</button>
        </div>
    </form>

    <!-- Clients Table Section -->
    <div class="form-section">
        <h2 class="section-title">Clients List</h2>

        <input type="search" id="clientSearch" placeholder="Search clients..."
            class="search-input" style="width: 100%; padding: 12px 16px; border: 2px solid #e2e8f0; border-radius: 6px; font-size: 1rem; margin-bottom: 20px;">

        <div class="table-container" style="overflow-x: auto; border-radius: 8px; border: 1px solid #e2e8f0;">
            <table id="clientsTable" style="width: 100%; border-collapse: collapse; background: white;">
                <thead>
                    <tr style="background: #f8fafc; border-bottom: 2px solid #e2e8f0;">
                        <th style="padding: 15px; text-align: left; font-weight: 600; color: #2d3748; border-right: 1px solid #e2e8f0;">Client ID</th>
                        <th style="padding: 15px; text-align: left; font-weight: 600; color: #2d3748; border-right: 1px solid #e2e8f0;">Name</th>
                        <th style="padding: 15px; text-align: left; font-weight: 600; color: #2d3748; border-right: 1px solid #e2e8f0;">Contact</th>
                        <th style="padding: 15px; text-align: left; font-weight: 600; color: #2d3748; border-right: 1px solid #e2e8f0;">Client Type</th>
                        <th style="padding: 15px; text-align: left; font-weight: 600; color: #2d3748; border-right: 1px solid #e2e8f0;">Occupation</th>
                        <th style="padding: 15px; text-align: left; font-weight: 600; color: #2d3748; border-right: 1px solid #e2e8f0;">Assigned To</th>
                        <th style="padding: 15px; text-align: left; font-weight: 600; color: #2d3748;">Actions</th>
                    </tr>
                </thead>
                <tbody id="clientsTableBody">
                    @foreach($clients ?? [] as $client)
                        <tr style="border-bottom: 1px solid #e2e8f0;">
                            <td style="padding: 15px; border-right: 1px solid #e2e8f0;">{{ $client->client_id ?? 'N/A' }}</td>
                            <td style="padding: 15px; border-right: 1px solid #e2e8f0;">
                                <div style="font-weight: 600; color: #2d3748;">{{ $client->first_name }} {{ $client->last_name }}</div>
                                <div style="font-size: 0.875rem; color: #718096;">{{ $client->national_id ?? 'N/A' }}</div>
                            </td>
                            <td style="padding: 15px; border-right: 1px solid #e2e8f0;">
                                <div>{{ $client->phone_primary ?? 'N/A' }}</div>
                                <div style="font-size: 0.875rem; color: #718096;">{{ $client->email ?? 'N/A' }}</div>
                            </td>
                            <td style="padding: 15px; border-right: 1px solid #e2e8f0;">{{ $client->client_type ?? 'N/A' }}</td>
                            <td style="padding: 15px; border-right: 1px solid #e2e8f0;">
                                <div>{{ $client->employer_name ?? 'N/A' }}</div>
                                <div style="font-size: 0.875rem; color: #718096;">{{ $client->position_role ?? '' }}</div>
                            </td>
                            <td style="padding: 15px; border-right: 1px solid #e2e8f0;">{{ $client->assigned_lawyer ?? 'N/A' }}</td>
                            <td style="padding: 15px;">
                                <a href="{{ route('clients.edit', $client->id) }}" style="background: #3b82f6; color: white; text-decoration: none; padding: 6px 12px; border-radius: 4px; font-size: 0.875rem; margin-right: 5px;">Edit</a>
                                <form action="{{ route('clients.destroy', $client->id) }}" method="POST" style="display: inline;">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" style="background: #e53e3e; color: white; border: none; padding: 6px 12px; border-radius: 4px; cursor: pointer; font-size: 0.875rem;" onclick="return confirm('Are you sure you want to delete this client?')">Delete</button>
                                </form>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>

        <div id="noClientsMessage" style="text-align: center; padding: 40px; color: #718096; font-style: italic;">
            No clients added yet. Fill the form above and click "Add Client" to get started.
        </div>
    </div>
</div>

<script>
    // Generate next client ID
    function generateClientId() {
        // Generate a unique client ID with better uniqueness
        const timestamp = Date.now();
        const random = Math.floor(Math.random() * 1000);
        return 'CL' + String(timestamp).slice(-4) + String(random).padStart(3, '0');
    }

    // Initialize client ID on page load
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('client_id').value = generateClientId();
    });

    // Search functionality
    document.getElementById('clientSearch').addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        const rows = document.querySelectorAll('#clientsTableBody tr');

        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(searchTerm) ? '' : 'none';
        });
    });

    // Lawyer search functionality
    document.addEventListener('DOMContentLoaded', function() {
        const lawyerInputs = document.querySelectorAll('.lawyer-search input[type="text"]');
        const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || '{{ csrf_token() }}';

        lawyerInputs.forEach(input => {
            const hiddenInput = input.nextElementSibling;
            const dropdown = input.nextElementSibling.nextElementSibling;
            let timeout;

            input.addEventListener('input', function() {
                clearTimeout(timeout);
                const query = this.value.trim();

                // Clear hidden input if visible input is cleared
                if (query.length === 0) {
                    hiddenInput.value = '';
                    dropdown.style.display = 'none';
                    return;
                }

                if (query.length < 2) {
                    dropdown.style.display = 'none';
                    return;
                }

                timeout = setTimeout(() => {
                    fetch(`/modules/api/lawyers/search?q=${encodeURIComponent(query)}`, {
                        method: 'GET',
                        headers: {
                            'X-CSRF-TOKEN': csrfToken,
                            'Accept': 'application/json'
                        }
                    })
                    .then(response => response.json())
                    .then(data => {
                        dropdown.innerHTML = '';

                        if (data.length > 0) {
                            data.forEach(lawyer => {
                                const item = document.createElement('div');
                                item.className = 'lawyer-item';
                                item.textContent = lawyer.full_name;
                                item.dataset.id = lawyer.lawyer_id;
                                item.addEventListener('click', function() {
                                    input.value = lawyer.full_name;
                                    hiddenInput.value = lawyer.lawyer_id;
                                    dropdown.style.display = 'none';
                                });
                                dropdown.appendChild(item);
                            });
                            dropdown.style.display = 'block';
                        } else {
                            dropdown.style.display = 'none';
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching lawyers:', error);
                        dropdown.style.display = 'none';
                    });
                }, 300);
            });

            // Hide dropdown when clicking outside
            document.addEventListener('click', function(e) {
                if (!input.contains(e.target) && !dropdown.contains(e.target)) {
                    dropdown.style.display = 'none';
                }
            });
        });
    });
</script>
@endsection

