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

<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="admin_office_edit_form" method="post" class="card-body" enctype="multipart/form-data">
                        <h4 class="card-title">Edit Administrative Office <hr></h4>

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

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Title</label>
                                    <input type="text" name="title" class="form-control" required value="<?= esc($office['title']) ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Head Name</label>
                                    <input type="text" name="head_name" class="form-control" required value="<?= esc($office['head_name']) ?>">
                                </div>
                            </div>
                        </div>

                        <div class="row mt-2">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Mobile</label>
                                    <input type="text" name="mobile" class="form-control" required value="<?= esc($office['mobile']) ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Email</label>
                                    <input type="email" name="email" class="form-control" required value="<?= esc($office['email']) ?>">
                                </div>
                            </div>
                        </div>

                        <div class="row mt-2">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label class="font-weight-bold">Available Time</label>
                                    <input type="text" name="time" class="form-control" required value="<?= esc($office['time']) ?>">
                                </div>
                            </div>
                        </div>

                        <div class="form-group mt-3">
                            <label class="font-weight-bold">Address</label>
                            <input type="text" name="address" class="form-control" required value="<?= esc($office['address']) ?>">
                        </div>

                        <div class="form-group mt-3">
                            <label class="font-weight-bold">Services</label>
                            <input type="text" id="service_input" class="form-control" placeholder="Type service name and press comma" />
                            <div id="service_tags" class="mt-2"></div>
                            <input type="hidden" name="services" id="services_hidden" />
                        </div>

                        <button type="submit" class="btn btn-primary btn-sm mt-4">
                            <i class="mdi mdi-check"></i>&nbsp;&nbsp;Update
                        </button>
                    </form>
                </div>

                <footer class="footer mt-3">
                    <div class="d-sm-flex justify-content-center justify-content-sm-between">
                        <span class="text-muted">© <?= date('Y') ?> <?= COMPANY_FULL_NAME ?>. All rights reserved.</span>
                        <span class="float-sm-right">With gratitude from <i class="mdi mdi-heart text-danger"></i>
                            <a href="<?= CREDIT_LINK ?>" target="_blank"><?= CREDIT_TITLE ?></a></span>
                    </div>
                </footer>
            </div>
        </div>
    </div>
</div>

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

<style>
    #service_tags .badge {
        font-size: 14px;
        padding: 6px 10px;
        margin-right: 5px;
        margin-top: 5px;
        display: inline-block;
    }
    .remove-tag {
        cursor: pointer;
    }
</style>

<script>
    $(document).ready(function () {
        let services = [];

        // Populate initial services
        const existingServices = "<?= esc($office['services']) ?>";
        if (existingServices) {
            services = existingServices.split(',').map(s => s.trim());
            services.forEach(service => {
                $('#service_tags').append(
                    `<span class="badge badge-info">
                        ${service}
                        <i class="mdi mdi-close text-white ml-1 remove-tag" data-val="${service}"></i>
                    </span>`
                );
            });
            updateServiceHiddenInput();
        }

        $('#service_input').on('keyup', function (e) {
            if (e.key === ',' || e.keyCode === 188) {
                let val = $(this).val().trim().replace(',', '');
                if (val !== '') {
                    if (!services.includes(val)) {
                        services.push(val);
                        $('#service_tags').append(
                            `<span class="badge badge-info">
                                ${val}
                                <i class="mdi mdi-close text-white ml-1 remove-tag" data-val="${val}"></i>
                            </span>`
                        );
                        updateServiceHiddenInput();
                    }
                }
                $(this).val('');
            }
        });

        $(document).on('click', '.remove-tag', function () {
            let val = $(this).data('val');
            services = services.filter(item => item !== val);
            $(this).parent().remove();
            updateServiceHiddenInput();
        });

        function updateServiceHiddenInput() {
            $('#services_hidden').val(services.join(','));
        }

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

            const csrfTokenName = '<?= csrf_token() ?>';
            const csrfTokenValue = '<?= csrf_hash() ?>';
            const jwtToken = localStorage.getItem('jwt_token');

            const formData = new FormData(this);
            formData.append(csrfTokenName, csrfTokenValue);

            $.ajax({
                url: '<?= base_url('api/contact/administrative-offices/update') ?>',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                headers: {
                    'Authorization': 'Bearer ' + jwtToken
                },
                success: function (response) {
                    if (response.status) {
                        toast('success', response.message);
                        window.location.href = '<?= base_url('backdesk/contacts/administrative-offices/index') ?>';
                    } else {
                        toast('danger', response.message || 'Something went wrong!');
                    }
                }
            });
        });
    });
</script>
</body>
</html>
