<?php echo $this->extend('template/admin/main') ?>

<?php echo $this->section('content') ?>

    <?php echo $this->include('common/message') ?>

    <style>
        .notification-stat-card {
            cursor: pointer;
            transition: box-shadow 0.2s ease, border-color 0.2s ease, transform 0.15s ease;
            border: 2px solid transparent;
        }

        .notification-stat-card:hover {
            box-shadow: 0 0.35rem 1rem rgba(0, 0, 0, 0.12);
            transform: translateY(-1px);
        }

        .notification-stat-card.is-active {
            border-color: var(--bs-primary);
            box-shadow: 0 0.35rem 1rem rgba(13, 110, 253, 0.18);
        }

        .notification-stat-card[data-status-filter="sent"].is-active {
            border-color: var(--bs-success);
        }

        .notification-stat-card[data-status-filter="scheduled"].is-active {
            border-color: var(--bs-warning);
        }

        .notification-stat-card[data-status-filter="cancelled"].is-active {
            border-color: var(--bs-danger);
        }
    </style>

    <div class="card mb-4">
        <div class="card-body">
            <div class="row align-items-center">
                <div class="col-md-6">
                    <h5 class="card-title mb-0">Notification Management</h5>
                </div>
                <div class="col-md-6 text-end">
                    <?php if ($add_data == true) : ?>
                        <a class="btn btn-success" href="<?php echo base_url(route_to('new-notification')) ?>">
                            <i class="fas fa-plus"></i> Create New Notification
                        </a>
                    <?php endif ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row mb-4">
        <div class="col-lg-3 col-sm-6 mb-3 mb-lg-0">
            <div class="card h-100 notification-stat-card is-active" data-status-filter="all" role="button" tabindex="0" aria-pressed="true">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5 class="mb-0"><?php echo (int) ($stats['total'] ?? 0) ?></h5>
                            <small class="text-muted">Total Notifications</small>
                        </div>
                        <div class="text-primary">
                            <i class="fas fa-bell fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-sm-6 mb-3 mb-lg-0">
            <div class="card h-100 notification-stat-card" data-status-filter="sent" role="button" tabindex="0" aria-pressed="false">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5 class="mb-0"><?php echo (int) ($stats['sent'] ?? 0) ?></h5>
                            <small class="text-muted">Sent</small>
                        </div>
                        <div class="text-success">
                            <i class="fas fa-check-circle fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-sm-6 mb-3 mb-lg-0">
            <div class="card h-100 notification-stat-card" data-status-filter="scheduled" role="button" tabindex="0" aria-pressed="false">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5 class="mb-0"><?php echo (int) ($stats['scheduled'] ?? 0) ?></h5>
                            <small class="text-muted">Scheduled</small>
                        </div>
                        <div class="text-warning">
                            <i class="fas fa-clock fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-3 col-sm-6">
            <div class="card h-100 notification-stat-card" data-status-filter="cancelled" role="button" tabindex="0" aria-pressed="false">
                <div class="card-body">
                    <div class="d-flex justify-content-between">
                        <div>
                            <h5 class="mb-0"><?php echo (int) ($stats['cancelled'] ?? 0) ?></h5>
                            <small class="text-muted">Cancelled</small>
                        </div>
                        <div class="text-danger">
                            <i class="fas fa-times-circle fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="row align-items-center mb-3">
                <div class="col-md-7">
                    <div id="notification-filter-label" class="small text-muted mb-md-0 mb-2">
                        Showing: <strong>Admin notifications</strong>
                        <?php if ((int) ($stats['trip_reminders'] ?? 0) > 0) : ?>
                            <span class="text-muted">(<?php echo number_format((int) $stats['trip_reminders']) ?> auto trip reminders hidden — use scope filter to view)</span>
                        <?php endif ?>
                    </div>
                </div>
                <div class="col-md-5">
                    <label for="notification-scope-filter" class="form-label small mb-1">List scope</label>
                    <select id="notification-scope-filter" class="form-select form-select-sm">
                        <option value="admin" selected>Admin notifications (<?php echo number_format((int) ($stats['admin_created'] ?? 0)) ?>)</option>
                        <option value="trip_reminders">Trip reminders only (<?php echo number_format((int) ($stats['trip_reminders'] ?? 0)) ?>)</option>
                        <option value="all">All notifications (<?php echo number_format((int) ($stats['total'] ?? 0)) ?>)</option>
                    </select>
                </div>
            </div>

            <div class="table-responsive">
                <table class="table display table-bordered table-striped table-hover basic" id="notificationTable" data-server="1">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Subject</th>
                            <th scope="col">Type</th>
                            <th scope="col">Target Group</th>
                            <th scope="col">Scheduled Date</th>
                            <th scope="col">Status</th>
                            <th scope="col">Notification Type</th>
                            <th scope="col">Created By</th>
                            <th scope="col">Created Date</th>
                            <th scope="col">Actions</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>

    <input type="hidden" name="<?php echo csrf_token(); ?>" id="csrf_token" value="<?php echo csrf_hash(); ?>">

<?php echo $this->include('common/datatable_default_lang_change') ?>

