<?php
/**
 * @var \App\View\AppView $this
 * @var iterable<\App\Model\Entity\Booking> $bookings
 * @var array $statusOptions
 * @var string $selectedStatus
 * @var string $selectedPickupDate
 * @var string $search
 * @var bool $showArchived
 */
?>

<style>
    .booking-shell {
        background: #ffffff;
        border-radius: 24px;
        box-shadow: 0 10px 30px rgba(15, 23, 42, 0.06);
        border: 1px solid #e5e7eb;
        overflow: hidden;
    }

    .booking-header {
        padding: 18px 28px 18px;
        border-bottom: 1px solid #eef2f7;
        background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
    }

    .booking-title {
        font-size: 2rem;
        font-weight: 700;
        color: #1f2937;
        margin: 0;
    }

    .booking-subtitle {
        color: #64748b;
        margin-top: 8px;
        font-size: 0.96rem;
        font-weight: 380;
    }

    .filter-bar {
        padding: 15px 20px;
        background: #fff;
        border-bottom: 1px solid #eef2f7;
    }

    .filter-control {
        border-radius: 14px !important;
        min-height: 49px;
        border: 1px solid #d7dfeb !important;
        box-shadow: none !important;
        font-weight: 400;
        color: #334155;
    }

    .filter-control:focus {
        border-color: #c8d4e5 !important;
        box-shadow: none !important;
    }

    .search-wrap {
        position: relative;
    }

    .search-wrap .search-icon {
        position: absolute;
        left: 16px;
        top: 50%;
        transform: translateY(-50%);
        color: #94a3b8;
        font-size: 1rem;
        z-index: 3;
    }

    .search-wrap input {
        padding-left: 40px !important;
    }

    .date-filter-wrap {
        position: relative;
        height: 50px;
        border: 1px solid #d7dfeb;
        border-radius: 14px;
        background: #fff;
        display: flex;
        align-items: center;
        padding: 0 42px 0 16px;
        overflow: hidden;
    }

    .date-filter-text {
        color: #475569;
        font-size: 1rem;
        font-weight: 400;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        pointer-events: none;
    }

    .date-filter-chevron {
        position: absolute;
        right: 16px;
        color: #64748b;
        pointer-events: none;
        font-size: 0.95rem;
    }

    .native-date-input {
        position: absolute !important;
        inset: 0;
        opacity: 0;
        cursor: pointer;
        width: 100%;
        height: 100%;
        z-index: 2;
    }

    .filter-actions {
        display: flex;
        gap: 10px;
        justify-content: flex-end;
    }

    .filter-icon-btn {
        width: 45px;
        min-width: 45px;
        height: 45px;
        border-radius: 12px;
        border: 1px solid #d7dfeb;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 0.92rem;
        transition: 0.2s ease;
        text-decoration: none;
        padding: 0;
        background: #fff;
        color: #64748b;
    }

    .filter-icon-btn:hover {
        background: #f8fafc;
        color: #334155;
        border-color: #cbd5e1;
    }

    .filter-icon-btn.active {
        background: #eff6ff;
        color: #2563eb;
        border-color: #bfdbfe;
    }

    .booking-table-wrap {
        max-height: 68vh;
        overflow-y: auto;
        background: #fff;
    }

    .booking-table {
        margin: 0;
        min-width: 1120px;
    }

    .booking-table thead th {
        position: sticky;
        top: 0;
        z-index: 5;
        background: #f8fafc;
        color: #475569;
        font-size: 0.82rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
        border-bottom: 1px solid #e5e7eb;
        padding: 16px 18px;
        white-space: nowrap;
        font-weight: 600;
    }

    .booking-table tbody td {
        padding: 18px;
        vertical-align: top;
        border-bottom: 1px solid #f1f5f9;
    }

    .booking-row:hover {
        background: #f8fbff;
    }

    .ref-code {
        font-weight: 500;
        color: #0f172a;
        font-size: 0.96rem;
        line-height: 1.35;
    }

    .main-text {
        color: #1f2937;
        font-weight: 500;
        line-height: 1.45;
    }

    .mini-text {
        color: #6b7280;
        font-size: 0.88rem;
        margin-top: 4px;
        line-height: 1.45;
        font-weight: 400;
    }

    .status-badge {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        padding: 8px 14px;
        border-radius: 999px;
        font-size: 0.84rem;
        font-weight: 600;
        white-space: nowrap;
    }

    .status-badge::before {
        content: "";
        width: 8px;
        height: 8px;
        border-radius: 50%;
        background: currentColor;
        opacity: 0.75;
    }

    .status-pending { background: #fff7ed; color: #c2410c; }
    .status-confirmed { background: #eff6ff; color: #1d4ed8; }
    .status-picked-up { background: #eef2ff; color: #4338ca; }
    .status-collected-at-depot { background: #f5f3ff; color: #6d28d9; }
    .status-in-transit { background: #eff6ff; color: #2563eb; }
    .status-out-for-delivery { background: #ecfeff; color: #0f766e; }
    .status-delivered { background: #ecfdf5; color: #15803d; }
    .status-delivery-failed { background: #fff1f2; color: #be123c; }
    .status-returned { background: #fef2f2; color: #b91c1c; }
    .status-cancelled { background: #f3f4f6; color: #4b5563; }
    .status-on-hold { background: #fffbea; color: #a16207; }
    .status-archived { background: #f1f5f9; color: #475569; }

    .action-dropdown {
        position: relative;
        display: inline-block;
    }

    .action-toggle {
        width: 44px;
        height: 44px;
        border-radius: 12px;
        border: 1px solid #d7dfeb;
        background: #ffffff;
        color: #475569;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 1rem;
        transition: 0.2s ease;
        cursor: pointer;
    }

    .action-toggle:hover {
        background: #f8fafc;
        color: #0f172a;
        border-color: #cbd5e1;
    }

    .action-menu {
        position: absolute;
        top: calc(100% + 10px);
        right: 0;
        min-width: 185px;
        background: #ffffff;
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        box-shadow: 0 16px 40px rgba(15, 23, 42, 0.12);
        padding: 8px;
        z-index: 50;
        display: none;
    }

    .action-menu.show {
        display: block;
    }

    .action-menu-item,
    .action-menu form button {
        width: 100%;
        display: flex;
        align-items: center;
        gap: 10px;
        border: none;
        background: transparent;
        text-decoration: none;
        padding: 11px 12px;
        border-radius: 12px;
        color: #334155;
        font-size: 0.94rem;
        font-weight: 500;
        text-align: left;
    }

    .action-menu-item:hover,
    .action-menu form button:hover {
        background: #f8fafc;
        color: #0f172a;
    }

    .action-menu-item.delete-item,
    .action-menu form button.delete-item {
        color: #dc2626;
    }

    .action-menu-item.delete-item:hover,
    .action-menu form button.delete-item:hover {
        background: #fef2f2;
        color: #b91c1c;
    }

    .action-menu-item.undo-item,
    .action-menu form button.undo-item {
        color: #2563eb;
    }

    .action-menu-item.undo-item:hover,
    .action-menu form button.undo-item:hover {
        background: #eff6ff;
        color: #1d4ed8;
    }

    .action-menu form {
        margin: 0;
    }

    .archive-banner {
        padding: 12px 20px;
        background: #f8fafc;
        border-bottom: 1px solid #e5e7eb;
        color: #475569;
        font-size: 0.92rem;
        font-weight: 500;
    }

    .empty-state {
        padding: 50px 24px;
        text-align: center;
        color: #6b7280;
    }

    @media (max-width: 991px) {
        .filter-actions {
            justify-content: flex-start;
        }
    }
</style>

<?php
$selectedStatus = $selectedStatus ?? '';
$selectedPickupDate = $selectedPickupDate ?? '';
$search = $search ?? '';
$showArchived = $showArchived ?? false;

function bookingStatusClass(string $status): string {
    $map = [
        'Pending' => 'status-pending',
        'Confirmed' => 'status-confirmed',
        'Picked Up' => 'status-picked-up',
        'Collected at Depot' => 'status-collected-at-depot',
        'In Transit' => 'status-in-transit',
        'Out for Delivery' => 'status-out-for-delivery',
        'Delivered' => 'status-delivered',
        'Delivery Failed' => 'status-delivery-failed',
        'Returned' => 'status-returned',
        'Cancelled' => 'status-cancelled',
        'On Hold' => 'status-on-hold',
    ];

    return $map[$status] ?? 'status-pending';
}
?>

<div class="booking-shell">
    <div class="booking-header">
        <h1 class="booking-title">Bookings</h1>
        <div class="booking-subtitle">
            <?= $showArchived
                ? 'Showing archived bookings. You can restore them back to the recent bookings list.'
                : 'Manage all courier bookings, view details, and update shipment status.' ?>
        </div>
    </div>

    <div class="filter-bar">
        <?= $this->Form->create(null, ['type' => 'get']) ?>

        <?php if ($showArchived): ?>
            <?= $this->Form->hidden('archived', ['value' => 1]) ?>
        <?php endif; ?>

        <div class="row g-3 align-items-center">
    <div class="col-lg-2">
        <?= $this->Form->control('status', [
            'label' => false,
            'empty' => 'All Statuses',
            'options' => array_combine($statusOptions, $statusOptions),
            'value' => $selectedStatus,
            'class' => 'form-select filter-control'
        ]) ?>
    </div>

    <div class="col-lg-2">
        <div class="date-filter-wrap">
            <span class="date-filter-text" id="pickupDateText">
                <?= !empty($selectedPickupDate) ? h(date('d M Y', strtotime($selectedPickupDate))) : 'Collect Date: All' ?>
            </span>
            <i class="bi bi-chevron-down date-filter-chevron"></i>

            <?= $this->Form->control('pickup_date', [
                'label' => false,
                'type' => 'date',
                'value' => !empty($selectedPickupDate) ? $selectedPickupDate : null,
                'class' => 'native-date-input',
                'id' => 'pickupDateInput'
            ]) ?>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="search-wrap">
            <i class="bi bi-search search-icon"></i>
            <?= $this->Form->control('q', [
                'label' => false,
                'placeholder' => 'Search by Ref, customer, phone or address',
                'value' => $search,
                'class' => 'form-control filter-control'
            ]) ?>
        </div>
    </div>

    <div class="col-lg-2">
        <div class="filter-actions">
            <button class="filter-icon-btn" type="submit" title="Filter">
                <i class="bi bi-sliders"></i>
            </button>

            <a class="filter-icon-btn <?= $showArchived ? 'active' : '' ?>"
               href="<?= $this->Url->build([
                   'prefix' => 'Admin',
                   'controller' => 'BookingManagement',
                   'action' => 'index',
                   '?' => ['archived' => 1]
               ]) ?>"
               title="Archived Bookings">
                <i class="bi bi-archive"></i>
            </a>

            <a class="filter-icon-btn"
               href="<?= $this->Url->build([
                   'prefix' => 'Admin',
                   'controller' => 'BookingManagement',
                   'action' => 'index'
               ]) ?>"
               title="Reset">
                <i class="bi bi-arrow-clockwise"></i>
            </a>
        </div>
    </div>
</div>

        <?= $this->Form->end() ?>
    </div>

    <?php if ($showArchived): ?>
        <div class="archive-banner">
            Archived bookings list
        </div>
    <?php endif; ?>

    <div class="booking-table-wrap">
        <table class="table booking-table align-middle">
            <thead>
                <tr>
                    <th>Ref</th>
                    <th>Customer</th>
                    <th>Collection</th>
                    <th>Delivery</th>
                    <th>Service</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php if (!empty($bookings->toArray())): ?>
                <?php foreach ($bookings as $booking): ?>
                    <tr class="booking-row">
                        <td>
                            <div class="ref-code"><?= h($booking->booking_reference) ?></div>
                            <div class="mini-text">
                                Created:
                                <?= !empty($booking->created) ? h($booking->created->format('d M Y, h:i A')) : '-' ?>
                            </div>
                        </td>

                        <td>
                            <div class="main-text"><?= h($booking->shipper_name ?? '-') ?></div>
                            <div class="mini-text"><?= h($booking->shipper_phone ?? '-') ?></div>
                            <div class="mini-text"><?= h($booking->shipper_email ?? '-') ?></div>
                        </td>

                        <td>
    <?php if (($booking->collection_method ?? 'Pickup') === 'Drop Off'): ?>
        <div class="main-text"><?= h($booking->dropoff_location ?? 'Drop Off') ?></div>
        <div class="mini-text">Drop Off</div>
    <?php else: ?>
        <div class="main-text"><?= h($booking->shipper_address ?? '-') ?></div>
        <div class="mini-text">
            <?= !empty($booking->pickup_date) ? h($booking->pickup_date->format('d M Y')) : '-' ?>
            <?php if (!empty($booking->pickup_time)): ?>
                , <?= h($booking->pickup_time->format('h:i A')) ?>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</td>

                        <td>
                            <div class="main-text"><?= h($booking->delivery_address ?? '-') ?></div>
                            <div class="mini-text">
                                Deadline:
                                <?= !empty($booking->delivery_deadline) ? h($booking->delivery_deadline->format('d M Y')) : '-' ?>
                            </div>
                        </td>

                        <td>
                            <div class="main-text"><?= h($booking->delivery_speed ?? '-') ?></div>
                            <div class="mini-text">
                                <?= h($booking->mode_of_transport ?? '-') ?> ·
                                <?= h($booking->package_type ?? '-') ?>
                            </div>
                        </td>

                        <td>
                            <span class="status-badge <?= bookingStatusClass((string)($booking->status ?? 'Pending')) ?>">
                                <?= h($booking->status ?? 'Pending') ?>
                            </span>
                        </td>

                        <td>
                            <div class="action-dropdown">
                                <button type="button" class="action-toggle js-action-toggle" aria-label="Booking actions">
                                    <i class="bi bi-three-dots"></i>
                                </button>

                                <div class="action-menu js-action-menu">
                                    <a class="action-menu-item"
                                       href="<?= $this->Url->build([
                                           'prefix' => 'Admin',
                                           'controller' => 'BookingManagement',
                                           'action' => 'view',
                                           $booking->id
                                       ]) ?>">
                                        <i class="bi bi-eye"></i>
                                        <span>View</span>
                                    </a>

                                    <?php if ($showArchived): ?>
                                        <?= $this->Form->postLink(
                                            '<i class="bi bi-arrow-counterclockwise"></i><span>Undo Archive</span>',
                                            ['prefix' => 'Admin', 'controller' => 'BookingManagement', 'action' => 'unarchive', $booking->id],
                                            [
                                                'escape' => false,
                                                'class' => 'action-menu-item undo-item',
                                                'confirm' => 'Move this booking back to recent bookings?',
                                            ]
                                        ) ?>
                                    <?php else: ?>
                                        <?= $this->Form->postLink(
                                            '<i class="bi bi-archive"></i><span>Archive</span>',
                                            ['prefix' => 'Admin', 'controller' => 'BookingManagement', 'action' => 'archive', $booking->id],
                                            [
                                                'escape' => false,
                                                'class' => 'action-menu-item',
                                                'confirm' => 'Archive this booking?',
                                            ]
                                        ) ?>
                                    <?php endif; ?>
                                    <?= $this->Form->postLink(
                                        '<i class="bi bi-check-circle"></i><span>Approve</span>',
                                        ['prefix' => 'Admin', 'controller' => 'BookingManagement', 'action' => 'approve', $booking->id],
                                        [
                                            'escape' => false,
                                            'class' => 'action-menu-item',
                                        ]
                                    ) ?>
                                    <a href="javascript:void(0);"
                                       class="action-menu-item delete-item"
                                       data-bs-toggle="modal"
                                       data-bs-target="#rejectModal"
                                       data-booking-id="<?= $booking->id ?>">
                                        <i class="bi bi-ban"></i>
                                        <span>Reject</span>
                                    </a>

                                    <?= $this->Form->postLink(
                                        '<i class="bi bi-trash"></i><span>Delete</span>',
                                        ['prefix' => 'Admin', 'controller' => 'BookingManagement', 'action' => 'delete', $booking->id],
                                        [
                                            'escape' => false,
                                            'class' => 'action-menu-item delete-item',
                                            'confirm' => 'Delete this booking permanently?',
                                        ]
                                    ) ?>
                                </div>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php else: ?>
                <tr>
                    <td colspan="7">
                        <div class="empty-state">
                            <?= $showArchived ? 'No archived bookings found.' : 'No bookings found.' ?>
                        </div>
                    </td>
                </tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<div class="modal fade" id="rejectModal" tabindex="-1" aria-labelledby="rejectModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="rejectModalLabel">Reject Booking</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <?= $this->Form->create(null, ['id' => 'reject-form']) ?>
            <div class="modal-body">
                <p class="text-muted">Please provide a reason for rejecting this booking. An email will be sent to the user.</p>
                <?= $this->Form->hidden('booking_id', ['id' => 'modal-booking-id']) ?>
                <?= $this->Form->control('reason', [
                    'type' => 'textarea',
                    'class' => 'form-control',
                    'placeholder' => 'Enter the reason here...',
                    'required' => true,
                    'rows' => 3
                ]) ?>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" class="btn btn-danger" id="confirm-reject-btn">Confirm Reject</button>
            </div>
            <?= $this->Form->end() ?>
        </div>
    </div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
    const pickupDateInput = document.getElementById('pickupDateInput');
    const pickupDateText = document.getElementById('pickupDateText');

    function formatDateForDisplay(value) {
        if (!value) {
            return 'Collect Date: All';
        }

        const parts = value.split('-');
        if (parts.length !== 3) {
            return 'Collect Date: All';
        }

        const year = parts[0];
        const month = parts[1];
        const day = parts[2];

        const date = new Date(year, month - 1, day);
        const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

        return day + ' ' + months[date.getMonth()] + ' ' + year;
    }

    if (pickupDateInput && pickupDateText) {
        pickupDateInput.addEventListener('change', function () {
            pickupDateText.textContent = formatDateForDisplay(this.value);
        });
    }

    const toggles = document.querySelectorAll('.js-action-toggle');

    toggles.forEach(function (toggle) {
        toggle.addEventListener('click', function (event) {
            event.stopPropagation();

            const currentMenu = this.parentElement.querySelector('.js-action-menu');
            const allMenus = document.querySelectorAll('.js-action-menu');

            allMenus.forEach(function (menu) {
                if (menu !== currentMenu) {
                    menu.classList.remove('show');
                }
            });

            currentMenu.classList.toggle('show');
        });
    });

    document.addEventListener('click', function () {
        document.querySelectorAll('.js-action-menu').forEach(function (menu) {
            menu.classList.remove('show');
        });
    });

    document.querySelectorAll('.js-action-menu').forEach(function (menu) {
        menu.addEventListener('click', function (event) {
            event.stopPropagation();
        });
    });

    const rejectModal = document.getElementById('rejectModal');
    const rejectForm = document.getElementById('reject-form');
    const bookingIdInput = document.getElementById('modal-booking-id');
    if (rejectModal) {
        rejectModal.addEventListener('show.bs.modal', function(event) {
            const button = event.relatedTarget;
            const bookingId = button.getAttribute('data-booking-id');
            bookingIdInput.value = bookingId;
        });
    }
    if (rejectForm) {
        rejectForm.addEventListener('submit', function(e) {
            e.preventDefault();

            const currentId = bookingIdInput.value;
            const submitBtn = document.getElementById('confirm-reject-btn');

            submitBtn.disabled = true;
            submitBtn.innerHTML = 'Sending...';

            const formData = new FormData(this);
            fetch('<?= $this->Url->build(['prefix' => 'Admin', 'controller' => 'BookingManagement', 'action' => 'reject']) ?>/' + currentId, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRF-Token': '<?= $this->request->getAttribute('csrfToken') ?>',
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('Error: ' + (data.message || 'Unknown error occurred.'));
                        submitBtn.disabled = false;
                        submitBtn.innerHTML = 'Confirm Reject';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while processing the request.');
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = 'Confirm Reject';
                });
        });
    }
});
</script>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
