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

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

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

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

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

        .offer-stat-card[data-status-filter="active"].is-active {
            border-color: var(--bs-success);
            box-shadow: 0 0.35rem 1rem rgba(25, 135, 84, 0.18);
        }

        .offer-stat-card[data-status-filter="inactive"].is-active {
            border-color: var(--bs-warning);
            box-shadow: 0 0.35rem 1rem rgba(255, 193, 7, 0.22);
        }
    </style>

    <div class="row mb-4">
        <div class="col-lg-4 col-sm-6 mb-3 mb-lg-0">
            <div class="card h-100 offer-stat-card" data-status-filter="all" role="button" tabindex="0" aria-pressed="false" title="Show all offers">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="mb-0"><?php echo (int) ($stats['total'] ?? 0) ?></h5>
                            <small class="text-muted">Total Offers</small>
                        </div>
                        <div class="text-primary">
                            <i class="fas fa-gift fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4 col-sm-6 mb-3 mb-lg-0">
            <div class="card h-100 offer-stat-card is-active" data-status-filter="active" role="button" tabindex="0" aria-pressed="true" title="Show active offers only">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="mb-0"><?php echo (int) ($stats['active'] ?? 0) ?></h5>
                            <small class="text-muted">Active Offers</small>
                        </div>
                        <div class="text-success">
                            <i class="fas fa-check-circle fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-4 col-sm-6">
            <div class="card h-100 offer-stat-card" data-status-filter="inactive" role="button" tabindex="0" aria-pressed="false" title="Show inactive offers only">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h5 class="mb-0"><?php echo (int) ($stats['inactive'] ?? 0) ?></h5>
                            <small class="text-muted">Inactive Offers</small>
                        </div>
                        <div class="text-warning">
                            <i class="fas fa-clock fa-2x"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="card mb-4">
        <div class="card-body">

            <?php if ($add_data == true) : ?>
                <div class="text-end mb-3">
                    <a class="btn btn-success" href="<?php echo base_url(route_to('new-offer')) ?>">
                        <i class="fas fa-gift"></i><sup><i class="fas fa-plus small"></i></sup>
                        <?php echo lang("Localize.add_offer") ?>
                    </a>
                </div>
            <?php endif ?>

            <div id="offer-filter-label" class="small text-muted mb-2">Showing: <strong>Active offers only</strong></div>

            <div class="table-responsive">
                <table class="table display table-bordered table-striped table-hover basic" id="offerlist">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col"><?php echo lang('Localize.offer_title'); ?></th>
                            <th scope="col"><?php echo lang("Localize.code") ?></th>
                            <th><?php echo lang('Localize.company'); ?></th>
                            <th scope="col"><?php echo lang('Localize.discount'); ?></th>
                            <th scope="col"><?php echo lang('Localize.minimum_passengers'); ?></th>
                            <th scope="col"><?php echo lang("Localize.start") ?> <?php echo lang("Localize.date") ?></th>
                            <th scope="col"><?php echo lang("Localize.end") ?> <?php echo lang("Localize.date") ?></th>
                            <th scope="col">Status</th>
                            <th scope="col"><?php echo lang("Localize.action") ?></th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>

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

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

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

<?php echo $this->section('js') ?>
<script>
    $(document).ready(function () {
        if (typeof $.fn.DataTable === 'undefined') {
            console.error('DataTables is not loaded.');
            return;
        }

        var companyname = $("#logotext").val() || "<?php echo lang('Localize.offer_list'); ?>";
        var statusFilter = 'active';
        var filterLabels = {
            all: 'All offers',
            active: 'Active offers only',
            inactive: 'Inactive offers only'
        };

        if ($('#offerlist').length === 0) {
            return;
        }

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

        function setActiveStatCard(filter) {
            $('.offer-stat-card').removeClass('is-active').attr('aria-pressed', 'false');
            $('.offer-stat-card[data-status-filter="' + filter + '"]')
                .addClass('is-active')
                .attr('aria-pressed', 'true');
            $('#offer-filter-label').html('Showing: <strong>' + filterLabels[filter] + '</strong>');
        }

        var table = $('#offerlist').DataTable({
            processing: true,
            serverSide: true,
            lengthMenu: [[10, 15, 20, 25, 30, 40, 50, -1], [10, 15, 20, 25, 30, 40, 50, "All"]],
            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-offer-list')); ?>",
                type: "POST",
                data: function(d) {
                    var csrfToken = $('#csrf_token').val() || $('input[name="<?php echo csrf_token(); ?>"]').val();
                    if (csrfToken) {
                        d.<?php echo csrf_token(); ?> = csrfToken;
                    }
                    d.status_filter = statusFilter;
                    return d;
                },
                beforeSend: function(xhr) {
                    var csrfToken = $('#csrf_token').val() || $('input[name="<?php echo 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: "offer_title", orderable: false },
                { data: "code" },
                { data: "company" },
                { data: "discount", orderable: false },
                { data: "min_passengers" },
                { data: "start_date" },
                { data: "end_date" },
                { data: "status", orderable: false, searchable: false },
                { data: "action", orderable: false, searchable: false }
            ],
            responsive: true,
            columnDefs: [
                { targets: [1, 8, 9], orderable: false }
            ]
        });

        $('.offer-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();
        });
    });
</script>
<?php echo $this->endSection() ?>
