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

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

// ================= FETCH GUEST =================
$guest = $conn->query("SELECT * FROM guests WHERE id=$guest_id")->fetch_assoc();
if(!$guest){
    echo "<div class='alert alert-danger'>Guest not found</div>";
    exit;
}

// ================= FETCH INVOICES WITH BALANCES & DISCOUNTS =================
$invoices_result = $conn->query("SELECT * FROM invoices WHERE guest_id=$guest_id ORDER BY created_at DESC");
$invoices = [];
while($inv = $invoices_result->fetch_assoc()){
    
    // Fetch related booking to get manual_discount and total_discount
    $booking = $conn->query("SELECT total_discount, manual_discount FROM conference_bookings WHERE id=".$inv['stay_id'])->fetch_assoc() ?? ['total_discount'=>0,'manual_discount'=>0];
    $total_discount = floatval($booking['total_discount']) + floatval($booking['manual_discount']);

    // Sum payments per invoice
    $paid_total = $conn->query("
        SELECT SUM(amount) AS total 
        FROM payments 
        WHERE guest_id=$guest_id 
        AND invoice_id=".$inv['id']."
    ")->fetch_assoc()['total'] ?? 0;

    // Calculate balance after discount
    $balance = $inv['total_amount'] - $paid_total - $total_discount;

    $inv['balance'] = max($balance,0); // prevent negative
    $inv['discount'] = $total_discount;
    $inv['disabled'] = $inv['balance'] <= 0;

    $invoices[] = $inv;
}

// ================= HANDLE PAYMENT SUBMISSION =================
if(isset($_POST['make_payment'])){
    $invoice_id = intval($_POST['invoice_id']);
    $amount = floatval($_POST['amount']);
    $method = $conn->real_escape_string($_POST['method']);
    $type = 'Conference';
    $status = 'Paid';

    // Fetch invoice including stay_id and invoice_number
    $invoice = $conn->query("SELECT total_amount, status, stay_id, invoice_number FROM invoices WHERE id=$invoice_id")->fetch_assoc();

    // Fetch related booking discounts
    $booking = $conn->query("SELECT total_discount, manual_discount FROM conference_bookings WHERE id=".$invoice['stay_id'])->fetch_assoc() ?? ['total_discount'=>0,'manual_discount'=>0];
    $total_discount = floatval($booking['total_discount']) + floatval($booking['manual_discount']);

    // Compute remaining balance
    $paid_total = $conn->query("SELECT SUM(amount) AS total FROM payments WHERE guest_id=$guest_id AND invoice_id=$invoice_id")->fetch_assoc()['total'] ?? 0;
    $balance = $invoice['total_amount'] - $paid_total - $total_discount;

    if($amount > $balance){
        echo "<script>alert('Amount exceeds invoice balance ($balance MWK)'); window.history.back();</script>";
        exit;
    }

    // Insert payment including discount
    $stmt = $conn->prepare("INSERT INTO payments (guest_id,invoice_id,invoice_number,amount,discount,type,method,status) VALUES (?,?,?,?,?,?,?,?)");
    $stmt->bind_param("idsdssss", $guest_id, $invoice_id, $invoice['invoice_number'], $amount, $total_discount, $type, $method, $status);
    $stmt->execute();

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

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

// ================= FETCH PAYMENTS HISTORY =================
$payments = $conn->query("SELECT * FROM payments WHERE guest_id=$guest_id AND type='Conference' ORDER BY payment_date DESC");

// Summary
$total_paid = $conn->query("SELECT SUM(amount) AS total FROM payments WHERE guest_id=$guest_id AND type='Conference'")->fetch_assoc()['total'] ?? 0;
$total_invoice = $conn->query("SELECT SUM(total_amount) AS total FROM invoices WHERE guest_id=$guest_id")->fetch_assoc()['total'] ?? 0;

// Total discount
$total_discount = $conn->query("
    SELECT SUM(cb.total_discount + cb.manual_discount) AS total
    FROM conference_bookings cb
    JOIN invoices i ON cb.id=i.stay_id
    WHERE i.guest_id=$guest_id
")->fetch_assoc()['total'] ?? 0;

$total_balance = $total_invoice - $total_paid - $total_discount;
?>

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

    <!-- Payment Form -->
    <div class="card mb-4 shadow-sm">
        <div class="card-header bg-dark text-white">
            💰 <b>Make Payment</b>
            - <span class="text-danger"><b>(Select invoice before payment capture)</b></span>
        </div>
        <div class="card-body">
            <form method="POST" class="row g-3">
                
                <!-- Invoice Select -->
                <div class="col-md-6">
                    <label>Invoice</label>
                    <select name="invoice_id" class="form-control" required>
                        <option value="">-- Select Invoice --</option>
                        <?php foreach($invoices as $inv): ?>
                            <option value="<?= $inv['id'] ?>" <?= $inv['disabled'] ? 'disabled' : '' ?>>
                                <?= htmlspecialchars($inv['invoice_number']) ?> - <?= number_format($inv['total_amount'],2) ?> MWK 
                                (<?= $inv['status'] ?>, Balance: <?= number_format($inv['balance'],2) ?> MWK)
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Discount Field -->
                <div class="col-md-3">
                    <label>Discount (MWK)</label>
                    <input type="number" class="form-control text-success fw-bold" id="discount" readonly>
                </div>

                <!-- Amount Field -->
                <div class="col-md-3">
                    <label>Amount to Pay (MWK)</label>
                    <input type="number" name="amount" id="amount" class="form-control fw-bold text-danger" step="0.01" required readonly>
                </div>

                <!-- Payment Method -->
                <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>

    <!-- Summary -->
    <div class="alert alert-info shadow-sm">
        <strong>Total Invoice Amount:</strong> <?= number_format($total_invoice,2) ?> MWK | 
        <strong>Total Discount:</strong> <?= number_format($total_discount,2) ?> MWK | 
        <strong>Total Paid:</strong> <?= number_format($total_paid,2) ?> MWK | 
        <strong>Remaining Balance:</strong> <?= number_format($total_balance,2) ?> MWK
    </div>

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

<script>
    // JS: auto-fill amount & discount when invoice is selected
    const invoices = <?= json_encode($invoices) ?>;
    const invoiceSelect = document.querySelector('select[name="invoice_id"]');
    const amountInput = document.getElementById('amount');
    const discountInput = document.getElementById('discount');

    invoiceSelect.addEventListener('change', function(){
        const selectedId = parseInt(this.value);
        if(selectedId){
            const invoice = invoices.find(i=>i.id==selectedId);
            amountInput.value = invoice.balance;
            discountInput.value = invoice.discount;
        } else {
            amountInput.value = '';
            discountInput.value = '';
        }
    });
</script>

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