<?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 ID.</div>";
    include 'includes/footer.php';
    exit;
}

// Fetch guest info
$guest_row = $conn->query("SELECT * FROM guests WHERE id=$guest_id")->fetch_assoc();
$guest_name = $guest_row['name'] ?? 'Unknown Guest';

// ================= FETCH STAY CHARGES =================
$stay_total = 0;
$res_stays = $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
");
while($s = $res_stays->fetch_assoc()){
    $stay_total += $s['days'] * $s['price'];
}

// ================= FETCH STANDARD CHARGES =================
$charges = [];
$res_charges = $conn->query("SELECT name, amount FROM charges");
while($row = $res_charges->fetch_assoc()){
    $charges[$row['name']] = floatval($row['amount']);
}
// Add room charge
if($stay_total > 0){
    $charges['Room'] = $stay_total;
}

// ================= FETCH CONFERENCE BOOKINGS =================
$conference_total = 0;
$conference_bookings = [];

$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;
}
if($conference_total > 0){
    $charges['Conference'] = $conference_total;
}

// ================= REMOVE EXCLUDED CHARGES =================
$res_removed = $conn->query("SELECT type FROM guest_removed_charges WHERE guest_id=$guest_id");
while($r = $res_removed->fetch_assoc()){
    if(isset($charges[$r['type']])) unset($charges[$r['type']]);
}

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

// ================= CALCULATE TOTALS =================
$total_invoice = 0;
$total_paid = 0;
foreach($charges as $type => $amount){
    $paid = $outstanding_charges[$type] ?? 0;
    $total_paid += $paid;
    $total_invoice += $amount;
}
$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 mb-3" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>
    <h4>Invoice Details for <?= htmlspecialchars($guest_name) ?></h4>
    <hr>

    <!-- Charges Table -->
    <h5><i class="fa fa-list-alt"></i> Charges</h5>
    <table class="table table-bordered table-striped">
        <thead class="table-dark">
            <tr>
                <th>Type</th>
                <th>Total (MK)</th>
                <th>Paid (MK)</th>
                <th>Balance (MK)</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($charges as $type => $amount):
                $paid = $outstanding_charges[$type] ?? 0;
                $bal = $amount - $paid;
                if($amount <= 0 && $paid <= 0) continue; // show only values > 0
            ?>
            <tr>
                <td><?= htmlspecialchars($type) ?></td>
                <td><?= number_format($amount,2) ?></td>
                <td><?= number_format($paid,2) ?></td>
                <td><?= number_format($bal,2) ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <!-- Payment History -->
    <h5 class="mt-4"><i class="fa fa-history"></i> Payment History</h5>
    <table class="table table-bordered table-striped">
        <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Date</th>
                <th>Type</th>
                <th>Amount (MK)</th>
                <th>Method</th>
                <th>Description</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><?= htmlspecialchars($p['type']) ?></td>
                <td><?= number_format($p['amount'],2) ?></td>
                <td><?= htmlspecialchars($p['method']) ?></td>
                <td><?= htmlspecialchars($p['description']) ?></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="table-primary text-white">
            <tr>
                <th>#</th>
                <th>Date</th>
                <th>Total Amount (MK)</th>
                <th>Status</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><?= htmlspecialchars($cb['status']) ?></td>
            </tr>
            <?php $j++; endforeach; ?>
        </tbody>
    </table>
    <?php endif; ?>

    <!-- Summary -->
    <h5 class="mt-4"><i class="fa fa-file-invoice-dollar"></i> Summary</h5>
    <table class="table table-bordered">
        <tr>
            <th>Total Charges (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>

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

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