<?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) $query .= " AND cb.status='". $conn->real_escape_string($status_filter) ."'";
if ($room_filter) $query .= " AND cb.conference_room_id=". intval($room_filter);
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);

// ==================== 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);

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

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

    <!-- Filters -->
    <form method="GET" class="row mb-3 g-2">
        <div class="col-md-2">
            <select name="status" class="form-control" onchange="this.form.submit()">
                <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" onchange="this.form.submit()">
                <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="date" name="from_date" value="<?= htmlspecialchars($from_date) ?>" class="form-control" onchange="this.form.submit()" placeholder="From Date">
        </div>
        <div class="col-md-2">
            <input type="date" name="to_date" value="<?= htmlspecialchars($to_date) ?>" class="form-control" onchange="this.form.submit()" placeholder="To Date">
        </div>
        <div class="col-md-2">
            <input type="text" name="guest" value="<?= htmlspecialchars($guest_filter) ?>" class="form-control" placeholder="Guest Name">
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary w-100">Filter</button>
        </div>
    </form>

    <!-- Cards -->
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card text-white bg-success mb-3">
                <div class="card-body">
                    <h5 class="card-title">Total Bookings</h5>
                    <p class="card-text fs-3"><?= $total_bookings ?></p>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card text-white bg-info mb-3">
                <div class="card-body">
                    <h5 class="card-title">Total Attendees</h5>
                    <p class="card-text fs-3"><?= $total_attendees ?></p>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card text-white bg-primary mb-3">
                <div class="card-body">
                    <h5 class="card-title">Total Amount (MK)</h5>
                    <p class="card-text fs-3"><?= number_format($total_amount,2) ?></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Export buttons -->
    <div class="mb-3">
        <button class="btn btn-success me-2" onclick="exportTableToCSV('paid_bookings.csv')">📥 Export CSV</button>
        <button class="btn btn-danger" onclick="window.print()">🖨 Print PDF</button>
    </div>

    <!-- Table -->
    <table class="table table-bordered table-striped" id="bookingsTable">
        <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>
            </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>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="7" class="text-center">No fully paid bookings found.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
// CSV Export
function exportTableToCSV(filename) {
    var csv = [];
    var rows = document.querySelectorAll("#bookingsTable tr");

    for (var i = 0; i < rows.length; i++) {
        var row = [], cols = rows[i].querySelectorAll("td, th");
        for (var j = 0; j < cols.length; j++)
            row.push('"' + cols[j].innerText.replace(/"/g, '""') + '"');
        csv.push(row.join(","));
    }

    // Download CSV
    var csvFile = new Blob([csv.join("\n")], { type: "text/csv" });
    var downloadLink = document.createElement("a");
    downloadLink.download = filename;
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}
</script>

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