@extends('layouts.master')

@section('title', 'Add Case - ')

@section('content')
<style>
:root{--sky:#0ea5e9;--sky-deep:#0369a1;--sky-ghost:rgba(14,165,233,.07);--sky-border:rgba(14,165,233,.2);--ink-mid:#3f4a5a;--white:#fff;--off:#f7fbff;--surface:#eef6fd;--border:#daeaf8;--danger:#ef4444;--danger-bg:rgba(239,68,68,.08);--danger-border:rgba(239,68,68,.2);--amber:#f59e0b;--amber-bg:rgba(245,158,11,.08);--amber-border:rgba(245,158,11,.22);--fd:'Cormorant Garamond',Georgia,serif;--fb:'DM Sans',system-ui,sans-serif;--fm:'DM Mono',monospace}
.main-content{background:var(--off);font-family:var(--fb)}
.main-content .container,.main-content .tx-page,.main-content .page-wrap,.main-content .content-wrapper,.main-content .wrap{background:var(--white);border:1px solid var(--border);border-radius:16px;box-shadow:0 8px 24px rgba(14,165,233,.1)}
.main-content h1,.main-content h2,.main-content h3{font-family:var(--fd);color:var(--sky-deep)}
.main-content .btn,.main-content .back-btn,.main-content .option-btn,.main-content .submit-btn,.main-content .refresh-btn,.main-content .action-btn,.main-content .act-btn,.main-content .link{border-radius:10px!important;font-family:var(--fb)!important;font-weight:600!important}
.main-content .btn-secondary,.main-content .back-btn,.main-content .refresh-btn,.main-content .btn-muted,.main-content .btn-ghost{background:#fff!important;color:var(--ink-mid)!important;border:1px solid var(--sky-border)!important}
.main-content .btn-primary,.main-content .option-btn,.main-content .submit-btn{background:linear-gradient(135deg,var(--sky-deep),var(--sky))!important;color:#fff!important;border:1px solid var(--sky-deep)!important}
.main-content table,.main-content .table{border-color:var(--border)!important}
.main-content thead,.main-content thead tr,.main-content th,.main-content .table thead th,.main-content .table-head-row{background:var(--surface)!important;color:var(--ink-mid)!important;border-color:var(--border)!important}
.main-content tbody tr:hover,.main-content .tx-row:hover{background:var(--sky-ghost)!important}
.main-content input,.main-content select,.main-content textarea{border:1px solid var(--border)!important;border-radius:10px!important;font-family:var(--fb)!important}
.main-content input:focus,.main-content select:focus,.main-content textarea:focus{border-color:var(--sky)!important;box-shadow:0 0 0 3px rgba(14,165,233,.12)!important}
.main-content .rate-badge,.main-content .badge,.main-content .status-badge{font-family:var(--fm)}
.main-content .actions,.main-content .cell-actions{display:flex;gap:7px;align-items:center;flex-wrap:wrap}
.main-content a[href*='/edit'],.main-content .act-edit,.main-content .btn-warning{background:var(--amber-bg)!important;color:#92400e!important;border:1px solid var(--amber-border)!important}
.main-content .act-delete,.main-content form button[type='submit'].btn-danger,.main-content form button[onclick*='delete']{background:var(--danger-bg)!important;color:#991b1b!important;border:1px solid var(--danger-border)!important}
.main-content a[href*='/show'],.main-content .act-view{background:var(--sky-ghost)!important;color:var(--sky-deep)!important;border:1px solid var(--sky-border)!important}
.conflict-badge{display:inline-flex;align-items:center;padding:6px 12px;border-radius:999px;font-size:12px;font-weight:700;text-transform:uppercase;letter-spacing:.06em}
.conflict-badge.pending{color:#b45309;border:1px solid var(--amber-border);background:var(--amber-bg)}
.conflict-badge.cleared{color:#0f766e;border:1px solid rgba(16,185,129,.2);background:rgba(16,185,129,.1)}
.conflict-badge.conflict{color:#991b1b;border:1px solid var(--danger-border);background:var(--danger-bg)}
.modal-overlay{position:fixed;inset:0;background:rgba(15,23,42,.45);display:none;align-items:center;justify-content:center;z-index:2000;padding:20px}
.modal{background:#fff;border-radius:16px;max-width:720px;width:100%;box-shadow:0 20px 50px rgba(2,132,199,.25);border:1px solid #e2e8f0;padding:20px}
.modal h3{margin:0 0 6px;color:#1e40af;font-size:20px}
.modal p{margin:0 0 14px;color:#475569;font-size:13px}
.modal table{width:100%;border-collapse:collapse}
.modal th{background:#eef6fd;text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:#64748b;padding:10px;border-bottom:1px solid #daeaf8}
.modal td{padding:10px;border-bottom:1px solid #daeaf8;font-size:13px;color:#475569}
.modal-actions{display:flex;gap:10px;justify-content:flex-end;margin-top:14px;flex-wrap:wrap}
</style>
<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);
        overflow: visible;
    }

    .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);
    }

    select {
        background-color: #ffffff !important;
        color: #000000 !important;
        position: relative;
        z-index: 10;
    }

    option {
        background-color: #ffffff !important;
        color: #000000 !important;
    }

    .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);
    }

    .party-row, .lawyer-row, .client-row {
        display: flex;
        gap: 15px;
        align-items: end;
        margin-bottom: 15px;
        padding: 15px;
        background: #f8fafc;
        border-radius: 6px;
        border: 1px solid #e2e8f0;
    }

    .party-row .form-group, .lawyer-row .form-group, .client-row .form-group {
        flex: 1;
        margin-bottom: 0;
    }

    .remove-btn {
        background: #ef4444;
        color: white;
        border: none;
        padding: 8px 12px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 0.9rem;
    }

    .add-btn {
        background: #10b981;
        color: white;
        border: none;
        padding: 10px 20px;
        border-radius: 6px;
        cursor: pointer;
        font-size: 0.95rem;
        margin-top: 10px;
    }

    .hidden {
        display: none;
    }
</style>

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

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

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

    <form action="{{ route('case.store') }}" method="POST" novalidate>
        @csrf
        <input type="hidden" id="caseConflictStatus" name="conflict_status" value="Pending">
        <input type="hidden" id="caseConflictCheckId" name="conflict_check_id" value="">

        <!-- Conflict Check -->
        <div class="form-section">
            <h2 class="section-title">Conflict Check</h2>
            <div class="form-row">
                <div class="form-group">
                    <label for="case_conflict_client_names">Client Names</label>
                    <input type="text" id="case_conflict_client_names" name="client_names" placeholder="Add client names">
                </div>
                <div class="form-group">
                    <label for="case_conflict_opposing_parties">Opposing Parties</label>
                    <input type="text" id="case_conflict_opposing_parties" name="opposing_parties" placeholder="Add opposing parties">
                </div>
                <div class="form-group">
                    <label for="case_conflict_company_names">Company Names</label>
                    <input type="text" id="case_conflict_company_names" name="company_names" placeholder="Add organizations">
                </div>
            </div>
            <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
                <span id="caseConflictBadge" class="conflict-badge pending">Status: Pending</span>
                <button type="button" class="submit-btn" style="padding:10px 16px;" id="runCaseConflictBtn">Run Conflict Search</button>
            </div>
        </div>

        <!-- Case Core Details -->
        <div class="form-section">
            <h2 class="section-title">1️⃣ Core Case Details</h2>
            <div class="form-row">
                <div class="form-group">
                    <label for="case_id" class="required">Case ID</label>
                    <input type="text" id="case_id" name="case_id" value="{{ old('case_id', 'CASE' . str_pad(\App\Models\LegalCase::count() + 1, 3, '0', STR_PAD_LEFT)) }}" required readonly>
                </div>
                <div class="form-group">
                    <label for="case_name" class="required">Case Name</label>
                    <input type="text" id="case_name" name="case_name" value="{{ old('case_name') }}" required>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="category_code" class="required">Category Code</label>
                    <select id="category_code" name="category_code" required>
                        <option value="">Select Case Category</option>
                        @foreach($caseCategories as $category)
                            <option value="{{ $category->category_code }}" {{ old('category_code') == $category->category_code ? 'selected' : '' }}>
                                {{ $category->category_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="form-group">
                    <label for="type_id" class="required">Type ID</label>
                    <select id="type_id" name="type_id" required>
                        <option value="">Select Case Type</option>
                        @foreach($caseTypes as $type)
                            <option value="{{ $type->type_id }}" {{ old('type_id') == $type->type_id ? 'selected' : '' }}>
                                {{ $type->type_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="form-group">
                    <label for="priority_id" class="required">Priority ID</label>
                    <select id="priority_id" name="priority_id" required>
                        <option value="">Select Priority</option>
                        @foreach(\App\Models\CasePriority::all() as $priority)
                            <option value="{{ $priority->priority_id }}" {{ old('priority_id') == $priority->priority_id ? 'selected' : '' }}>
                                {{ $priority->priority_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label for="role_id" class="required">Role ID</label>
                    <select id="role_id" name="role_id" required>
                        <option value="">Select Role</option>
                        @foreach($caseRoles as $role)
                            <option value="{{ $role->role_id }}" {{ old('role_id') == $role->role_id ? 'selected' : '' }}>
                                {{ $role->role_name }}
                            </option>
                        @endforeach
                    </select>
                </div>
            </div>
        </div>

        <!-- Clients -->
        <div class="form-section">
            <h2 class="section-title">2️⃣ Clients</h2>
            <div id="clients-container"></div>
            <button type="button" class="add-btn" onclick="addClientRow()">Add Client</button>
        </div>

        <!-- Assigned Lawyers -->
        <div class="form-section">
            <h2 class="section-title">3️⃣ Assigned Lawyers</h2>
            <div id="lawyers-container">
                <!-- Dynamic lawyer rows will be added here -->
            </div>
            <button type="button" class="add-btn" onclick="addLawyerRow()">Add Lawyer</button>
        </div>

        <!-- Dates -->
        <div class="form-section">
            <h2 class="section-title">4️⃣ Dates</h2>
            <div class="form-row">
                <div class="form-group">
                    <label for="date_of_incident">Date of Incident</label>
                    <input type="date" id="date_of_incident" name="date_of_incident" value="{{ old('date_of_incident') }}">
                </div>
                <div class="form-group">
                    <label for="court_appearance_date">Court Appearance Date</label>
                    <input type="date" id="court_appearance_date" name="court_appearance_date" value="{{ old('court_appearance_date') }}">
                </div>
            </div>
        </div>

        <!-- Notes -->
        <div class="form-section">
            <h2 class="section-title">5️⃣ Notes</h2>
            <div class="form-group">
                <label for="notes">Notes</label>
                <textarea id="notes" name="notes" rows="4" placeholder="Internal remarks, optional">{{ old('notes') }}</textarea>
            </div>
        </div>

        <div style="text-align: center; margin-top: 30px;">
            <button type="button" class="submit-btn" style="background: linear-gradient(135deg, #6b7280, #4b5563); margin-right: 15px;" onclick="clearForm()">Clear Form</button>
            <button type="submit" class="submit-btn">Save Case</button>
        </div>
    </form>
</div>

<div id="caseConflictModal" class="modal-overlay" aria-hidden="true">
    <div class="modal" role="dialog" aria-modal="true" aria-labelledby="caseConflictModalTitle">
        <h3 id="caseConflictModalTitle">Conflict Check Results</h3>
        <p id="caseConflictModalSummary">Review the matches found during the conflict search.</p>
        <div id="caseConflictResultsWrap"></div>
        <div class="modal-actions">
            <button type="button" class="submit-btn" style="background:#fff;color:#475569;border:1px solid #daeaf8;" id="caseConflictModalClose">Close</button>
        </div>
    </div>
</div>

<script>
let lawyerIndex = 0;
let clientIndex = 0;

function addClientRow() {
    const container = document.getElementById('clients-container');
    const row = document.createElement('div');
    row.className = 'client-row';
    row.innerHTML = `
        <div class="form-group">
            <label>Client</label>
            <select name="clients[${clientIndex}][client_id]" required>
                <option value="">Select Client</option>
                @foreach($clients as $client)
                    <option value="{{ $client->id }}">{{ $client->full_name }} ({{ $client->client_id }})</option>
                @endforeach
            </select>
        </div>
        <div class="form-group">
            <label>Role (optional)</label>
            <select name="clients[${clientIndex}][role_code]">
                <option value="">Select Role</option>
                @foreach($caseRoles as $role)
                    <option value="{{ $role->role_name }}">{{ $role->role_name }}</option>
                @endforeach
            </select>
        </div>
        <button type="button" class="remove-btn" onclick="removeRow(this)">Remove</button>
    `;
    container.appendChild(row);
    clientIndex++;
}

function addLawyerRow() {
    const container = document.getElementById('lawyers-container');
    const row = document.createElement('div');
    row.className = 'lawyer-row';
    row.innerHTML = `
        <div class="form-group">
            <label>Lawyer ID</label>
            <select name="lawyers[${lawyerIndex}][lawyer_id]" required>
                <option value="">Select Lawyer</option>
                @foreach($lawyers as $lawyer)
                    <option value="{{ $lawyer->lawyer_id }}">{{ $lawyer->full_name }} ({{ $lawyer->lawyer_tier ?? 'N/A' }})</option>
                @endforeach
            </select>
        </div>
        <div class="form-group">
            <label>Role</label>
            <select name="lawyers[${lawyerIndex}][role]" required>
                <option value="">Select Role</option>
                @foreach(\App\Models\LawyerRole::all() as $role)
                    <option value="{{ $role->code }}">{{ $role->name }}</option>
                @endforeach
            </select>
        </div>
        <button type="button" class="remove-btn" onclick="removeRow(this)">Remove</button>
    `;
    container.appendChild(row);
    lawyerIndex++;
}

function removeRow(button) {
    button.parentElement.remove();
}

// Initialize with one lawyer row
document.addEventListener('DOMContentLoaded', function() {
    addClientRow();
    addLawyerRow();
});

function clearForm() {
    // Clear all input fields except readonly ones
    const inputs = document.querySelectorAll('input:not([readonly]), select, textarea');
    inputs.forEach(input => {
        if (input.type === 'date') {
            // Reset date to today
            input.value = new Date().toISOString().split('T')[0];
        } else {
            input.value = '';
        }
    });

    // Clear dynamic client and lawyer rows
    const clientsContainer = document.getElementById('clients-container');
    const lawyersContainer = document.getElementById('lawyers-container');

    // Remove all existing rows
    clientsContainer.innerHTML = '';
    lawyersContainer.innerHTML = '';

    // Reset index
    clientIndex = 0;
    lawyerIndex = 0;

    // Add back one row
    addClientRow();
    addLawyerRow();
}

(() => {
    const runBtn = document.getElementById('runCaseConflictBtn');
    const badge = document.getElementById('caseConflictBadge');
    const statusInput = document.getElementById('caseConflictStatus');
    const checkIdInput = document.getElementById('caseConflictCheckId');
    const clientInput = document.getElementById('case_conflict_client_names');
    const opposingInput = document.getElementById('case_conflict_opposing_parties');
    const companyInput = document.getElementById('case_conflict_company_names');
    const modal = document.getElementById('caseConflictModal');
    const modalClose = document.getElementById('caseConflictModalClose');
    const resultsWrap = document.getElementById('caseConflictResultsWrap');
    const summary = document.getElementById('caseConflictModalSummary');

    function setBadge(status) {
        badge.classList.remove('pending', 'cleared', 'conflict');
        if (status === 'Cleared') {
            badge.classList.add('cleared');
        } else if (status === 'Conflict Found') {
            badge.classList.add('conflict');
        } else {
            badge.classList.add('pending');
        }
        badge.textContent = `Status: ${status}`;
        if (statusInput) {
            statusInput.value = status;
        }
    }

    function openModal() {
        modal.style.display = 'flex';
        modal.setAttribute('aria-hidden', 'false');
    }

    function closeModal() {
        modal.style.display = 'none';
        modal.setAttribute('aria-hidden', 'true');
    }

    function renderResults(results, status) {
        resultsWrap.innerHTML = '';
        if (!results.length) {
            const empty = document.createElement('div');
            empty.textContent = 'No conflicts found for the provided names.';
            empty.style.fontSize = '13px';
            empty.style.color = '#475569';
            resultsWrap.appendChild(empty);
            summary.textContent = `Status: ${status}. No matching opposing parties were found.`;
            return;
        }

        summary.textContent = `Status: ${status}. ${results.length} potential conflict(s) detected.`;
        const table = document.createElement('table');
        const thead = document.createElement('thead');
        const headRow = document.createElement('tr');
        ['Match Type', 'Matched Name', 'Entity', 'Search Term', 'Context'].forEach((label) => {
            const th = document.createElement('th');
            th.textContent = label;
            headRow.appendChild(th);
        });
        thead.appendChild(headRow);
        table.appendChild(thead);

        const tbody = document.createElement('tbody');
        results.forEach((row) => {
            const tr = document.createElement('tr');
            const matchType = document.createElement('td');
            matchType.textContent = row.match_type || 'match';
            const matchedName = document.createElement('td');
            matchedName.textContent = row.matched_name || '—';
            const entity = document.createElement('td');
            entity.textContent = row.matched_entity_type || '—';
            const term = document.createElement('td');
            term.textContent = row.search_term || '—';
            const context = document.createElement('td');
            const details = Array.isArray(row.details) ? row.details : [];
            if (!details.length) {
                context.textContent = 'No related case found.';
            } else {
                const lines = details.map((detail) => {
                    const parts = [];
                    if (detail.context_ref || detail.context_name) {
                        parts.push(`${detail.context_ref || '—'} · ${detail.context_name || '—'}`);
                    }
                    if (detail.party_name || detail.party_role) {
                        parts.push(`${detail.party_role || 'Party'}: ${detail.party_name || '—'}`);
                    }
                    if (detail.represented_by && detail.represented_by.length) {
                        parts.push(`Represented by: ${detail.represented_by.join(', ')}`);
                    }
                    if (detail.represented_on) {
                        parts.push(`Last activity: ${detail.represented_on}`);
                    }
                    return parts.filter(Boolean).join(' | ');
                });
                context.innerHTML = lines.map((line) => `<div style="margin-bottom:6px;">${line}</div>`).join('');
            }
            tr.appendChild(matchType);
            tr.appendChild(matchedName);
            tr.appendChild(entity);
            tr.appendChild(term);
            tr.appendChild(context);
            tbody.appendChild(tr);
        });
        table.appendChild(tbody);
        resultsWrap.appendChild(table);
    }

    runBtn?.addEventListener('click', async () => {
        runBtn.disabled = true;
        setBadge('Pending');

        const payload = {
            client_names: clientInput.value || '',
            opposing_parties: opposingInput.value || '',
            company_names: companyInput.value || '',
        };

        try {
            const response = await fetch("{{ route('modules.edit.conflicts.run') }}", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name=\"csrf-token\"]').content,
                },
                body: JSON.stringify(payload),
            });

            if (!response.ok) {
                throw new Error(`Conflict check failed with status ${response.status}`);
            }

            const data = await response.json();
            const status = data.status || 'Pending';
            setBadge(status);
            if (checkIdInput) {
                checkIdInput.value = data.check_id || '';
            }
            renderResults(data.results || [], status);
            openModal();
        } catch (error) {
            setBadge('Pending');
            if (checkIdInput) {
                checkIdInput.value = '';
            }
            resultsWrap.innerHTML = '';
            summary.textContent = 'Conflict check failed. Please try again.';
            openModal();
        } finally {
            runBtn.disabled = false;
        }
    });

    modalClose?.addEventListener('click', closeModal);
    modal?.addEventListener('click', (event) => {
        if (event.target === modal) {
            closeModal();
        }
    });
})();
</script>
@endsection



