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

// Check permissions
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$success_msg = "";
$error_msg = "";

// Handle Settlement Action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['settle_claim'])) {
    $claim_id = $_POST['claim_id'];
    $amount_paid = $_POST['amount_paid'];
    $payment_date = $_POST['payment_date'];

    // Update Claim
    $sql = "UPDATE insurance_claims SET claim_status = 'PAID', approved_amount = ?, payment_date = ?, updated_at = NOW() WHERE claim_id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("dsi", $amount_paid, $payment_date, $claim_id);

    if ($stmt->execute()) {
        $success_msg = "Claim settled successfully.";
    } else {
        $error_msg = "Error settling claim: " . $conn->error;
    }
}

// Filters
$provider_filter = $_GET['provider'] ?? '';
$status_filter = $_GET['status'] ?? '';

$sql = "SELECT c.*, ip.provider_name, p.patient_number, 
               u.full_name
        FROM insurance_claims c
        JOIN insurance_providers ip ON c.provider_id = ip.provider_id
        JOIN patients p ON c.patient_id = p.patient_id
        JOIN users u ON p.user_id = u.user_id
        WHERE 1=1";

if ($provider_filter) {
    $sql .= " AND c.provider_id = " . intval($provider_filter);
}
if ($status_filter) {
    $sql .= " AND c.claim_status = '" . $conn->real_escape_string($status_filter) . "'";
} else {
    $sql .= " AND c.claim_status IN ('SUBMITTED', 'APPROVED', 'PARTIAL')";
}

$sql .= " ORDER BY c.claim_date DESC";
$result = $conn->query($sql);

// Fetch Providers for filter
$providers = $conn->query("SELECT * FROM insurance_providers ORDER BY provider_name");
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Insurance Settlements')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.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">

                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Insurance Settlements</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Settlements</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if ($success_msg): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $success_msg; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Filters -->
                    <div class="row mb-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Provider</label>
                                            <select class="form-select" name="provider">
                                                <option value="">All Providers</option>
                                                <?php $providers->data_seek(0);
                                                while ($p = $providers->fetch_assoc()): ?>
                                                    <option value="<?php echo $p['provider_id']; ?>" <?php echo $provider_filter == $p['provider_id'] ? 'selected' : ''; ?>>
                                                        <?php echo $p['provider_name']; ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Status</label>
                                            <select class="form-select" name="status">
                                                <option value="">Pending settlement</option>
                                                <option value="SUBMITTED" <?php echo $status_filter == 'SUBMITTED' ? 'selected' : ''; ?>>Submitted</option>
                                                <option value="APPROVED" <?php echo $status_filter == 'APPROVED' ? 'selected' : ''; ?>>Approved</option>
                                                <option value="PARTIAL" <?php echo $status_filter == 'PARTIAL' ? 'selected' : ''; ?>>Partial</option>
                                                <option value="PAID" <?php echo $status_filter == 'PAID' ? 'selected' : ''; ?>>Paid</option>
                                            </select>
                                        </div>
                                        <div class="col-md-4 d-flex align-items-end">
                                            <button type="submit" class="btn btn-primary w-100">Filter</button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Settlements Table -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <table id="settlementsTable"
                                        class="table table-bordered dt-responsive nowrap table-striped align-middle"
                                        style="width:100%">
                                        <thead>
                                            <tr>
                                                <th>Claim #</th>
                                                <th>Provider</th>
                                                <th>Patient</th>
                                                <th>Service Date</th>
                                                <th>Claimed Amount</th>
                                                <th>Status</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($row = $result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($row['claim_number']); ?></td>
                                                    <td><?php echo htmlspecialchars($row['provider_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($row['first_name'] . ' ' . $row['last_name']); ?>
                                                    </td>
                                                    <td><?php echo date('d M Y', strtotime($row['service_date'])); ?></td>
                                                    <td><?php echo number_format($row['claim_amount'], 2); ?></td>
                                                    <td>
                                                        <span
                                                            class="badge bg-<?php echo $row['claim_status'] == 'PAID' ? 'success' : 'warning'; ?>">
                                                            <?php echo $row['claim_status']; ?>
                                                        </span>
                                                    </td>
                                                    <td>
                                                        <?php if ($row['claim_status'] !== 'PAID'): ?>
                                                            <button class="btn btn-sm btn-success" data-bs-toggle="modal"
                                                                data-bs-target="#settleModal<?php echo $row['claim_id']; ?>">Settle</button>

                                                            <!-- Settle Modal -->
                                                            <div class="modal fade"
                                                                id="settleModal<?php echo $row['claim_id']; ?>" tabindex="-1">
                                                                <div class="modal-dialog">
                                                                    <div class="modal-content">
                                                                        <form method="POST">
                                                                            <div class="modal-header">
                                                                                <h5 class="modal-title">Settle Claim
                                                                                    <?php echo $row['claim_number']; ?></h5>
                                                                                <button type="button" class="btn-close"
                                                                                    data-bs-dismiss="modal"></button>
                                                                            </div>
                                                                            <div class="modal-body">
                                                                                <input type="hidden" name="claim_id"
                                                                                    value="<?php echo $row['claim_id']; ?>">
                                                                                <div class="mb-3">
                                                                                    <label class="form-label">Payment
                                                                                        Date</label>
                                                                                    <input type="date" class="form-control"
                                                                                        name="payment_date"
                                                                                        value="<?php echo date('Y-m-d'); ?>"
                                                                                        required>
                                                                                </div>
                                                                                <div class="mb-3">
                                                                                    <label class="form-label">Amount
                                                                                        Paid</label>
                                                                                    <input type="number" class="form-control"
                                                                                        name="amount_paid" step="0.01"
                                                                                        value="<?php echo $row['claim_amount']; ?>"
                                                                                        required>
                                                                                </div>
                                                                            </div>
                                                                            <div class="modal-footer">
                                                                                <button type="button" class="btn btn-secondary"
                                                                                    data-bs-dismiss="modal">Close</button>
                                                                                <button type="submit" name="settle_claim"
                                                                                    class="btn btn-primary">Confirm
                                                                                    Settlement</button>
                                                                            </div>
                                                                        </form>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function () {
            $('#settlementsTable').DataTable();
        });
    </script>
</body>

</html>