<?php
session_start();
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] !== 1) {
    header('Location: login.php');
    exit();
}

// Get pending claims
$sql = "SELECT c.*, p.provider_name FROM edi_claims c
        JOIN edi_providers p ON c.provider_id = p.provider_id
        WHERE c.status = 'PENDING'
        ORDER BY c.created_at DESC";
$result = $conn->query($sql);
$claims = $result->fetch_all(MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pending EDI Claims')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'EDI', 'title' => 'Pending Claims')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Pending EDI Claims</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered">
                                            <thead>
                                                <tr>
                                                    <th>Claim Code</th>
                                                    <th>Member Number</th>
                                                    <th>Amount</th>
                                                    <th>Provider</th>
                                                    <th>Created</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($claims as $claim): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($claim['claim_code']); ?></td>
                                                    <td><?php echo htmlspecialchars($claim['member_number']); ?></td>
                                                    <td class="text-end">
                                                        <?php echo number_format($claim['amount'], 2); ?>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($claim['provider_name']); ?></td>
                                                    <td>
                                                        <?php echo date('d M Y H:i', strtotime($claim['created_at'])); ?>
                                                    </td>
                                                    <td>
                                                        <button type="button" class="btn btn-info btn-sm"
                                                                onclick="viewClaim(<?php echo $claim['claim_id']; ?>)">
                                                            <i class="ri-eye-line align-middle me-1"></i>
                                                            View
                                                        </button>
                                                        <button type="button" class="btn btn-success btn-sm"
                                                                onclick="processClaim(<?php echo $claim['claim_id']; ?>)">
                                                            <i class="ri-check-line align-middle me-1"></i>
                                                            Process
                                                        </button>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                                <?php if (empty($claims)): ?>
                                                <tr>
                                                    <td colspan="6" class="text-center">No pending claims found</td>
                                                </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <script>
    function viewClaim(claimId) {
        fetch(`get_claim_details.php?id=${claimId}`)
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    throw new Error(data.error || 'Failed to fetch claim details');
                }

                const claim = data.claim;
                const claimData = JSON.parse(claim.claim_data);

                let diagnosisHtml = '';
                if (claimData.diagnosis && claimData.diagnosis.length > 0) {
                    diagnosisHtml = '<h6 class="mt-4 mb-2">Diagnosis</h6><ul>';
                    claimData.diagnosis.forEach(d => {
                        diagnosisHtml += `<li>${d.code} - ${d.name}</li>`;
                    });
                    diagnosisHtml += '</ul>';
                }

                let invoicesHtml = '';
                if (claimData.invoices && claimData.invoices.length > 0) {
                    invoicesHtml = '<h6 class="mt-4 mb-2">Invoices</h6>';
                    claimData.invoices.forEach(inv => {
                        invoicesHtml += `
                            <div class="border rounded p-3 mb-3">
                                <p><strong>Invoice:</strong> ${inv.invoice_number}</p>
                                <p><strong>Type:</strong> ${inv.service_type}</p>
                                <p><strong>Amount:</strong> ${inv.amount}</p>
                            </div>
                        `;
                    });
                }

                Swal.fire({
                    title: `Claim Details - ${claim.claim_code}`,
                    html: `
                        <div class="text-start">
                            <p><strong>Member:</strong> ${claim.member_number}</p>
                            <p><strong>Amount:</strong> ${parseFloat(claim.amount).toFixed(2)}</p>
                            <p><strong>Provider:</strong> ${claimData.provider_name || ''}</p>
                            ${diagnosisHtml}
                            ${invoicesHtml}
                        </div>
                    `,
                    width: '600px',
                    confirmButtonText: 'Close'
                });
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
    }

    function processClaim(claimId) {
        Swal.fire({
            title: 'Process Claim',
            text: 'Are you sure you want to process this claim?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Process',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch('process_edi_claim.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ claim_id: claimId })
                })
                .then(response => response.json())
                .then(data => {
                    if (!data.success) {
                        throw new Error(data.error || 'Failed to process claim');
                    }

                    Swal.fire({
                        icon: 'success',
                        title: 'Success',
                        text: 'Claim processed successfully'
                    }).then(() => {
                        window.location.reload();
                    });
                })
                .catch(error => {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error.message
                    });
                });
            }
        });
    }
    </script>
</body>
</html>