<?= 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_edit_form" method="post" enctype="multipart/form-data" class="card-body">
                        <h4 class="card-title">Edit Page Media</h4><hr>

                        <input type="hidden" name="id" value="<?= esc($media['id']) ?>">

                        <!-- 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']) ?>" <?= $media['menu_id'] == $menu['id'] ? 'selected' : '' ?>>
                                                <?= esc($menu['name']) ?>
                                            </option>
                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                            </div>

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

                        <!-- Media Upload -->
                        <div class="row mt-3">
                            <div class="col-md-6">
                                <label class="font-weight-bold">Replace Image(s)</label>
                                <input type="file" name="media_files[]" class="form-control" multiple accept="image/*">
                                <?php if (!empty($media['image'])): ?>
                                    <div class="mt-2">
                                        <img src="<?= esc($media['image']) ?>" alt="Existing Media" width="150">
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Submit -->
                        <div class="row mt-4">
                            <div class="col-md-12">
                                <button type="submit" class="btn btn-primary btn-sm">
                                    <i class="mdi mdi-content-save"></i> Update 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) ?>;
    const selectedMenuId = '<?= esc($media['menu_id']) ?>';
    const selectedSubmenuId = '<?= esc($media['submenu_id']) ?>';

    // Load submenu 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) {
                const selected = (menu.id == selectedSubmenuId) ? 'selected' : '';
                submenuSelect.append(`<option value="${menu.id}" ${selected}>${menu.name}</option>`);
            }
        });
    }).trigger('change');

    $('#media_edit_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/update-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 updated successfully');
                    setTimeout(() => {
                        window.location.href = '<?= base_url('backdesk/page-media/index') ?>';
                    }, 1000);
                } else {
                    toast('danger', response.message || 'Update failed');
                }
            },
            error: function (xhr) {
                console.error(xhr);
                toast('danger', 'Something went wrong');
            }
        });
    });
});
</script>
</body>
</html>
