<?php
session_start();
if (!isset($_SESSION['staff_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';

$msg = '';
$patients = $conn->query("SELECT patient_id, first_name, last_name FROM patients ORDER BY first_name");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $patient_id = $_POST['patient_id'];
    $amount = $_POST['amount'];
    $description = $_POST['description'];
    $reference = 'INV_' . time() . '_' . $patient_id;
    
    $stmt = $conn->prepare("INSERT INTO payments (patient_id, amount, reference, description, status) VALUES (?, ?, ?, ?, 'pending')");
    $stmt->bind_param("sdss", $patient_id, $amount, $reference, $description);
    if ($stmt->execute()) {
        $msg = "Invoice created! Reference: $reference";
    } else {
        $msg = "Error: " . $conn->error;
    }
}
?>
<!DOCTYPE html>
<html><head><title>Billing</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"></head>
<body><div class="container mt-4"><div class="card"><div class="card-header bg-success text-white"><h4>Create Invoice</h4></div><div class="card-body">
<?php if($msg) echo "<div class='alert alert-info'>$msg</div>"; ?>
<form method="POST">
    <select name="patient_id" class="form-control mb-2" required><option value="">Select Patient</option><?php while($p=$patients->fetch_assoc()) echo "<option value='{$p['patient_id']}'>{$p['first_name']} {$p['last_name']}</option>"; ?></select>
    <input type="number" name="amount" class="form-control mb-2" placeholder="Amount (₦)" step="0.01" required>
    <input type="text" name="description" class="form-control mb-2" placeholder="Description" required>
    <button type="submit" class="btn btn-primary w-100">Create Invoice</button>
</form>
<a href="dashboard.php" class="btn btn-secondary mt-3 w-100">Back</a>
</div></div></div></body>
</html>