<?= view('common/top_header_backdesk.php') ?>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
    .form-control, select.form-control {
        outline: 1px solid #67676b;
        border-radius: 5px;
        padding: 8px 10px;
    }
    .error {
        color: red;
        padding-top: 10px;
    }
</style>
</head>

<body>
<div class="container-scroller">
    <?= view('common/top_navbar') ?>
    <div class="container-fluid page-body-wrapper">
        <?= view('common/side_navbar') ?>
        <div class="main-panel">
            <div class="content-wrapper">
                <div class="card">
                    <form id="media_upload_form" method="post" enctype="multipart/form-data" class="card-body">
                        <h4 class="card-title">Add Page Media</h4><hr>

                        <!-- Menu -->
                        <div class="row">
                            <div class="col-md-6">
                                <label class="font-weight-bold">Menu <span class="text-danger">*</span></label>
                                <select name="menu_id" id="menu_id" class="form-control select2" required>
                                    <option value="">-- Select Menu --</option>
                                    <?php foreach ($menus as $menu): ?>
                                        <?php if ($menu['parent_id'] == 0): ?>
                                            <option value="<?= esc($menu['id']) ?>"><?= esc($menu['name']) ?></option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <!-- Submenu -->
                            <div class="col-md-6">
                                <label class="font-weight-bold">Submenu <span class="text-danger">*</span></label>
                                <select name="submenu_id" id="submenu_id" class="form-control select2" required>
                                    <option value="">-- Select Submenu --</option>
                                </select>
                            </div>
                        </div>

                        <!-- Media Upload -->
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <label class="font-weight-bold">Upload Image(s) <span class="text-danger">*</span></label>
                                <input type="file" name="media_files[]" class="form-control" multiple accept="image/*" required>
                            </div>
                        </div>

                        <!-- Submit -->
                        <div class="row mt-4">
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-success btn-sm">
                                    <i class="mdi mdi-upload"></i> Upload Media
                                </button>
                                <a href="<?= base_url('backdesk/page-media/index') ?>" class="btn btn-secondary btn-sm">Cancel</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <?= view('common/footer_backdesk.php') ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function () {
    $('.select2').select2();

    const allMenus = <?= json_encode($menus) ?>;

    // Load submenu options based on selected menu
    $('#menu_id').on('change', function () {
        const selectedMenu = $(this).val();
        const submenuSelect = $('#submenu_id');
        submenuSelect.empty().append('<option value="">-- Select Submenu --</option>');

        allMenus.forEach(menu => {
            if (menu.parent_id == selectedMenu) {
                submenuSelect.append(`<option value="${menu.id}">${menu.name}</option>`);
            }
        });

        submenuSelect.trigger('change');
    });

    $('#media_upload_form').on('submit', function (e) {
        e.preventDefault();

        const jwtToken = localStorage.getItem('jwt_token');

        if (!jwtToken) {
            toast('danger', 'Unauthorized: Please login again.');
            return;
        }

        const formData = new FormData(this);

        $.ajax({
            url: '<?= base_url('api/page-media/add-media') ?>',
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + jwtToken
            },
            data: formData,
            contentType: false,
            processData: false,
            success: function (response) {
                if (response.status === true || response.status === 200) {
                    toast('success', response.message || 'Media uploaded successfully');
                    setTimeout(() => {
                        window.location.href = '<?= base_url('backdesk/page-media/index') ?>';
                    }, 1000);
                } else {
                    toast('danger', response.message || 'Upload failed');
                }
            },
            error: function (xhr) {
                console.error(xhr);
                if (xhr.status === 401) {
                    toast('danger', 'Unauthorized. Please login again.');
                    // setTimeout(() => {
                    //     window.location.href = '<?= base_url('login') ?>';
                    // }, 1500);
                } else {
                    toast('danger', 'Something went wrong');
                }
            }
        });
    });


});
</script>
</body>
</html>
