@extends('layouts.admin')

@section('content')
<div class="card shadow-sm mb-3">

    {{-- ================= HEADER ================= --}}
    <div class="card-header bg-white">
        <div class="d-flex justify-content-between align-items-center">
            <div>
                <a href="{{ route('claims.index') }}" class="btn btn-sm btn-outline-primary">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <h6 class="mt-2 mb-0 text-muted">Claim Details</h6>
                <small class="text-muted">
                    <strong>Reference:</strong>
                    {{ $claim->reference_number ?? 'Pending Assignment' }}
                </small>
            </div>

           <div>
    @if($claim->claim_status === 'Pending')
        <a href="{{ route('claims.edit', $claim->id) }}" class="btn btn-sm btn-warning">
            <i class="fas fa-edit"></i> Edit
        </a>
    @endif

    @if($claim->claim_status === 'Approved')
        <form method="POST"
              action="{{ route('claims.emailUnderwriter', $claim) }}"
              class="d-inline">
            @csrf
            <button class="btn btn-sm btn-primary"
                    onclick="return confirm('Email claim to underwriter?')">
                <i class="fas fa-envelope"></i> Email Underwriter
            </button>
        </form>
    @endif

    <a href="{{ route('claims.print', $claim->id) }}"
       target="_blank"
       class="btn btn-sm btn-secondary">
        <i class="fas fa-print"></i> Print
    </a>
</div>

        </div>
    </div>

    <div class="card-body small text-muted">

        {{-- ================= STATUS ================= --}}
        <p>
    <strong>Status:</strong>
    <span class="badge
        {{ $claim->claim_status === 'Pending' ? 'bg-warning text-dark' : '' }}
        {{ $claim->claim_status === 'Reviewed' ? 'bg-info' : '' }}
        {{ $claim->claim_status === 'Approved' ? 'bg-success' : '' }}
        {{ $claim->claim_status === 'Rejected' ? 'bg-danger' : '' }}">
        {{ $claim->claim_status }}
    </span>
