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

// ================= FETCH GUESTS =================
$guests = $conn->query("SELECT * FROM guests WHERE status = 2 ORDER BY name");

// ================= ADD PAYMENT =================
if(isset($_POST['save_payment'])){
    $guest_id = intval($_POST['guest_id']);
    $amount = floatval($_POST['amount']);
    $method = $_POST['method'];
    $type = $_POST['type'];
    $description = $_POST['description'] ?? '';
    $payment_date = $_POST['payment_date'] ?? date('Y-m-d H:i:s');

    $stmt = $conn->prepare("INSERT INTO payments (guest_id, amount, method, type, description, payment_date) VALUES (?,?,?,?,?,?)");
    $stmt->bind_param("idssss", $guest_id, $amount, $method, $type, $description, $payment_date);
    if($stmt->execute()){
        echo "<div class='alert alert-success mt-3'><i class='fa fa-check-circle'></i> Payment recorded successfully.</div>";
    } else {
        echo "<div class='alert alert-danger mt-3'><i class='fa fa-exclamation-triangle'></i> Error: ".$stmt->error."</div>";
    }
}

// ================= GET SELECTED GUEST =================
$guest_id = intval($_GET['guest_id'] ?? 0);
$outstanding_charges = [];
$total_invoice = 0;
$total_paid = 0;
$balance = 0;
$conference_bookings = [];
$conference_total = 0;

