<?php
require_once __DIR__ . '/auth.php';
if (empty($_SESSION['user'])) {
    redirect('login.php');
}
$user = $_SESSION['user'];
$message = '';
$banner = '';
$summary = processHxQueue($user['email']);
if (!is_array($summary)) {
    $summary = [
        'detected_hx' => 0,
        'detected_un' => 0,
        'auto_removed' => 0,
        'auto_escalated' => 0,
        'notifications' => 0,
    ];
}
$bookings = getBookings($user['email']) ?: [];
$logs = array_reverse(getAgentHxLogs($user['email']) ?: []);
$badgeCount = getQueueBadgeCount($user['email']);
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['escalate_booking']) && $_POST['escalate_booking'] === '1') {
        $bookingId = $_POST['booking_id'] ?? '';
        $reason = trim($_POST['escalation_reason'] ?? 'Manual escalation');
        if ($bookingId) {
            escalateBooking($bookingId, $user['email'], $reason);
            $banner = 'Booking escalated successfully and team lead notified.';
            $bookings = getBookings($user['email']) ?: [];
            $logs = array_reverse(getAgentHxLogs($user['email']) ?: []);
            $badgeCount = getQueueBadgeCount($user['email']);
        }
    }
    if (isset($_POST['remove_booking']) && $_POST['remove_booking'] === '1') {
        $bookingId = $_POST['booking_id'] ?? '';
        $reason = trim($_POST['removal_reason'] ?? 'Manual removal');
        if ($bookingId) {
            removeBooking($bookingId, $user['email'], $reason);
            $banner = 'Booking removed from queue and email notification generated.';
            $bookings = getBookings($user['email']) ?: [];
            $logs = array_reverse(getAgentHxLogs($user['email']) ?: []);
            $badgeCount = getQueueBadgeCount($user['email']);
        }
    }
    if (isset($_POST['notify_booking']) && $_POST['notify_booking'] === '1') {
        $bookingId = $_POST['booking_id'] ?? '';
        $note = trim($_POST['notification_note'] ?? 'Queue update');
        if ($bookingId) {
            sendBookingNotification($bookingId, $user['email'], $note);
            $banner = 'Queue notification sent to main agent and team lead.';
            $logs = array_reverse(getAgentHxLogs($user['email']) ?: []);
            $badgeCount = getQueueBadgeCount($user['email']);
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en-US">
<?php include "pages/header.php"; ?>

<div id="page-title" class="text-grey background-overlay background-img-dark" style="background-image: url('images/page-title-9.jpg');">
    <div class="text-center">
        <ol class="breadcrumb z-index-2 position-relative no-background padding-30px margin-0px border-top-1 border-grey-4">
            <li><a href="index.php" class="text-white">Home</a></li>
            <li class="active">Booking HX Manager</li>
        </ol>
    </div>
</div>

<section class="padding-tb-60px background-light-grey">
    <div class="container">
        <?php if ($banner): ?>
            <div class="alert alert-success"><?= htmlentities($banner) ?></div>
        <?php endif; ?>
        <div class="alert alert-info d-flex justify-content-between align-items-center">
            <div>
                <strong>Real-time HX alerts:</strong> automatic queue monitoring detects PNR HX and UN updates, evaluates ticketing and payment, and marks removals in the queue.
            </div>
            <span class="badge badge-primary badge-pill"><?= $badgeCount ?> new alerts</span>
        </div>
        <div class="row">
            <div class="col-md-4 mb-4">
                <div class="dashboard-panel">
                    <h3>Queue summary</h3>
                    <p><strong>Total queue:</strong> <?= count($bookings) ?></p>
                    <p><strong>HX detected:</strong> <?= $summary['detected_hx'] ?></p>
                    <p><strong>UN detected:</strong> <?= $summary['detected_un'] ?></p>
                    <p><strong>Auto removed:</strong> <?= $summary['auto_removed'] ?></p>
                    <p><strong>Escalations:</strong> <?= $summary['auto_escalated'] ?></p>
                </div>
            </div>
            <div class="col-md-8 mb-4">
                <div class="dashboard-panel">
                    <h3>Queue health</h3>
                    <p>Bookings are evaluated automatically for ticketing, payment and segment status. Actions are logged for every automated decision and agent intervention.</p>
                    <div class="row text-center">
                        <div class="col-sm-4">
                            <div class="dashboard-summary card p-3 mb-3">
                                <div class="card-title">Pending</div>
                                <div class="display-4"><?= $summary['unresolved'] ?></div>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="dashboard-summary card p-3 mb-3">
                                <div class="card-title">Pending removals</div>
                                <div class="display-4"><?= $summary['pending_removal'] ?></div>
                            </div>
                        </div>
                        <div class="col-sm-4">
                            <div class="dashboard-summary card p-3 mb-3">
                                <div class="card-title">Log alerts</div>
                                <div class="display-4"><?= count($logs) ?></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="dashboard-panel booking-table mb-4">
            <h3>Booking queue</h3>
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Destination</th>
                            <th>PNR / HX</th>
                            <th>UN</th>
                            <th>Status</th>
                            <th>Ticketed</th>
                            <th>Paid</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($bookings as $booking): ?>
                            <tr>
                                <td><?= htmlentities($booking['id'] ?? 'N/A') ?></td>
                                <td><?= htmlentities($booking['destination'] ?? 'Unknown') ?></td>
                                <td>
                                    <?= !empty($booking['hx_detected']) ? '<span class="badge badge-success">HX</span>' : '<span class="badge badge-secondary">No HX</span>' ?>
                                    <br><small><?= htmlentities($booking['pnr'] ?? '—') ?></small>
                                </td>
                                <td>
                                    <?= !empty($booking['un_detected']) ? '<span class="badge badge-success">UN</span>' : '<span class="badge badge-secondary">No UN</span>' ?>
                                    <br><small><?= htmlentities($booking['pnr_un'] ?? '—') ?></small>
                                </td>
                                <td>
                                    <?php
                                    $status = $booking['status'] ?? 'Pending';
                                    $badgeClass = 'badge-secondary';
                                    if (strtolower($status) === 'removed') {
                                        $badgeClass = 'badge-cancelled';
                                    } elseif (strtolower($status) === 'escalated') {
                                        $badgeClass = 'badge-pending';
                                    } elseif (!empty($booking['ticketed']) && !empty($booking['paid'])) {
                                        $badgeClass = 'badge-confirmed';
                                    }
                                    ?>
                                    <span class="badge <?= $badgeClass ?>"><?= htmlentities($status) ?></span>
                                </td>
                                <td><?= !empty($booking['ticketed']) ? '<span class="badge badge-success">Yes</span>' : '<span class="badge badge-secondary">No</span>' ?></td>
                                <td><?= !empty($booking['paid']) ? '<span class="badge badge-success">Yes</span>' : '<span class="badge badge-secondary">No</span>' ?></td>
                                <td>
                                    <button class="btn btn-sm btn-light" data-toggle="modal" data-target="#bookingModal" data-booking='<?= htmlspecialchars(json_encode($booking, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT), ENT_QUOTES, 'UTF-8') ?>'>Details</button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="dashboard-panel">
            <h3>Audit log</h3>
            <?php if (empty($logs)): ?>
                <p class="small-text">No audit entries yet. Actions and automated decisions will appear here.</p>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm table-borderless">
                        <thead>
                            <tr>
                                <th>Time</th>
                                <th>Type</th>
                                <th>Booking</th>
                                <th>Message</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($logs as $log): ?>
                                <tr>
                                    <td><?= htmlentities(date('Y-m-d H:i', strtotime($log['created_at']))) ?></td>
                                    <td><?= htmlentities($log['type']) ?></td>
                                    <td><?= htmlentities($log['booking_id'] ?? '-') ?></td>
                                    <td><?= htmlentities($log['message'] ?? '') ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</section>

<div class="modal fade" id="bookingModal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Booking action</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form id="booking-action-form" action="booking_hx.php" method="post">
                <input type="hidden" name="booking_id" id="booking_id" value="">
                <input type="hidden" name="escalate_booking" id="escalate_booking" value="0">
                <input type="hidden" name="remove_booking" id="remove_booking" value="0">
                <input type="hidden" name="notify_booking" id="notify_booking" value="0">
                <div class="modal-body">
                    <div class="form-group">
                        <label>Booking ID</label>
                        <input type="text" id="modal_booking_id" class="form-control" readonly>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label>Destination</label>
                            <input type="text" id="modal_destination" class="form-control" readonly>
                        </div>
                        <div class="form-group col-md-6">
                            <label>PNR</label>
                            <input type="text" id="modal_pnr" class="form-control" readonly>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label>Ticketed</label>
                            <input type="text" id="modal_ticketed" class="form-control" readonly>
                        </div>
                        <div class="form-group col-md-6">
                            <label>Paid</label>
                            <input type="text" id="modal_paid" class="form-control" readonly>
                        </div>
                    </div>
                    <div class="form-group">
                        <label>Message / note</label>
                        <textarea name="notification_note" id="modal_note" rows="3" class="form-control" placeholder="Add a note for the queue notification or escalation"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-warning" id="btn_escalate">Escalate</button>
                    <button type="button" class="btn btn-danger" id="btn_remove">Remove</button>
                    <button type="button" class="btn btn-primary" id="btn_notify">Send notification</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include "pages/footer.php"; ?>
<script src="//<?= $_SERVER['HTTP_HOST']; ?>/travelsspeed/js/popper.min.js"></script>
<script src="//<?= $_SERVER['HTTP_HOST']; ?>/travelsspeed/js/bootstrap.min.js"></script>
<script>
    $('#bookingModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget);
        var data = button.attr('data-booking');
        var booking = {};
        if (data) {
            try {
                booking = JSON.parse(data);
            } catch (e) {
                booking = button.data('booking') || {};
            }
        } else {
            booking = button.data('booking') || {};
        }
        $('#booking_id').val(booking.id || '');
        $('#modal_booking_id').val(booking.id || '');
        $('#modal_destination').val(booking.destination || '');
        $('#modal_pnr').val(booking.pnr || '');
        $('#modal_ticketed').val(booking.ticketed ? 'Yes' : 'No');
        $('#modal_paid').val(booking.paid ? 'Yes' : 'No');
        $('#modal_note').val('');
        $('#escalate_booking').val('0');
        $('#remove_booking').val('0');
        $('#notify_booking').val('0');
    });
    $('#btn_escalate').click(function () {
        $('#escalate_booking').val('1');
        $('#remove_booking').val('0');
        $('#notify_booking').val('0');
        $('#booking-action-form').submit();
    });
    $('#btn_remove').click(function () {
        $('#remove_booking').val('1');
        $('#escalate_booking').val('0');
        $('#notify_booking').val('0');
        $('#booking-action-form').submit();
    });
    $('#btn_notify').click(function () {
        $('#notify_booking').val('1');
        $('#escalate_booking').val('0');
        $('#remove_booking').val('0');
        $('#booking-action-form').submit();
    });
</script>
</body>
</html>
