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

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

$msg = "";
$inv_res = null;

if (isset($_GET['invoice_id'])) {
    $invoice_id = $_GET['invoice_id'];
    $inv_res = $conn->query("SELECT i.*, u.full_name FROM invoices i JOIN patients p ON i.patient_id=p.patient_id JOIN users u ON p.user_id=u.user_id WHERE i.invoice_id=$invoice_id")->fetch_assoc();
}

if (isset($_POST['record_payment'])) {
    $inv_id = $_POST['invoice_id'] ?? null;
    $pat_id = $_POST['patient_id'];
    $amount = $_POST['amount'];
    $method = $_POST['method'];
    $ref = $_POST['reference'];

    // Validate
    if (empty($amount) || empty($method)) {
        $msg = '<div class="alert alert-danger">Amount and Method are required.</div>';
    } else {
        $conn->begin_transaction();
        try {
            // Record Payment
            $stmt = $conn->prepare("INSERT INTO payments (invoice_id, patient_id, payment_date, amount_paid, payment_method, transaction_ref, created_by) VALUES (?, ?, CURDATE(), ?, ?, ?, ?)");
            $stmt->bind_param("iisssi", $inv_id, $pat_id, $amount, $method, $ref, $_SESSION['user_id']);
            $stmt->execute();
            $pay_id = $conn->insert_id;

            // Update Invoice if applicable
            if ($inv_id) {
                $conn->query("UPDATE invoices SET amount_paid = amount_paid + $amount, status = IF(amount_paid >= total_amount, 'PAID', 'PARTIALLY_PAID') WHERE invoice_id=$inv_id");
            }

            $conn->commit();
            $_SESSION['success'] = "Payment recorded successfully. Receipt #$pay_id";
            header("Location: payment_receipts.php");
            exit();

        } catch (Exception $e) {
            $conn->rollback();
            $msg = '<div class="alert alert-danger">Error: ' . $e->getMessage() . '</div>';
        }
    }
}
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Collect Payment')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/select2/css/select2.min.css" rel="stylesheet" />
</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">Collect Payment</h4>
                            </div>
                        </div>
                    </div>

                    <div class="row justify-content-center">
                        <div class="col-lg-6">
                            <div class="card">
                                <div class="card-body">
                                    <?php echo $msg; ?>
                                    <form method="POST">
                                        <?php if ($inv_res): ?>
                                            <input type="hidden" name="invoice_id"
                                                value="<?php echo $inv_res['invoice_id']; ?>">
                                            <input type="hidden" name="patient_id"
                                                value="<?php echo $inv_res['patient_id']; ?>">
                                            <div class="alert alert-info">
                                                <strong>Paying for Invoice
                                                    #<?php echo $inv_res['invoice_id']; ?></strong><br>
                                                Patient: <?php echo $inv_res['full_name']; ?><br>
                                                Balance Due:
                                                <?php echo number_format($inv_res['total_amount'] - $inv_res['amount_paid'], 2); ?>
                                            </div>
                                        <?php else: ?>
                                            <div class="mb-3">
                                                <label class="form-label">Select Patient</label>
                                                <select class="form-select select2" name="patient_id" required>
                                                    <option value="">Select Patient...</option>
                                                    <?php
                                                    $p_sql = "SELECT p.patient_id, u.full_name, p.phone_number FROM patients p JOIN users u ON p.user_id = u.user_id ORDER BY p.updated_at DESC LIMIT 50";
                                                    $p_res = $conn->query($p_sql);
                                                    while ($p = $p_res->fetch_assoc()) {
                                                        echo "<option value='" . $p['patient_id'] . "'>" . $p['full_name'] . " (" . $p['phone_number'] . ")</option>";
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        <?php endif; ?>

                                        <div class="mb-3">
                                            <label class="form-label">Amount</label>
                                            <input type="number" step="0.01" name="amount" class="form-control"
                                                value="<?php echo $inv_res ? ($inv_res['total_amount'] - $inv_res['amount_paid']) : ''; ?>"
                                                required>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Payment Method</label>
                                            <select name="method" class="form-select" required>
                                                <option value="CASH">Cash</option>
                                                <option value="CARD">Card</option>
                                                <option value="MPESA">M-Pesa</option>
                                                <option value="BANK_TRANSFER">Bank Transfer</option>
                                                <option value="INSURANCE">Insurance</option>
                                            </select>
                                        </div>

                                        <div class="mb-3">
                                            <label class="form-label">Transaction Reference (Optional)</label>
                                            <input type="text" name="reference" class="form-control"
                                                placeholder="e.g. M-Pesa Code">
                                        </div>

                                        <button type="submit" name="record_payment" class="btn btn-success w-100"><i
                                                class="ri-money-dollar-circle-line"></i> Record Payment</button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/select2/js/select2.min.js"></script>
    <script>
        $(document).ready(function () {
            $('.select2').select2();
        });
    </script>
</body>

</html>