@extends('layouts.app')

@section('content')
    <div class="pcoded-content">
        <div class="pcoded-inner-content">
            <div class="main-body">
                <div class="page-wrapper">

                    <div class="page-header card page-body">
                        <div class="row align-items-end">
                            <div class="col-lg-8">
                                <div class="page-header-title">
                                    <i class="icofont icofont-file-document bg-c-pink"></i>
                                    <div class="d-inline">
                                        <h4>License Keys</h4>
                                        <span>Manage license keys for system resources</span>
                                    </div>
                                </div>
                            </div>
                            <div class="col-lg-4 text-right">
                                <button class="btn btn-primary" data-toggle="modal" data-target="#addLicenseKeyModal">
                                    Add New License Key
                                </button>
                            </div>
                        </div>
                        <hr>

                        <!-- License Keys Table -->
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h5>License Key List</h5>
                                    </div>
                                    <div class="card-block">
                                        <div class="table-responsive">
                                            <table class="table table-striped table-bordered">
                                                <thead>
                                                <tr>
                                                    <th>#</th>
                                                    <th>Resource</th>
                                                    <th>Key</th>
                                                    <th>Start Date</th>
                                                    <th>End Date</th>
                                                </tr>
                                                </thead>
                                                <tbody>
                                                @foreach($licenseKeys as $index => $license)
                                                    <tr>
                                                        <td>{{ $index + 1 }}</td>
                                                        <td>{{ $license->resource }}</td>
                                                        <td>{{ $license->key }}</td>
                                                        <td>{{ $license->start_date }}</td>
                                                        <td>{{ $license->end_date }}</td>
                                                    </tr>
                                                @endforeach
                                                </tbody>
                                            </table>
                                            @if(count($licenseKeys) === 0)
                                                <p class="text-center">No license keys available.</p>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="modal fade" id="addLicenseKeyModal" tabindex="-1" role="dialog" aria-labelledby="addLicenseKeyModalLabel" aria-hidden="true">
                            <div class="modal-dialog" role="document">
                                <form action="{{ route('license-keys.store') }}" method="POST" onsubmit="return validateDates()">
                                    <input type="text" name="_hp" value="" autocomplete="off" tabindex="-1" style="position:absolute;left:-9999px;opacity:0;height:0;width:0;" aria-hidden="true">
                                    @csrf
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title" id="addLicenseKeyModalLabel">Add License Key</h5>
                                            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                                <span aria-hidden="true">&times;</span>
                                            </button>
                                        </div>
                                        <div class="modal-body">

                                            <div class="form-group">
                                                <label for="resource">Resource</label>
                                                <select name="resource" class="form-control" required>
                                                    <option value="">-- Select Resource --</option>
                                                    @foreach($resources as $resource)
                                                        <option value="{{ $resource }}">{{ $resource }}</option>
                                                    @endforeach
                                                </select>
                                            </div>

                                            <div class="form-group">
                                                <label for="key">Key</label>
                                                <input type="text" name="key" class="form-control" required maxlength="255">
                                            </div>

                                            <div class="form-group">
                                                <label for="start_date">Start Date</label>
                                                <input type="text" name="start_date" id="from" class="form-control datepicker" required autocomplete="off" placeholder="YYYY-MM-DD">
                                            </div>

                                            <div class="form-group">
                                                <label for="end_date">End Date</label>
                                                <input type="text" name="end_date" id="to" class="form-control datepicker" required autocomplete="off" placeholder="YYYY-MM-DD">
                                            </div>

                                        </div>
                                        <div class="modal-footer">
                                            <button type="submit" class="btn btn-success">Save</button>
                                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
                <div id="styleSelector"></div>
            </div>
        </div>
    </div>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        /*
         * Flatpickr inside Bootstrap modal fix.
         * The calendar must sit above the modal/backdrop and must not be clipped by the
         * modal body/content. Some admin themes apply overflow/transform rules that
         * otherwise make the calendar appear behind the form.
         */
        #addLicenseKeyModal,
        #addLicenseKeyModal .modal-dialog,
        #addLicenseKeyModal .modal-content,
        #addLicenseKeyModal .modal-body {
            overflow: visible !important;
        }

        #addLicenseKeyModal .modal-body {
            position: relative;
        }

        .modal-open .flatpickr-calendar,
        .flatpickr-calendar.open {
            z-index: 2147483647 !important;
        }

        .flatpickr-calendar {
            z-index: 2147483647 !important;
        }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>

        let licenseKeyDatePickersInitialised = false;

        function initialiseLicenseKeyDatePickers() {
            if (licenseKeyDatePickersInitialised) {
                return;
            }

            const modal = document.getElementById('addLicenseKeyModal');
            const modalBody = modal ? modal.querySelector('.modal-body') : document.body;

            if (typeof flatpickr !== 'function') {
                // Fallback in case the CDN fails to load.
                document.querySelectorAll('#from, #to').forEach(function (input) {
                    input.setAttribute('type', 'date');
                });
                licenseKeyDatePickersInitialised = true;
                return;
            }

            flatpickr('#from', {
                dateFormat: 'Y-m-d',
                allowInput: true,
                appendTo: modalBody,
                positionElement: document.getElementById('from'),
                disableMobile: true,
                onOpen: function(selectedDates, dateStr, instance) {
                    instance.calendarContainer.style.zIndex = '2147483647';
                }
            });

            flatpickr('#to', {
                dateFormat: 'Y-m-d',
                allowInput: true,
                appendTo: modalBody,
                positionElement: document.getElementById('to'),
                disableMobile: true,
                onOpen: function(selectedDates, dateStr, instance) {
                    instance.calendarContainer.style.zIndex = '2147483647';
                }
            });

            licenseKeyDatePickersInitialised = true;
        }

        if (window.jQuery) {
            $('#addLicenseKeyModal').on('shown.bs.modal', function () {
                initialiseLicenseKeyDatePickers();
            });
        }

        document.addEventListener('DOMContentLoaded', function () {
            initialiseLicenseKeyDatePickers();
        });

        function validateDates() {
            const fromValue = document.getElementById('from').value;
            const toValue = document.getElementById('to').value;

            if (!fromValue || !toValue) {
                alert("Please select both Start Date and End Date.");
                return false;
            }

            const start = new Date(fromValue + 'T00:00:00');
            const end = new Date(toValue + 'T00:00:00');

            if (start > end) {
                alert("Start date cannot be after End date.");
                return false;
            }
            return true;
        }


        @if (session('success'))
        Swal.fire({
            icon: 'success',
            title: 'Success',
            text: "{{ session('success') }}",
            timer: 3000,
            showConfirmButton: false
        });
        @endif

        @if (session('error'))
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: "{{ session('error') }}",
            timer: 3000,
            showConfirmButton: false
        });
        @endif


    </script>

@endsection