<?php echo $this->endSection() ?>

<?php echo $this->section('js') ?>
<script>
function cancelNotification(id) {
    if (confirm('Are you sure you want to cancel this notification?')) {
        var form = document.createElement('form');
        form.method = 'POST';
        form.action = '<?php echo base_url('modules/backend/notifications/cancel/') ?>' + id;

        var csrf = document.createElement('input');
        csrf.type = 'hidden';
        csrf.name = '<?= csrf_token() ?>';
        csrf.value = '<?= csrf_hash() ?>';
        form.appendChild(csrf);

        document.body.appendChild(form);
        form.submit();
    }
}

$(document).ready(function () {
    if (typeof $.fn.DataTable === 'undefined' || !$('#notificationTable').length) {
        return;
    }

    var companyname = $("#logotext").val() || "Notifications";
    var statusFilter = 'all';
    var scopeFilter = 'admin';
    var statusLabels = {
        all: 'All statuses',
        sent: 'Sent notifications',
        scheduled: 'Scheduled notifications',
        cancelled: 'Cancelled notifications'
    };
    var scopeLabels = {
        admin: 'Admin notifications',
        trip_reminders: 'Trip reminders only',
        all: 'All notifications'
    };

    if ($.fn.DataTable.isDataTable('#notificationTable')) {
        $('#notificationTable').DataTable().destroy();
    }

    function updateFilterLabel() {
        $('#notification-filter-label').html(
            'Showing: <strong>' + scopeLabels[scopeFilter] + ' — ' + statusLabels[statusFilter] + '</strong>'
        );
    }

    function setActiveStatCard(filter) {
        $('.notification-stat-card').removeClass('is-active').attr('aria-pressed', 'false');
        $('.notification-stat-card[data-status-filter="' + filter + '"]')
            .addClass('is-active')
            .attr('aria-pressed', 'true');
        updateFilterLabel();
    }

    var table = $('#notificationTable').DataTable({
        processing: true,
        serverSide: true,
        pageLength: 25,
        lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
        dom: 'lBfrtip',
        language: {
            search: search,
            lengthMenu: lengthMenu,
            zeroRecords: zeroRecords,
            info: info,
            infoEmpty: infoEmpty,
            infoFiltered: infoFiltered,
            paginate: {
                first: first,
                previous: previous,
                next: next,
                last: last
            }
        },
        ajax: {
            url: "<?= base_url(route_to('server-notification-list')); ?>",
            type: "POST",
            data: function(d) {
                var csrfToken = $('#csrf_token').val();
                if (csrfToken) {
                    d.<?php echo csrf_token(); ?> = csrfToken;
                }
                d.status_filter = statusFilter;
                d.scope_filter = scopeFilter;
                return d;
            },
            beforeSend: function(xhr) {
                var csrfToken = $('#csrf_token').val();
                if (csrfToken) {
                    xhr.setRequestHeader('X-CSRF-TOKEN', csrfToken);
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                }
            },
            dataSrc: 'data',
            error: function(xhr) {
                if (xhr.status === 403) {
                    alert("CSRF token validation failed. Please refresh the page and try again.");
                }
            }
        },
        buttons: [
            { extend: 'copy', title: companyname, messageTop: companyname, exportOptions: { columns: [0,1,2,3,4,5,6,7,8] } },
            { extend: 'csv', title: companyname, messageTop: companyname, exportOptions: { columns: [0,1,2,3,4,5,6,7,8] } },
            { extend: 'excel', title: companyname, messageTop: companyname, exportOptions: { columns: [0,1,2,3,4,5,6,7,8] } },
            { extend: 'pdf', title: companyname, messageTop: companyname, exportOptions: { columns: [0,1,2,3,4,5,6,7,8] } },
            { extend: 'print', title: companyname, messageTop: companyname, exportOptions: { columns: [0,1,2,3,4,5,6,7,8] } }
        ],
        columns: [
            { data: "index", orderable: false },
            { data: "subject", orderable: true },
            { data: "target_group", orderable: false, searchable: false },
            { data: "trip_name", orderable: true },
            { data: "notification_date", orderable: true },
            { data: "status", orderable: true, searchable: false },
            { data: "notification_type", orderable: true },
            { data: "created_by_name", orderable: false },
            { data: "created_at", orderable: true },
            { data: "action", orderable: false, searchable: false }
        ],
        order: [[8, 'desc']],
        responsive: true,
        columnDefs: [
            { targets: [2, 5, 7, 9], orderable: false }
        ]
    });

    $('.notification-stat-card').on('click keypress', function(e) {
        if (e.type === 'keypress' && e.which !== 13 && e.which !== 32) {
            return;
        }
        e.preventDefault();

        var nextFilter = $(this).data('status-filter');
        if (!nextFilter || nextFilter === statusFilter) {
            return;
        }

        statusFilter = nextFilter;
        setActiveStatCard(statusFilter);
        table.ajax.reload();
    });

    $('#notification-scope-filter').on('change', function() {
        scopeFilter = $(this).val() || 'admin';
        updateFilterLabel();
        table.ajax.reload();
    });
});
</script>
<?php echo $this->endSection() ?>
