<?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 failed claims with pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 25;
$offset = ($page - 1) * $limit;

$sql = "SELECT c.*, p.provider_name 
        FROM edi_claims c
        JOIN edi_providers p ON c.provider_id = p.provider_id
        WHERE c.status = 'FAILED'
        ORDER BY c.created_at DESC
        LIMIT ? OFFSET ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ii', $limit, $offset);
$stmt->execute();
$claims = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

// Get total count for pagination
$sql = "SELECT COUNT(*) as total FROM edi_claims WHERE status = 'FAILED'";
$total_claims = $conn->query($sql)->fetch_assoc()['total'];
$total_pages = ceil($total_claims / $limit);
?>

<!DOCTYPE html>
<html>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Failed 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' => 'Failed Claims')); ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Failed EDI Claims</h4>
                                    <div class="flex-shrink-0">
                                        <input type="text" id="searchInput" class="form-control" placeholder="Search claims...">
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-hover" id="claimsTable">
                                            <thead>
                                                <tr>
                                                    <th>Claim Code</th>
                                                    <th>Member Number</th>
                                                    <th>Amount</th>
                                                    <th>Provider</th>
                                                    <th>Error Message</th>
                                                    <th>Created At</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php foreach ($claims as $claim): 
                                                    $claim_data = json_decode($claim['claim_data'], true);
                                                ?>
                                                <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>
                                                        <span class="badge bg-danger text-wrap">
                                                            <?php echo htmlspecialchars($claim['error_message']); ?>
                                                        </span>
                                                    </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-warning btn-sm"
                                                                onclick="retryProcessing(<?php echo $claim['claim_id']; ?>)">
                                                            <i class="ri-refresh-line align-middle me-1"></i>
                                                            Retry
                                                        </button>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                                <?php if (empty($claims)): ?>
                                                <tr>
                                                    <td colspan="7" class="text-center">No failed claims found</td>
                                                </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>

                                    <?php if ($total_pages > 1): ?>
                                    <div class="d-flex justify-content-end mt-3">
                                        <ul class="pagination">
                                            <?php if ($page > 1): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page - 1; ?>">Previous</a>
                                            </li>
                                            <?php endif; ?>
                                            
                                            <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                                            <li class="page-item <?php echo $i === $page ? 'active' : ''; ?>">
                                                <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                                            </li>
                                            <?php endfor; ?>
                                            
                                            <?php if ($page < $total_pages): ?>
                                            <li class="page-item">
                                                <a class="page-link" href="?page=<?php echo $page + 1; ?>">Next</a>
                                            </li>
                                            <?php endif; ?>
                                        </ul>
                                    </div>
                                    <?php endif; ?>
                                </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>
    document.addEventListener('DOMContentLoaded', function() {
        // Search functionality
        const searchInput = document.getElementById('searchInput');
        const table = document.getElementById('claimsTable');
        const rows = table.getElementsByTagName('tr');

        searchInput.addEventListener('keyup', function(e) {
            const search = e.target.value.toLowerCase();
            
            // Start from index 1 to skip the header row
            for (let i = 1; i < rows.length; i++) {
                const text = rows[i].textContent.toLowerCase();
                rows[i].style.display = text.includes(search) ? '' : 'none';
            }
        });
    });

    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 class="alert alert-danger mt-3">
                                <i class="ri-error-warning-line me-2"></i>
                                ${claim.error_message}
                            </div>
                        </div>
                    `,
                    width: '600px',
                    confirmButtonText: 'Close'
                });
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
    }

    function retryProcessing(claimId) {
        Swal.fire({
            title: 'Retry Processing',
            text: 'Are you sure you want to retry processing this claim?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Retry',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                // Reset the claim status
                fetch('reset_claim_status.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 reset claim');
                    }

                    Swal.fire({
                        icon: 'success',
                        title: 'Claim Reset',
                        text: 'Claim has been reset and will be reprocessed'
                    }).then(() => {
                        window.location.reload();
                    });
                })
                .catch(error => {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: error.message
                    });
                });
            }
        });
    }
    </script>
</body>
</html>