</p>


        <hr>

        {{-- ================= POLICY HOLDER ================= --}}
        <h6 class="text-primary"><i class="fas fa-user-shield"></i> Policy Holder</h6>
        <div class="row">
            <div class="col-md-6">
                <p><strong>Name:</strong> {{ $claim->policyHolder->name }} {{ $claim->policyHolder->surname }}</p>
                <p><strong>National ID:</strong> {{ $claim->policyHolder->national_id }}</p>
            </div>
            <div class="col-md-6">
                <p><strong>Phone:</strong> {{ $claim->policyHolder->cell_number }}</p>
                <p><strong>Email:</strong> {{ $claim->policyHolder->email ?? 'N/A' }}</p>
            </div>
        </div>

        <hr>

        {{-- ================= CLAIMANT ================= --}}
        <h6 class="text-primary"><i class="fas fa-user"></i> Claimant</h6>
        <div class="row">
            <div class="col-md-6">
                <p><strong>Name:</strong> {{ $claim->claimant_full_name }}</p>
                <p><strong>National ID:</strong> {{ $claim->claimant_national_id ?? 'N/A' }}</p>
            </div>
            <div class="col-md-6">
                <p><strong>Phone:</strong> {{ $claim->claimant_phone ?? 'N/A' }}</p>
                <p><strong>Address:</strong> {{ $claim->claimant_address ?? 'N/A' }}</p>
            </div>
        </div>
        <p><strong>Relationship to Policy Holder:</strong> {{ $claim->relationship_to_policyholder }}</p>

        <hr>


        {{-- ================= DECEASED ================= --}}
        <h6 class="text-primary"><i class="fas fa-cross"></i> Deceased</h6>
        <div class="row">
            <div class="col-md-6">
                <p><strong>Name:</strong> {{ $claim->deceased_full_name }}</p>
                <p><strong>National ID:</strong> {{ $claim->deceased_national_id }}</p>
            </div>
            <div class="col-md-6">
                <p><strong>Gender:</strong> {{ $claim->deceased_gender }}</p>
                <p><strong>Date of Birth:</strong> {{ $claim->deceased_date_of_birth }}</p>
            </div>
        </div>
        <p><strong>Deceased Type:</strong> {{ $claim->deceased_type }}</p>

        <hr>

        {{-- ================= CLAIM DETAILS ================= --}}
        <h6 class="text-primary"><i class="fas fa-file-invoice"></i> Claim Information</h6>
        <div class="row">
            <div class="col-md-6">
                <p><strong>Date of Death:</strong> {{ $claim->date_of_death }}</p>
                <p><strong>Cause of Death:</strong> {{ $claim->cause_of_death }}</p>
            </div>
            <div class="col-md-6">
                <p><strong>Remarks:</strong> {{ $claim->remarks ?? 'N/A' }}</p>
            </div>
        </div>

        <hr>

        {{-- ================= PAYOUT ================= --}}
        <h6 class="text-primary"><i class="fas fa-coins"></i> Claim Payout</h6>
        <p><strong>Sum Assured:</strong> {{ number_format($sumAssured, 2) }}</p>
        <p><strong>Percentage Applied:</strong> {{ $percentageApplied }}%</p>
        <p class="fw-bold text-success">
            <strong>Amount Payable:</strong> {{ number_format($amountPayable, 2) }}
        </p>

        <hr>

        {{-- ================= CLAIM DOCUMENTS ================= --}}
        <h6 class="text-primary"><i class="fas fa-folder-open"></i> Documents</h6>

        <div class="progress mb-2" style="height:18px;">
            <div id="docProgress" class="progress-bar bg-warning" style="width:0%">0%</div>
        </div>

        <small id="docCounter" class="text-muted"></small>

        <ul id="requiredDocsList" class="list-group list-group-sm my-3"></ul>

        <table class="table table-sm table-bordered">
            <thead class="table-light">
                <tr>
                    <th>Document</th>
                    <th width="25%">Action</th>
                </tr>
            </thead>
            <tbody>
                @foreach($claim->documents as $doc)
                <tr>
                    <td>{{ $doc->document_type }}</td>
                    <td>
                        <a href="{{ asset($doc->document_path) }}"
                            target="_blank"
                            class="btn btn-sm btn-info">
                            <i class="fas fa-eye"></i>
                        </a>
                        @if($claim->claim_status === 'Pending')
                        <form method="POST"
                            action="{{ route('claims.documents.delete', $doc->id) }}"
                            class="d-inline">
                            @csrf
                            @method('DELETE')
                            <button class="btn btn-sm btn-danger"
                                onclick="return confirm('Delete document?')">
                                <i class="fas fa-trash"></i>
                            </button>
                        </form>
                        @endif
                    </td>
                </tr>
                @endforeach
            </tbody>
        </table>

        {{-- ================= UPLOAD ================= --}}
        @if($claim->claim_status === 'Pending')
        <hr>
        <h6 class="text-primary"><i class="fas fa-upload"></i> Upload Document</h6>

        <form method="POST"
            action="{{ url('claims/'.$claim->id.'/documents') }}"
            enctype="multipart/form-data">
            @csrf

            <div class="row">
                <div class="col-md-6 mb-2">
                    <select id="documentTypeSelect"
                        name="document_type"
                        class="form-control form-control-sm"
                        required></select>
                </div>

                <div class="col-md-6 mb-2">
                    <input type="file"
                        name="document_file"
                        class="form-control form-control-sm"
                        required>
                </div>
            </div>

            <button class="btn btn-sm btn-success">
                <i class="fas fa-upload"></i> Upload
            </button>
        </form>
        @endif

        {{-- ================= REVIEWER ACTIONS ================= --}}
        @if(
        Auth::user()->role == 3 &&
        $claim->claim_status === 'Pending' &&
        $claim->created_by == Auth::id()
        )
        <hr>
        <h6 class="text-warning">
            <i class="fas fa-search"></i> Reviewer Actions
        </h6>

        <form id="reviewForm"
            method="POST"
            action="{{ route('claims.review', $claim) }}"
            class="d-inline">
            @csrf

            <input type="hidden" name="documents_ok" id="documents_ok">
            <input type="hidden" name="comment" id="review_comment">

            <button type="button"
                class="btn btn-sm btn-success"
                onclick="reviewDecision(true)">
                <i class="fas fa-check"></i> Documents OK
            </button>

            <button type="button"
                class="btn btn-sm btn-danger"
                onclick="reviewDecision(false)">
                <i class="fas fa-times"></i> Documents Missing
            </button>
        </form>
        @endif


        {{-- ================= ADMIN ACTIONS ================= --}}
        @if(Auth::user()->role == 3 && $claim->claim_status === 'Reviewed')
        <hr>
        <h6 class="text-primary"><i class="fas fa-user-shield"></i> Admin Actions</h6>

        <button id="approveBtn"
            class="btn btn-sm btn-success"
            disabled
            data-bs-toggle="modal"
            data-bs-target="#approveModal">
            <i class="fas fa-check"></i> Approve
        </button>

        <button id="rejectBtn"
            class="btn btn-sm btn-danger"
            disabled
            data-bs-toggle="modal"
            data-bs-target="#rejectModal">
            <i class="fas fa-times"></i> Reject
        </button>
        @endif

    </div>
</div>

