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

if (!isset($_SESSION['user_id']) || $_SESSION['role_code'] !== 'PATIENT') {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$pat_res = $conn->query("SELECT patient_id FROM patients WHERE user_id = $user_id")->fetch_assoc();
$patient_id = $pat_res['patient_id'];

// Get Total Outstanding
$bal_sql = "SELECT SUM(balance) as total_outstanding FROM invoices WHERE patient_id = ? AND status != 'CANCELLED'";
$stmt = $conn->prepare($bal_sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$total_outstanding = $stmt->get_result()->fetch_assoc()['total_outstanding'] ?? 0;

// Fetch Invoices
$sql = "SELECT * FROM invoices WHERE patient_id = ? ORDER BY invoice_date DESC";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$result = $stmt->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'My Invoices')); ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <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">My Invoices</h4>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-4 col-md-6">
                            <div class="card card-animate bg-primary">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-white-50 text-truncate mb-0">Total
                                                Outstanding</p>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4 text-white">KES
                                                <?php echo number_format($total_outstanding, 2); ?></h4>
                                            <a href="patient_make_payment.php"
                                                class="text-white-50 text-decoration-underline">Make a Payment</a>
                                        </div>
                                        <div class="avatar-sm flex-shrink-0">
                                            <span class="avatar-title bg-white bg-opacity-10 rounded fs-3">
                                                <i class="ri-money-dollar-circle-line text-white"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <table id="invoicesTable" class="table table-bordered dt-responsive nowrap w-100">
                                        <thead>
                                            <tr>
                                                <th>Invoice #</th>
                                                <th>Date</th>
                                                <th>Total Amount</th>
                                                <th>Paid</th>
                                                <th>Balance</th>
                                                <th>Status</th>
                                                <th>Action</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while ($row = $result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo $row['invoice_number']; ?></td>
                                                    <td><?php echo date('M d, Y', strtotime($row['invoice_date'])); ?></td>
                                                    <td><?php echo number_format($row['total_amount'], 2); ?></td>
                                                    <td><?php echo number_format($row['amount_paid'], 2); ?></td>
                                                    <td class="text-danger"><?php echo number_format($row['balance'], 2); ?>
                                                    </td>
                                                    <td>
                                                        <?php
                                                        $statusClass = match ($row['status']) {
                                                            'PAID' => 'bg-success',
                                                            'PARTIAL_PAYMENT' => 'bg-warning',
                                                            'SENT', 'OVERDUE' => 'bg-danger',
                                                            default => 'bg-secondary'
                                                        };
                                                        ?>
                                                        <span
                                                            class="badge <?php echo $statusClass; ?>"><?php echo $row['status']; ?></span>
                                                    </td>
                                                    <td>
                                                        <a href="patient_download_records.php?type=invoice&id=<?php echo $row['invoice_id']; ?>"
                                                            class="btn btn-sm btn-soft-primary">
                                                            <i class="ri-download-line"></i> Download
                                                        </a>
                                                        <?php if ($row['balance'] > 0): ?>
                                                            <a href="patient_make_payment.php?invoice_id=<?php echo $row['invoice_id']; ?>"
                                                                class="btn btn-sm btn-soft-success">
                                                                <i class="ri-bank-card-line"></i> Pay
                                                            </a>
                                                        <?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 () {
            $('#invoicesTable').DataTable({
                order: [[1, 'desc']]
            });
        });
    </script>
</body>

</html>