if($guest_id){
    // ================= HOTEL STAY CHARGES =================
    $stay = $conn->query("
        SELECT s.days, r.price 
        FROM stays s 
        JOIN rooms r ON s.room_id=r.id 
        WHERE s.guest_id=$guest_id AND s.checkout_date IS NULL 
        LIMIT 1
    ")->fetch_assoc();
    $room_rate = $stay ? $stay['days'] * $stay['price'] : 0;

    // ================= CONFERENCE BOOKINGS =================
    $guest_row = $conn->query("SELECT name FROM guests WHERE id=$guest_id")->fetch_assoc();
    $guest_name = $guest_row['name'] ?? '';

    $conference_total = 0;
    $conference_bookings = [];
    if ($guest_name){
        $conf_stmt = $conn->prepare("SELECT * FROM conference_bookings WHERE client_name=? AND status<>?");
        $status_cancelled = 'CANCELLED';
        $conf_stmt->bind_param("ss", $guest_name, $status_cancelled);
        $conf_stmt->execute();
        $conf_result = $conf_stmt->get_result();

        while($c = $conf_result->fetch_assoc()){
            $conference_total += $c['total_amount'];
            $conference_bookings[] = $c;
        }
    }

    // ================= STANDARD CHARGES =================
    $charges = [];

    // Add room charge
    $charges['Room'] = $room_rate;

    // Fetch standard charges from table (like bar/restaurant/services)
    $res_charges = $conn->query("SELECT name, amount FROM charges");
    while($row = $res_charges->fetch_assoc()){
        $charges[$row['name']] = floatval($row['amount']);
    }

    // Add conference bookings
    $charges['Conference'] = $conference_total;

    // ================= FETCH REMOVED CHARGES =================
    $removed_types = [];
    $res_removed = $conn->query("SELECT type FROM guest_removed_charges WHERE guest_id=$guest_id");
    while($r = $res_removed->fetch_assoc()) $removed_types[] = $r['type'];

    foreach($removed_types as $rt){
        if(isset($charges[$rt])) unset($charges[$rt]);
    }

    // ================= PAYMENTS PER TYPE =================
    $outstanding_charges = [];
    $res = $conn->query("SELECT type, SUM(amount) as total_paid FROM payments WHERE guest_id=$guest_id GROUP BY type");
    while($row = $res->fetch_assoc()){
        $outstanding_charges[$row['type']] = $row['total_paid'];
    }

    // ================= TOTAL FROM INVOICES =================
    $invoice_total = 0;
    $invoice_res = $conn->query("SELECT SUM(total_amount) AS inv_total FROM invoices WHERE guest_id=$guest_id");
    if($invoice_res && $inv_row = $invoice_res->fetch_assoc()){
        $invoice_total = floatval($inv_row['inv_total']);
    }

    // ================= CALCULATE TOTALS =================
    $total_invoice = $invoice_total; // Start with total from invoices
    $total_paid = 0;

    foreach($charges as $type => $amount){
        $paid = $outstanding_charges[$type] ?? 0;
        $total_paid += $paid;
        $total_invoice += $amount; // Add standard charges to invoice total
    }

    $balance = $total_invoice - $total_paid;
}
?>

<div class="container mt-4">
 <div class="welcome-msg">
    <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
 </div>
    
 <button class="btn btn-secondary btn-custom mb-3" onclick="history.back()">
    <i class="fa fa-arrow-left"></i> Back
 </button>

<h4><i class="fa fa-money-bill-wave"></i> Guest Payments & Conference Bookings</h4>
<hr>

<!-- Select Guest -->
<form method="GET" class="row g-3 mb-3">
    <div class="col-md-4">
        <select name="guest_id" class="form-control" onchange="this.form.submit()">
            <option value="">Select Guest</option>
            <?php
            // Re-fetch guests to populate dropdown if previous loop exhausted it
            $guests2 = $conn->query("SELECT * FROM guests WHERE status = 2 ORDER BY name");
            while($g=$guests2->fetch_assoc()): ?>
                <option value="<?= $g['id'] ?>" <?= $guest_id==$g['id']?'selected':'' ?>>
                    <?= htmlspecialchars($g['name']) ?>
                </option>
            <?php endwhile; ?>
        </select>
    </div>
</form>

<?php if($guest_id): ?>

    <!-- Invoice Summary -->
    <h5><i class="fa fa-file-invoice-dollar"></i> Invoice Summary</h5>
    <div class="mb-3">
        <div class="progress" style="height:25px;">
            <?php $progress = $total_invoice ? ($total_paid/$total_invoice)*100 : 0; ?>
            <div class="progress-bar bg-success" role="progressbar" style="width:<?= $progress ?>%" aria-valuenow="<?= $progress ?>" aria-valuemin="0" aria-valuemax="100">
                <?= number_format($progress,2) ?>%
            </div>
        </div>
    </div>
    <table class="table table-bordered">
        <tr>
            <th>Total Invoice (MK)</th>
            <th>Total Paid (MK)</th>
            <th>Balance (MK)</th>
        </tr>
        <tr>
            <td><?= number_format($total_invoice,2) ?></td>
            <td><?= number_format($total_paid,2) ?></td>
            <td><?= number_format($balance,2) ?></td>
        </tr>
    </table>

    <!-- Add Payment Form -->
    <h5 class="mt-4"><i class="fa fa-plus-circle"></i> Add Payment</h5>
    <form method="POST" class="row g-3">
        <input type="hidden" name="guest_id" value="<?= $guest_id ?>">
        <div class="col-md-3">
            <select name="type" class="form-control" required>
                <option value="">Select Charge Type</option>
                <?php foreach($charges as $type => $amount): ?>
                    <option value="<?= $type ?>"><?= $type ?> (<?= number_format($amount - ($outstanding_charges[$type] ?? 0),2) ?> MK remaining)</option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-2">
            <input type="number" step="0.01" name="amount" class="form-control" placeholder="Amount" required>
        </div>
        <div class="col-md-3">
            <select name="method" class="form-control">
                <option>Cash</option>
                <option>Bank Transfer</option>
                <option>EFT</option>
                <option>Cheque Deposit</option>
                <option>Mobile Money</option>
            </select>
        </div>
        <div class="col-md-2">
            <input type="datetime-local" name="payment_date" class="form-control">
        </div>
        <div class="col-md-2">
            <input type="text" name="description" class="form-control" placeholder="Bank Name/Other Info">
        </div>
        <div class="col-md-2 mt-2">
            <button type="submit" name="save_payment" class="btn btn-success w-100"><i class="fa fa-save"></i> Record Payment</button>
        </div>
    </form>

    <!-- Outstanding Charges Table -->
    <h5 class="mt-4"><i class="fa fa-list-alt"></i> Outstanding Charges</h5>
    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white">
            <tr>
                <th>Type</th>
                <th>Total</th>
                <th>Paid</th>
                <th>Balance</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($charges as $type => $amount):
                $paid = $outstanding_charges[$type] ?? 0;
                $bal  = $amount - $paid;
            ?>
            <tr>
                <td><?= $type ?></td>
                <td><?= number_format($amount,2) ?></td>
                <td><?= number_format($paid,2) ?></td>
                <td><?= number_format($bal,2) ?></td>
                <td>
                    <?php if($bal > 0): ?>
                        <a href="edit_charge.php?guest_id=<?= $guest_id ?>&type=<?= urlencode($type) ?>" class="btn btn-sm btn-primary"><i class="fa fa-edit"></i> Edit</a>
                        <a href="delete_charge.php?guest_id=<?= $guest_id ?>&type=<?= urlencode($type) ?>" onclick="return confirm('Remove this charge for this guest?')" class="btn btn-sm btn-danger"><i class="fa fa-trash"></i> Remove</a>
                    <?php else: ?>
                        <span class="text-success"><i class="fa fa-check"></i> Paid</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- Guest Payment History -->
    <h5 class="mt-4"><i class="fa fa-history"></i> Guest Payment History</h5>
    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white">
            <tr>
                <th>#</th>
                <th>Date</th>
                <th>Type</th>
                <th>Amount (MK)</th>
                <th>Method</th>
                <th>Description</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $res = $conn->query("SELECT * FROM payments WHERE guest_id=$guest_id ORDER BY payment_date DESC");
        $i=1;
        while($p = $res->fetch_assoc()):
        ?>
            <tr>
                <td><?= $i ?></td>
                <td><?= date('d-M-Y H:i', strtotime($p['payment_date'])) ?></td>
                <td><?= $p['type'] ?></td>
                <td><?= number_format($p['amount'],2) ?></td>
                <td><?= $p['method'] ?></td>
                <td><?= $p['description'] ?></td>
                <td>
                    <a href="edit_payment.php?id=<?= $p['id'] ?>" class="btn btn-sm btn-primary"><i class="fa fa-edit"></i></a>
                    <a href="receipt_pay.php?id=<?= $p['id'] ?>" target="_blank" class="btn btn-sm btn-success"><i class="fa fa-receipt"></i></a>
                </td>
            </tr>
        <?php $i++; endwhile; ?>
        </tbody>
    </table>

    <!-- Conference Bookings -->
    <?php if(!empty($conference_bookings)): ?>
        <h5 class="mt-4"><i class="fa fa-users"></i> Conference Bookings</h5>
        <table class="table table-bordered table-striped">
            <thead class="bg-primary text-white">
                <tr>
                    <th>#</th>
                    <th>Date</th>
                    <th>Total Amount (MK)</th>
                    <th>Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>
            <?php $j=1; foreach($conference_bookings as $cb): ?>
                <tr>
                    <td><?= $j ?></td>
                    <td><?= date('d-M-Y', strtotime($cb['booking_date'] ?? '')) ?></td>
                    <td><?= number_format($cb['total_amount'],2) ?></td>
                    <td><?= $cb['status'] ?? 'N/A' ?></td>
                    <td>
                        <a href="view_conference_booking.php?booking_id=<?= $cb['id'] ?>" class="btn btn-sm btn-info"><i class="fa fa-eye"></i> View</a>
                        <a href="invoice_conference.php?booking_id=<?= $cb['id'] ?>" class="btn btn-sm btn-success"><i class="fa fa-file-invoice"></i> Invoice</a>
                        <a href="quote_conference.php?booking_id=<?= $cb['id'] ?>" class="btn btn-sm btn-warning"><i class="fa fa-file-alt"></i> Quote</a>
                    </td>
                </tr>
            <?php $j++; endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>

    <!-- Link to full invoice -->
    <a href="create_invoice.php?stay_id=<?= $guest_id ?>" class="btn btn-info mt-3">
        <i class="fa fa-file-invoice"></i> View Full Invoice
    </a>

<?php endif; ?>
</div>

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