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

$user_id = $_SESSION['user_id'] ?? 0;
$user_role = $_SESSION['role'] ?? '';

// ==================== FILTERS ====================
$status_filter = $_GET['status'] ?? '';
$room_filter   = $_GET['room'] ?? '';

$query = "
    SELECT cb.*, g.name AS guest_name, cr.name AS room_name, cr.price AS room_price
    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
    WHERE 1
    AND cb.id NOT IN (
        SELECT stay_id 
        FROM invoices 
        WHERE 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";
}

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

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

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

// Current datetime
$now = new DateTime();
?>

<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>

    <!-- Simple button -->
<a href="conference_invoices.php" class="btn btn-primary">View Conference Invoices</a>

    <!-- Simple button -->
<a href="paid_invoices.php" class="btn btn-danger">View Paid Conference Invoices</a>




    <h3 class="text-center mb-4">📋 Conference Bookings</h3>
    <hr>

    <!-- Filters -->
    <div class="row mb-3 g-2">
        <div class="col-md-3">
            <form method="GET">
                <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>
            </form>
        </div>

        <div class="col-md-3">
            <form method="GET">
                <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>
            </form>
        </div>

        <div class="col-md-3">
            <a href="add_conference_booking.php" class="btn btn-success w-100">
                ➕ Add Booking
            </a>
        </div>
    </div>

    <!-- Bookings Table -->
    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white">
            <tr>
                <th>#Booking ID</th>
                <th>Client</th>
                <th>Room</th>
                <th>Booking Date</th>
                <th>Start Date</th>
                <th>End Date</th>
                <th>Attendees</th>
                <th>Total Amount (MK)</th>
                <th>Status</th>
                <th>Progress</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
        <?php if($bookings->num_rows > 0): ?>
            <?php while($b = $bookings->fetch_assoc()): ?>
                <?php
                    $booking_start = new DateTime($b['booking_date']);
                    $booking_end = clone $booking_start;
                    $booking_end->modify('+'.($b['num_days']-1).' days');

                    // Progress %
                    $total_days = $b['num_days'];
                    $elapsed_days = max(0, min($total_days, $now->diff($booking_start)->days));
                    if ($now < $booking_start) $elapsed_days = 0;
                    if ($now > $booking_end) $elapsed_days = $total_days;
                    $progress = ($total_days > 0) ? ($elapsed_days/$total_days)*100 : 0;

                    $can_start = ($now >= $booking_start && $now <= $booking_end && $b['status']=='CONFIRMED');

                    // Breakdown for tooltip
                    $room_price = $b['room_price'] ?? 0;
                    $num_days   = $b['num_days'] ?? 1;
                    $attendees  = $b['attendees'] ?? 1;
                    $total_calc = $room_price * $num_days * $attendees;
                    $tooltip = "Room Price: MK $room_price\nDays: $num_days\nAttendees: $attendees\nMK $room_price × $num_days × $attendees = MK ".number_format($total_calc,2);
                ?>
                <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><?= $booking_start->format('d-m-Y') ?></td>
                    <td><?= $booking_end->format('d-m-Y') ?></td>
                    <td><?= $b['attendees'] ?></td>
                    <td>
                        <span data-bs-toggle="tooltip" data-bs-placement="top" title="<?= htmlspecialchars($tooltip) ?>">
                            <?= number_format($b['total_amount'],2) ?>
                        </span>
                    </td>
                    <td>
                        <?php
                            $status = $b['status'];
                            $badge_class = 'secondary';
                            if($status=='PENDING') $badge_class='warning';
                            if($status=='CONFIRMED') $badge_class='success';
                            if($status=='ONGOING') $badge_class='info';
                            if($status=='COMPLETED') $badge_class='primary';
                            if($status=='CANCELLED') $badge_class='danger';
                            echo "<span class='badge bg-$badge_class'>$status</span>";
                        ?>
                    </td>
                    <td>
                        <div class="progress" style="height:20px;">
                            <div class="progress-bar bg-info" role="progressbar" style="width:<?= round($progress) ?>%">
                                <?= round($progress) ?>%
                            </div>
                        </div>
                    </td>
<?php
// Check if an invoice already exists for this guest (booking_id)
$invoice = $conn->query("SELECT id FROM invoices WHERE guest_id = ".intval($b['id'])." LIMIT 1")->fetch_assoc();
$invoice_exists = !empty($invoice);
$invoice_id = $invoice_exists ? $invoice['id'] : 0;
?>
<td class="d-flex gap-1 flex-wrap">
    <?php if($status=='PENDING' && ($user_role=='admin' || $user_role=='manager')): ?>
        <a href="confirm_conference.php?booking_id=<?= $b['id'] ?>" class="btn btn-success btn-sm">✅ Confirm</a>
        <a href="delete_conference_booking.php?booking_id=<?= $b['id'] ?>" 
           class="btn btn-danger btn-sm"
           onclick="return confirm('Delete this booking?');">🗑️ Delete</a>
    <?php endif; ?>

    <?php if($status=='CONFIRMED' || $status=='ONGOING'): ?>
        <a href="start_conference.php?booking_id=<?= $b['id'] ?>" 
           class="btn btn-warning btn-sm" <?= $can_start?'':'disabled' ?>>🚀 Start</a>
    <?php endif; ?>

    <a href="view_conference_booking.php?booking_id=<?= $b['id'] ?>" class="btn btn-info btn-sm">👁️ View</a>

    <?php if($status=='PENDING' || $status=='CONFIRMED'): ?>
        <a href="edit_conference_booking.php?booking_id=<?= $b['id'] ?>" class="btn btn-primary btn-sm">✏️ Edit</a>
    <?php endif; ?>

    <?php if($status=='PENDING' || $status=='CONFIRMED' || $status=='ONGOING'): ?>
        <?php if($invoice_exists): ?>
            <a href="receive_pay.php?guest_id=<?= $b['guest_id'] ?>&booking_id=<?= $b['id'] ?>" class="btn btn-success btn-sm">
                💰 Receive Payment
            </a>
        <?php else: ?>
            <button class="btn btn-secondary btn-sm" disabled title="Invoice not yet generated">
                💰 Receive Payment
            </button>
        <?php endif; ?>
    <?php endif; ?>

    <a href="generate_quote.php?booking_id=<?= $b['id'] ?>" class="btn btn-primary btn-sm">Quote</a>
  <?php if($invoice_exists): ?>
    <a href="conference_invoices.php" class="btn btn-primary btn-sm">
        👁️ Invoices
    </a>
<?php else: ?>
    <a href="generate_invoice.php?booking_id=<?= $b['id'] ?>" class="btn btn-primary btn-sm">
        🧾 Generate Invoice
    </a>
<?php endif; ?>
</td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="11" class="text-center">No bookings found.</td></tr>
        <?php endif; ?>
        </tbody>
    </table>
</div>

<script>
// Initialize Bootstrap 5 tooltips
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})
</script>

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