<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

// ================= GET INVOICE =================
$invoice_id = intval($_GET['invoice_id'] ?? 0);
if(!$invoice_id){
    echo "<div class='alert alert-danger'>Invalid Invoice</div>";
    exit;
}

// Fetch invoice details
$invoice = $conn->query("
    SELECT i.*, g.name AS guest_name, cb.client_name, cb.booking_date
    FROM invoices i
    LEFT JOIN conference_bookings cb ON i.stay_id = cb.id
    LEFT JOIN guests g ON i.guest_id = g.id
    WHERE i.id = $invoice_id
")->fetch_assoc();

if(!$invoice){
    echo "<div class='alert alert-danger'>Invoice not found</div>";
    exit;
}

$guest_id = $invoice['guest_id'];

// ================= FETCH PAYMENTS FOR THIS INVOICE =================
$payments_result = $conn->query("
    SELECT * FROM payments 
    WHERE guest_id=$guest_id AND invoice_id=$invoice_id
    ORDER BY payment_date DESC
");

$payments = [];
$total_paid = 0;
while($p = $payments_result->fetch_assoc()){
    $payments[] = $p;
    $total_paid += $p['amount'];
}

$balance = $invoice['total_amount'] - $total_paid;

// ================= HANDLE PAYMENT SUBMISSION =================
if(isset($_POST['make_payment'])){
    $amount = floatval($_POST['amount']);
    $method = $conn->real_escape_string($_POST['method']);
    $status = 'Paid';
    $type = 'Conference';
    
    if($amount > $balance){
        echo "<script>alert('Amount exceeds invoice balance ($balance MWK)'); window.history.back();</script>";
        exit;
    }

    // Insert payment with invoice_id
    $stmt = $conn->prepare("
        INSERT INTO payments (guest_id, invoice_id, amount, type, method, status) 
        VALUES (?,?,?,?,?,?)
    ");
    $stmt->bind_param("iiidss", $guest_id, $invoice_id, $amount, $type, $method, $status);
    $stmt->execute();

    // Update invoice status
    $new_total_paid = $total_paid + $amount;
    if($new_total_paid >= $invoice['total_amount']){
        $conn->query("UPDATE invoices SET status='Paid' WHERE id=$invoice_id");
    } elseif($new_total_paid > 0){
        $conn->query("UPDATE invoices SET status='Partially Paid' WHERE id=$invoice_id");
    }

    echo "<script>alert('Payment recorded successfully'); window.location='receive_pay_conf.php?invoice_id=$invoice_id';</script>";
    exit;
}
?>

<div class="container mt-4">
    <button class="btn btn-secondary" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>
    <h3>Receive Payment for <?= htmlspecialchars($invoice['guest_name'] ?? $invoice['client_name']) ?></h3>

    <!-- Payment Form -->
    <?php if($balance > 0): ?>
    <div class="card mb-4">
        <div class="card-header bg-dark text-white">💰 Make Payment</div>
        <div class="card-body">
            <form method="POST" class="row g-3">
                <div class="col-md-6">
                    <label>Invoice</label>
                    <input type="text" class="form-control" value="<?= htmlspecialchars($invoice['invoice_number']) ?> (Balance: <?= number_format($balance,2) ?> MWK)" disabled>
                </div>
                <div class="col-md-3">
                    <label>Amount</label>
                    <input type="number" name="amount" class="form-control" step="0.01" max="<?= $balance ?>" required>
                </div>
                <div class="col-md-3">
                    <label>Payment Method</label>
                    <select name="method" class="form-control" required>
                        <option value="">-- Select Method --</option>
                        <option value="Cash">Cash</option>
                        <option value="Bank Transfer">Bank Transfer</option>
                        <option value="Mobile Money">Mobile Money</option>
                    </select>
                </div>
                <div class="col-12 mt-2">
                    <button type="submit" name="make_payment" class="btn btn-success">💾 Record Payment</button>
                </div>
            </form>
        </div>
    </div>
    <?php else: ?>
        <div class="alert alert-success">✅ This invoice is fully paid.</div>
    <?php endif; ?>

    <!-- Payments History -->
    <div class="card">
        <div class="card-header bg-info text-white">📜 Payment History</div>
        <div class="card-body">
            <?php if(count($payments) > 0): ?>
                <table class="table table-bordered table-striped">
                    <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>Amount (MWK)</th>
                            <th>Method</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php $c=1; foreach($payments as $p): ?>
                        <tr>
                            <td><?= $c++ ?></td>
                            <td><?= number_format($p['amount'],2) ?></td>
                            <td><?= htmlspecialchars($p['method']) ?></td>
                            <td><?= date('d/m/Y H:i', strtotime($p['payment_date'])) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="text-muted">No payments recorded yet for this invoice.</p>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>