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

$invoice_id = intval($_GET['invoice_id'] ?? 0);

if (!$invoice_id) {
    echo "<div class='alert alert-danger'>Invalid Invoice ID</div>";
    exit;
}

// Fetch invoice details
$invoice = $conn->query("SELECT i.*, g.name AS guest_name 
                         FROM invoices i 
                         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;
}

// Calculate total paid so far
$total_paid_result = $conn->query("SELECT SUM(amount) AS paid FROM payments WHERE invoice_id=$invoice_id")->fetch_assoc();
$total_paid = $total_paid_result['paid'] ?? 0;

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

// Handle form submission
if (isset($_POST['submit'])) {
    $amount = floatval($_POST['amount']);
    $method = $_POST['method'];
    $description = $conn->real_escape_string($_POST['description']);
    $guest_id = $invoice['guest_id'];
    $user_id = $_SESSION['username'] ?? 'system';
    $invoice_number = $invoice['invoice_number'];

    if ($amount <= 0) {
        echo "<div class='alert alert-danger'>Amount must be greater than zero.</div>";
    } elseif ($amount > $balance) {
        echo "<div class='alert alert-danger'>Amount cannot exceed remaining balance: MWK " . number_format($balance, 2) . "</div>";
    } else {
        // Insert payment
        $stmt = $conn->prepare("INSERT INTO payments 
            (guest_id, invoice_id, amount, type, method, payment_date, description, user_id, invoice_number) 
            VALUES (?, ?, ?, 'Room', ?, NOW(), ?, ?, ?)");
        $stmt->bind_param("iidssss", $guest_id, $invoice_id, $amount, $method, $description, $user_id, $invoice_number);
        $stmt->execute();

        // Update invoice status
        $total_paid_result = $conn->query("SELECT SUM(amount) AS paid FROM payments WHERE invoice_id=$invoice_id")->fetch_assoc();
        $total_paid = $total_paid_result['paid'] ?? 0;
        $balance = $invoice['total_amount'] - $total_paid;

        if ($total_paid >= $invoice['total_amount']) {
            $status = 'Paid';
        } elseif ($total_paid > 0) {
            $status = 'Partially Paid';
        } else {
            $status = 'Unpaid';
        }

        $conn->query("UPDATE invoices SET status='$status' WHERE id=$invoice_id");

        echo "<div class='alert alert-success'>Payment of MWK " . number_format($amount, 2) . " received successfully.</div>";
        echo "<a href='combined_invoices.php' class='btn btn-secondary'>Back to Bulk Invoices</a>";
        exit;
    }
}
?>

<div class="container mt-4">
    <h3>Receive Payment for Invoice: <?= htmlspecialchars($invoice['invoice_number']) ?></h3>
    <p><strong>Guest:</strong> <?= htmlspecialchars($invoice['guest_name']) ?></p>
    <p><strong>Total Invoice Amount:</strong> <?= number_format($invoice['total_amount'], 2) ?> MWK</p>
    <p><strong>Total Paid:</strong> <?= number_format($total_paid, 2) ?> MWK</p>
    <p><strong>Remaining Balance:</strong> <?= number_format($balance, 2) ?> MWK</p>

    <form method="POST" class="mt-3">
        <div class="mb-3">
            <label>Amount Received (MWK)</label>
            <input type="number" step="0.01" min="0" max="<?= $balance ?>" name="amount" class="form-control" required>
        </div>

        <div class="mb-3">
            <label>Payment Method</label>
            <select name="method" class="form-control" required>
                <option value="Cash">Cash</option>
                <option value="Bank">Bank</option>
                <option value="Mobile Money">Mobile Money</option>
            </select>
        </div>

        <div class="mb-3">
            <label>Description</label>
            <textarea name="description" class="form-control" rows="2"></textarea>
        </div>

        <button type="submit" name="submit" class="btn btn-success">Receive Payment</button>
        <a href="combined_invoices.php" class="btn btn-secondary">Cancel</a>
    </form>
</div>