<?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 processed 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 = 'PROCESSED'
        ORDER BY c.processed_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 = 'PROCESSED'";
$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' => 'Processed 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' => 'Processed 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">Processed EDI Claims</h4>
                                    <div class="flex-shrink-0">
                                        <div class="form-group">
                                            <input type="text" id="searchInput" class="form-control" placeholder="Search claims...">
                                        </div>
                                    </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>Processed At</th>
                                                    <th>Bill Status</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>
                                                        <?php echo date('d M Y H:i', strtotime($claim['processed_at'])); ?>
                                                    </td>
                                                    <td>
                                                        <?php
                                                        // Get bill status
                                                        $sql = "SELECT vet_status FROM bills WHERE claim_no = ?";
                                                        $stmt = $conn->prepare($sql);
                                                        $stmt->bind_param('s', $claim['claim_code']);
                                                        $stmt->execute();
                                                        $bill = $stmt->get_result()->fetch_assoc();
                                                        
                                                        if ($bill) {
                                                            $status_class = $bill['vet_status'] === 1 ? 'success' : 
                                                                         ($bill['vet_status'] === 2 ? 'danger' : 'warning');
                                                            $status_text = $bill['vet_status'] === 1 ? 'Approved' :
                                                                         ($bill['vet_status'] === 2 ? 'Rejected' : 'Pending');
                                                            echo "<span class='badge bg-{$status_class}'>{$status_text}</span>";
                                                        } else {
                                                            echo "<span class='badge bg-danger'>Bill Not Found</span>";
                                                        }
                                                        ?>
                                                    </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>
                                                        <?php if ($bill): ?>
                                                        <a href="view_claim.php?id=<?php echo $claim['claim_code']; ?>" 
                                                           class="btn btn-primary btn-sm">
                                                            <i class="ri-file-list-3-line align-middle me-1"></i>
                                                            View Bill
                                                        </a>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <?php endforeach; ?>
                                                <?php if (empty($claims)): ?>
                                                <tr>
                                                    <td colspan="7" class="text-center">No processed 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-success mt-3">
                                <i class="ri-check-line me-2"></i>
                                Processed successfully on ${new Date(claim.processed_at).toLocaleString()}
                            </div>
                        </div>
                    `,
                    width: '600px',
                    confirmButtonText: 'Close'
                });
            })
            .catch(error => {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error.message
                });
            });
    }
    </script>
</body>
</html>