{{-- ================= APPROVE MODAL ================= --}}
<div class="modal fade" id="approveModal">
    <div class="modal-dialog modal-sm">
        <form method="POST" action="{{ route('claims.approve', $claim->id) }}">
            @csrf
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h6 class="modal-title">Approve Claim</h6>
                </div>
                <div class="modal-body">
                    <textarea name="comment" class="form-control"
                        placeholder="Approval comment (optional)"></textarea>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-success btn-sm">Approve</button>
                </div>
            </div>
        </form>
    </div>
</div>

{{-- ================= REJECT MODAL ================= --}}
<div class="modal fade" id="rejectModal">
    <div class="modal-dialog modal-sm">
        <form method="POST" action="{{ route('claims.reject', $claim->id) }}">
            @csrf
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h6 class="modal-title">Reject Claim</h6>
                </div>
                <div class="modal-body">
                    <textarea name="comment" class="form-control"
                        placeholder="Reason for rejection" required></textarea>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-danger btn-sm">Reject</button>
                </div>
            </div>
        </form>
    </div>
</div>

{{-- ================= JAVASCRIPT RULE ENGINE ================= --}}

<script>
    const relationship = "{{ $claim->relationship_to_policyholder }}";

    const uploadedDocs = @json(
        $claim->documents->pluck('document_type')->toArray()
    );

    const rules = {
        Spouse: [
            "Mortuary Letter", "Letter from Umphakatsi", "Doctor’s Report",
            "ID of Deceased", "Death Certificate", "Marriage Certificate",
            "Claimant ID", "Bank Details"
        ],
        Child: [
            "Letter from Umphakatsi", "Doctor’s Report", "Death Certificate",
            "ID of Deceased", "Linking Birth Certificates", "Mortuary Letter",
            "Bank Details"
        ],
        Sibling: [
            "Letter from Umphakatsi", "Doctor’s Report", "Death Certificate",
            "ID of Deceased", "Linking Birth Certificates", "Mortuary Letter",
            "Bank Details"
        ],
        Mother: [
            "Letter from Umphakatsi", "Doctor’s Report", "Death Certificate",
            "ID of Deceased", "Claimant ID", "Mortuary Letter", "Bank Details"
        ],
        Father: [
            "Letter from Umphakatsi", "Doctor’s Report", "Death Certificate",
            "ID of Deceased", "Claimant ID", "Mortuary Letter", "Bank Details"
        ]
    };

    const required = rules[relationship] || [];
    const list = document.getElementById("requiredDocsList");
    const progress = document.getElementById("docProgress");
    const counter = document.getElementById("docCounter");
    const select = document.getElementById("documentTypeSelect");
    const approveBtn = document.getElementById("approveBtn");
    const rejectBtn = document.getElementById("rejectBtn");

    let uploaded = 0;

    list.innerHTML = "";

    required.forEach(doc => {
        const hasDoc = uploadedDocs.includes(doc);
        if (hasDoc) uploaded++;

        list.innerHTML += `
            <li class="list-group-item d-flex justify-content-between">
                ${doc}
                <span class="badge ${hasDoc ? 'bg-success' : 'bg-danger'}">
                    ${hasDoc ? '✔' : '✖'}
                </span>
            </li>`;
    });

    const percent = required.length
        ? Math.round((uploaded / required.length) * 100)
        : 0;

    progress.style.width = percent + "%";
    progress.textContent = percent + "%";
    counter.textContent = `${uploaded} of ${required.length} required documents uploaded`;

    if (percent === 100) {
        progress.classList.remove("bg-warning");
        progress.classList.add("bg-success");

        approveBtn?.removeAttribute("disabled");
        rejectBtn?.removeAttribute("disabled");
    }

    if (select) {
        select.innerHTML = `<option value="">Select Document</option>`;
        required.forEach(doc => {
            if (!uploadedDocs.includes(doc)) {
                select.innerHTML += `<option value="${doc}">${doc}</option>`;
            }
        });
    }

    // ================= REVIEW ACTION =================
    function reviewDecision(isOk) {

        if (isOk) {
            if (!confirm('Are you sure ALL required documents have been reviewed and are correct?')) {
                return;
            }

            document.getElementById('documents_ok').value = 1;
            document.getElementById('review_comment').value = '';
            document.getElementById('reviewForm').submit();
            return;
        }

        // DOCUMENTS MISSING
        let comment = prompt(
            'Please specify which documents are missing or invalid:'
        );

        if (!comment || comment.trim() === '') {
            alert('Comment is required when documents are missing.');
            return;
        }

        if (!confirm('This will notify the claim creator. Continue?')) {
            return;
        }

        document.getElementById('documents_ok').value = 0;
        document.getElementById('review_comment').value = comment;
        document.getElementById('reviewForm').submit();
    }
</script>

@endsection