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

// ==================== FILTERS ====================
$status_filter = $_GET['status'] ?? '';
$room_filter   = $_GET['room'] ?? '';
$from_date     = $_GET['from_date'] ?? '';
$to_date       = $_GET['to_date'] ?? '';
$guest_filter  = $_GET['guest'] ?? '';

// ==================== QUERY ====================
$query = "
    SELECT cb.*, g.name AS guest_name, cr.name AS room_name, cr.price AS room_price, 
           i.id AS invoice_id, i.invoice_number
    FROM conference_bookings cb
    LEFT JOIN guests g ON cb.guest_id = g.id
    LEFT JOIN conference_rooms cr ON cb.conference_room_id = cr.id
    LEFT JOIN invoices i ON cb.id = i.stay_id
    WHERE i.status='Paid'
";

if ($status_filter) {
    $safe_status = $conn->real_escape_string($status_filter);
    $query .= " AND cb.status='$safe_status'";
}
if ($room_filter) {
    $safe_room = intval($room_filter);
    $query .= " AND cb.conference_room_id=$safe_room";
}
if ($from_date) {
    $query .= " AND cb.booking_date >= '". $conn->real_escape_string($from_date) ."'";
}
if ($to_date) {
    $query .= " AND cb.booking_date <= '". $conn->real_escape_string($to_date) ."'";
}
if ($guest_filter) {
    $query .= " AND g.name LIKE '%". $conn->real_escape_string($guest_filter) ."%'";
}

$query .= " ORDER BY cb.id DESC";

$bookings = $conn->query($query);

// Fetch rooms for filter dropdown
$rooms = $conn->query("SELECT * FROM conference_rooms ORDER BY name");

// ==================== CALCULATE TOTALS ====================
$total_bookings = 0;
$total_amount   = 0;
$total_attendees= 0;
while ($b = $bookings->fetch_assoc()) {
    $total_bookings++;
    $total_amount += floatval($b['total_amount']);
    $total_attendees += intval($b['attendees']);
}
// Reset pointer for table
$bookings->data_seek(0);
?>

<div class="container mt-4">

    <h3 class="text-center mb-4">💰 Paid Conference Bookings / Invoices</h3>

    <!-- Filter Row -->
    <form method="GET" class="row g-2 mb-3">
        <div class="col-md-2">
            <input type="date" name="from_date" class="form-control" value="<?= htmlspecialchars($from_date) ?>" placeholder="From Date">
        </div>
        <div class="col-md-2">
            <input type="date" name="to_date" class="form-control" value="<?= htmlspecialchars($to_date) ?>" placeholder="To Date">
        </div>
        <div class="col-md-2">
            <select name="status" class="form-control">
                <option value="">-- All Statuses --</option>
                <option value="PENDING" <?= $status_filter=='PENDING'?'selected':'' ?>>Pending</option>
                <option value="CONFIRMED" <?= $status_filter=='CONFIRMED'?'selected':'' ?>>Confirmed</option>
                <option value="ONGOING" <?= $status_filter=='ONGOING'?'selected':'' ?>>Ongoing</option>
                <option value="COMPLETED" <?= $status_filter=='COMPLETED'?'selected':'' ?>>Completed</option>
                <option value="CANCELLED" <?= $status_filter=='CANCELLED'?'selected':'' ?>>Cancelled</option>
            </select>
        </div>
        <div class="col-md-2">
            <select name="room" class="form-control">
                <option value="">-- All Rooms --</option>
                <?php while($r = $rooms->fetch_assoc()): ?>
                    <option value="<?= $r['id'] ?>" <?= $room_filter==$r['id']?'selected':'' ?>>
                        <?= htmlspecialchars($r['name']) ?>
                    </option>
                <?php endwhile; ?>
            </select>
        </div>
        <div class="col-md-2">
            <input type="text" name="guest" class="form-control" value="<?= htmlspecialchars($guest_filter) ?>" placeholder="Guest Name">
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary w-100">Filter</button>
        </div>
    </form>

    <!-- Summary Cards -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card bg-success text-white">
                <div class="card-body text-center">
                    <h5>Total Bookings</h5>
                    <h3><?= $total_bookings ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card bg-info text-white">
                <div class="card-body text-center">
                    <h5>Total Amount Paid</h5>
                    <h3>MK <?= number_format($total_amount,2) ?></h3>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card bg-warning text-dark">
                <div class="card-body text-center">
                    <h5>Total Attendees</h5>
                    <h3><?= $total_attendees ?></h3>
                </div>
            </div>
        </div>
    </div>

    <!-- Export Buttons -->
    <div class="mb-3">
        <a href="export_paid_bookings_excel.php?format=excel" class="btn btn-success me-2">📥 Export Excel</a>
        <a href="export_paid_bookings_pdf.php?format=pdf" class="btn btn-danger">📄 Export PDF</a>
    </div>

    <!-- Bookings Table -->
    <div class="table-responsive">
    <table class="table table-bordered table-striped">
        <thead class="bg-success text-white">
            <tr>
                <th>#Booking ID</th>
                <th>Client</th>
                <th>Room</th>
                <th>Booking Date</th>
                <th>Total Amount (MK)</th>
                <th>Invoice #</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
        <?php if($bookings->num_rows > 0): ?>
            <?php while($b = $bookings->fetch_assoc()): ?>
                <tr>
                    <td><?= $b['id'] ?></td>
                    <td><?= htmlspecialchars($b['client_name']) ?></td>
                    <td><?= htmlspecialchars($b['room_name'] ?? '-') ?> (<?= number_format($b['room_price'],2) ?>)</td>
                    <td><?= date('d-m-Y H:i', strtotime($b['booking_date'])) ?></td>
                    <td><?= number_format($b['total_amount'],2) ?></td>
                    <td><?= htmlspecialchars($b['invoice_number'] ?? '-') ?></td>
                    <td><span class="badge bg-success">Paid</span></td>
                    <td>
                        <a href="view_conference_booking.php?booking_id=<?= $b['id'] ?>" class="btn btn-info btn-sm">👁️ View</a>
                        <a href="receipt_cthermal.php?invoice_id=<?= $b['invoice_id'] ?>" target="_blank" class="btn btn-warning btn-sm">🧾 Print Receipt</a>
                    </td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="8" class="text-center">No fully paid bookings found.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
    </div>
</div>

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