<?php echo message_box('success');
$type = $this->uri->segment(4);
$selected_notified_users = array();
$selected_notified_user_ids = json_decode(config_item('notified_user'));
if (!empty($selected_notified_user_ids)) {
    $all_user_info = get_result('tbl_users', array('role_id !=' => 2, 'activated' => 1));
    if (!empty($all_user_info)) {
        foreach ($all_user_info as $v_user) {
            if (in_array($v_user->user_id, $selected_notified_user_ids)) {
                $profile_info = $this->db->where('user_id', $v_user->user_id)->get('tbl_account_details')->row();
                if (!empty($profile_info)) {
                    $selected_notified_users[] = array(
                        'id' => $v_user->user_id,
                        'text' => $profile_info->fullname,
                    );
                }
            }
        }
    }
}
?>

<div class="space-y-6">
    <!-- Start Form -->
    <div class="w-full">
        <form role="form" enctype="multipart/form-data"
              action="<?php echo base_url(); ?>admin/settings/save_email_integration"
              method="post"
              class="space-y-6">
            <div class="rounded-2xl border border-border bg-card shadow-sm">
                <div class="border-b border-border bg-muted/50 px-6 py-4">
                    <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                        <h2 class="text-lg font-semibold text-foreground">
                            <?= lang('email_integration') . ' ' . lang('for') . ' ' . (!empty($type) && strtolower($type) == 'leads' ? lang('leads') : lang('tickets')) ?>
                        </h2>
                        <a class="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-4 py-2 text-sm font-medium text-primary-foreground shadow-sm hover:bg-primary/90 transition-colors"
                           href="<?= base_url('admin/settings/email_integration/' . (!empty($type) && strtolower($type) == 'leads' ? '' : 'Leads')) ?>">
                            <i class="text-xs" data-lucide="mail"></i>
                            <?= lang('set') . ' ' . lang('email') . ' ' . lang('for') . ' ' . (!empty($type) && strtolower($type) == 'leads' ? lang('tickets') : lang('leads')) ?>
                        </a>
                    </div>
                </div>
                <div class="p-6">
                    <?php
                    $trace_msg = $this->session->userdata('header');
                    if (!empty($trace_msg)) {
                        ?>
                        <div class="rounded-lg border border-border bg-card shadow-sm" id="copyright-wrap">
                            <div class="flex items-center justify-between border-b border-border bg-muted/50 px-4 py-3">
                                <h3 class="text-sm font-semibold text-foreground"><?= $this->session->userdata('header'); ?></h3>
                                <button type="button" class="text-muted-foreground hover:text-foreground" data-target="#copyright-wrap" data-dismiss="alert">
                                    <i data-lucide="x"></i>
                                </button>
                            </div>
                            <div class="p-4">
                                <div class="rounded-lg <?= ($this->session->userdata('type') == 'error' ? 'bg-destructive/10 text-destructive' : 'bg-primary/10 text-primary') ?> px-4 py-3">
                                    <?php echo $trace_msg ?>
                                </div>
                            </div>
                        </div>
                    <?php }
                    $this->session->unset_userdata('header');
                    ?>
                    <?php echo validation_errors(); ?>
                    <input type="hidden" name="settings" value="<?= $load_setting ?>">
                    
                    <?php if (empty($type) || !empty($type) && is_numeric($type)) { ?>
                        <div class="mx-auto max-w-5xl space-y-4">
                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr]">
                                <label class="pt-2 text-right text-sm font-medium text-foreground"><?= lang('postmaster_link') ?></label>
                                <div class="rounded-lg bg-muted px-4 py-2">
                                    <code class="text-sm font-mono text-foreground">wget -q -O- <?= base_url() ?>postmaster/tickets</code>
                                </div>
                            </div>
                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr]">
                                <label class="pt-0 text-right text-sm font-medium text-foreground"><?= lang('last_postmaster_run') ?></label>
                                <div class="text-sm font-semibold text-foreground">
                                    <?php
                                    $last_tickets_postmaster_run = config_item('last_tickets_postmaster_run');
                                    if (!empty($last_tickets_postmaster_run)) {
                                        echo display_datetime($last_tickets_postmaster_run, true);
                                    } else {
                                        echo "-";
                                    } ?>
                                </div>
                            </div>
                        </div>
                        <?php $all_departments = get_result('tbl_departments');
                        if (!empty($all_departments)) {
                            foreach ($all_departments as $d_key => $v_departments) {
                                $department_open = !empty($type) && is_numeric($type) && (int) $type === (int) $v_departments->departments_id;
                                ?>
                                <div class="border border-border rounded-lg overflow-hidden mt-3">
                                    <button type="button" class="w-full flex items-center justify-between bg-muted/30 px-4 py-3 text-left hover:bg-muted/50 transition-colors" data-email-integration-toggle data-target="#dept_<?php echo $d_key ?>" aria-expanded="<?= $department_open ? 'true' : 'false' ?>">
                                        <span class="flex items-center gap-2 text-sm font-medium text-foreground">
                                            <i data-lucide="settings"></i>
                                            <?php echo $v_departments->deptname; ?>
                                        </span>
                                        <i class="text-xs text-muted-foreground transition-transform <?= $department_open ? 'rotate-180' : '' ?>" data-lucide="chevron-down"></i>
                                    </button>
                                    <div id="dept_<?php echo $d_key ?>" class="<?= $department_open ? '' : 'hidden' ?>">
                                        <div class="mx-auto max-w-5xl space-y-4 border-t border-border bg-background p-6">
                                            <!-- Email Field -->
                                            <?= form_input_group('email_' . $v_departments->departments_id, lang('email'), $v_departments->email, 'text', false, array(), '', '', 'horizontal') ?>
                                            
                                            <!-- Encryption Field -->
                                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr]">
                                                <label class="pt-2 text-right text-sm font-medium text-foreground"><?= lang('encryption') ?></label>
                                                <div>
                                                    <div class="flex flex-wrap gap-4">
                                                        <label class="inline-flex items-center gap-2 cursor-pointer">
                                                            <input class="select_one w-4 h-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20" type="checkbox" value="tls" name="encryption_<?= $v_departments->departments_id ?>" <?php if ($v_departments->encryption == 'tls') { echo "checked=\"checked\""; } ?>>
                                                            <span class="text-sm text-foreground"><?= lang('tls') ?></span>
                                                        </label>
                                                        <label class="inline-flex items-center gap-2 cursor-pointer">
                                                            <input class="select_one w-4 h-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20" type="checkbox" value="ssl" name="encryption_<?= $v_departments->departments_id ?>" <?php if ($v_departments->encryption == 'ssl') { echo "checked=\"checked\""; } ?>>
                                                            <span class="text-sm text-foreground"><?= lang('ssl') ?></span>
                                                        </label>
                                                        <label class="inline-flex items-center gap-2 cursor-pointer">
                                                            <input class="select_one w-4 h-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20" type="checkbox" name="encryption_<?= $v_departments->departments_id ?>" <?php if ($v_departments->encryption == null) { echo "checked=\"checked\""; } ?>>
                                                            <span class="text-sm text-foreground"><?= lang('no') . ' ' . lang('encryption') ?></span>
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Host Field -->
                                            <?= form_input_group('host_' . $v_departments->departments_id, lang('host'), $v_departments->host, 'text', false, array(), '', '', 'horizontal') ?>
                                            
                                            <!-- Username Field -->
                                            <?= form_input_group('username_' . $v_departments->departments_id, lang('username'), $v_departments->username, 'text', false, array(), '', '', 'horizontal') ?>
                                            
                                            <!-- Password Field -->
                                            <?php $password = strlen(decrypt($v_departments->password)); ?>
                                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr]">
                                                <label class="pt-2 text-right text-sm font-medium text-foreground"><?= lang('password') ?></label>
                                                <div class="space-y-2">
                                                    <?= form_input_group(
                                                        'password_' . $v_departments->departments_id,
                                                        '',
                                                        '',
                                                        'password',
                                                        false,
                                                        array(
                                                            'placeholder' => (!empty($password) ? str_repeat('*', (int) $password) : '')
                                                        )
                                                    ) ?>
                                                    <?= btn_modal(
                                                        'admin/client/see_password/timap_' . $v_departments->departments_id,
                                                        lang('see_password'),
                                                        lang('see_password'),
                                                        'md',
                                                        '',
                                                        array('class' => 'inline-flex items-center gap-1 text-xs text-primary hover:text-primary/80')
                                                    ) ?>
                                                </div>
                                            </div>
                                            
                                            <!-- Mailbox Field -->
                                            <?php
                                            $mailbox = $v_departments->mailbox;
                                            $unread_email = $v_departments->unread_email;
                                            ?>
                                            <div>
                                                <?= form_input_group('mailbox_' . $v_departments->departments_id, lang('mailbox'), (!empty($mailbox) ? $mailbox : 'INBOX'), 'text', false, array(), '', '', 'horizontal') ?>
                                                <p class="ml-0 mt-1 text-xs text-muted-foreground md:ml-[204px]">e.g Gmail: INBOX</p>
                                            </div>
                                            
                                            <!-- Checkboxes -->
                                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr]">
                                                <div></div>
                                                <div>
                                                    <div class="flex flex-wrap gap-4">
                                                        <label class="inline-flex items-center gap-2 cursor-pointer">
                                                            <input type="checkbox" value="1" name="unread_email_<?= $v_departments->departments_id ?>" <?php if ($unread_email == '1') { echo "checked=\"checked\""; } ?> class="w-4 h-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20">
                                                            <span class="text-sm text-foreground"><?= lang('unread_email') ?></span>
                                                        </label>
                                                        <label class="inline-flex items-center gap-2 cursor-pointer">
                                                            <input type="checkbox" value="1" name="delete_mail_after_import_<?= $v_departments->departments_id ?>" <?php if ($v_departments->delete_mail_after_import == '1') { echo "checked=\"checked\""; } ?> class="w-4 h-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20">
                                                            <span class="text-sm text-foreground"><?= lang('delete_mail_after_import') ?></span>
                                                        </label>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <!-- Action Buttons -->
                                            <div class="flex items-center justify-between border-t border-border pt-4 md:pl-[204px]">
                                                <button type="submit" name="departments_id" value="<?= $v_departments->departments_id ?>" class="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-6 py-2.5 text-sm font-medium text-primary-foreground shadow-sm hover:bg-primary/90 transition-colors">
                                                    <i class="text-xs" data-lucide="save"></i>
                                                    <span><?= lang('save_changes') ?></span>
                                                </button>
                                                <div data-toggle="tooltip" data-placement="top" title="<?= lang('save_email_then_test') ?>">
                                                    <a href="<?= base_url('admin/settings/test_email/' . $v_departments->departments_id) ?>" class="inline-flex items-center justify-center gap-2 rounded-lg bg-success px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-success/90 transition-colors">
                                                        <i class="text-xs" data-lucide="check-circle"></i>
                                                        <span><?= lang('test_email_settings') ?></span>
                                                    </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php }
                        }
                    }
                    ?>
                    <?php if (!empty($type) && strtolower($type) == 'leads') { ?>
                        <div class="mx-auto max-w-5xl">
                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr]">
                                <label class="pt-0 text-right text-sm font-medium text-foreground"><?= lang('encryption') ?></label>
                                <div class="flex flex-wrap gap-4">
                                    <label class="inline-flex items-center gap-2 cursor-pointer">
                                        <input class="select_one h-4 w-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20" type="checkbox" value="tls" name="encryption" <?php if (config_item('encryption') == 'tls') { echo "checked=\"checked\""; } ?>>
                                        <span class="text-sm text-foreground"><?= lang('tls') ?></span>
                                    </label>
                                    <label class="inline-flex items-center gap-2 cursor-pointer">
                                        <input class="select_one h-4 w-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20" type="checkbox" value="ssl" name="encryption" <?php if (config_item('encryption') == 'ssl') { echo "checked=\"checked\""; } ?>>
                                        <span class="text-sm text-foreground"><?= lang('ssl') ?></span>
                                    </label>
                                    <label class="inline-flex items-center gap-2 cursor-pointer">
                                        <input class="select_one h-4 w-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20" type="checkbox" name="encryption" <?php if (config_item('encryption') == null) { echo "checked=\"checked\""; } ?>>
                                        <span class="text-sm text-foreground"><?= lang('no') . ' ' . lang('encryption') ?></span>
                                    </label>
                                </div>
                            </div>

                            <?= form_input_group('config_host', lang('host'), config_item('config_host'), 'text', false, array(), '', '', 'horizontal') ?>
                            <?= form_input_group('config_username', lang('username'), config_item('config_username'), 'text', false, array(), '', '', 'horizontal') ?>

                            <?php $password = strlen(decrypt(config_item('config_password'))); ?>
                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr]">
                                <label class="pt-2 text-right text-sm font-medium text-foreground"><?= lang('password') ?></label>
                                <div class="space-y-1">
                                    <div class="flex items-start gap-4">
                                        <div class="min-w-0 flex-1">
                                            <?= form_input_group(
                                                'config_password',
                                                '',
                                                '',
                                                'password',
                                                false,
                                                array(
                                                    'placeholder' => (!empty($password) ? str_repeat('*', (int) $password) : '')
                                                )
                                            ) ?>
                                        </div>
                                        <?= btn_modal(
                                            'admin/client/see_password/emin',
                                            lang('see_password'),
                                            lang('see_password'),
                                            'md',
                                            '',
                                            array(
                                                'id' => 'see_password',
                                                'class' => 'mt-2 inline-flex shrink-0 items-center gap-1 text-sm text-primary hover:text-primary/80'
                                            )
                                        ) ?>
                                    </div>
                                    <strong id="show_password" class="required"></strong>
                                    <strong class="required hosting_password"></strong>
                                </div>
                            </div>

                            <?php
                            $mailbox = config_item('config_mailbox');
                            $unread_email = config_item('unread_email');
                            ?>
                            <div>
                                <?= form_input_group('config_mailbox', lang('mailbox'), (!empty($mailbox) ? $mailbox : 'INBOX'), 'text', false, array(), '', '', 'horizontal') ?>
                                <p class="ml-0 text-xs text-muted-foreground md:ml-[204px]">e.g Gmail: INBOX</p>
                            </div>

                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr] mt-3">
                                <div></div>
                                <div class="flex flex-wrap gap-6">
                                    <label class="inline-flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" name="unread_email" <?php if ($unread_email == 'on') { echo "checked=\"checked\""; } ?> class="h-4 w-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20">
                                        <span class="text-sm text-foreground"><?= lang('unread_email') ?></span>
                                    </label>
                                    <label class="inline-flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" name="delete_mail_after_import" <?php if (config_item('delete_mail_after_import') == 'on') { echo "checked=\"checked\""; } ?> class="h-4 w-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20">
                                        <span class="text-sm text-foreground"><?= lang('delete_mail_after_import') ?></span>
                                    </label>
                                </div>
                            </div>

                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr] mt-3">
                                <label class="pt-2 text-right text-sm font-medium text-foreground"><?= lang('imap_search') ?></label>
                                <div class="space-y-3">
                                    <label class="inline-flex items-center gap-2 cursor-pointer">
                                        <input type="checkbox" name="imap_search_for_leads" <?php if (config_item('imap_search_for_leads') == 'on') { echo "checked=\"checked\""; } ?> class="h-4 w-4 rounded border-border text-primary focus:ring-2 focus:ring-primary/20">
                                        <span class="text-sm text-foreground"><?= lang('search_keyword') ?></span>
                                    </label>
                                    <?= form_input_group('leads_keyword', '', config_item('leads_keyword'), 'text', false, array('placeholder' => lang('search_keyword'))) ?>
                                </div>
                            </div>

                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr] mb-2">
                                <label class="pt-4 text-right text-sm font-medium text-foreground"><?= lang('notified_user') ?></label>
                                <div>
                                    <?= form_multi_lookup_group('notified_user', '', $selected_notified_users, false, array(), '', array('type' => 'staff', 'min_length' => 0, 'placeholder' => lang('search') . ' ' . lang('notified_user'))); ?>
                                </div>
                            </div>

                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr] mb-2">
                                <label class="pt-2 text-right text-sm font-medium text-foreground"><?= lang('postmaster_link') ?></label>
                                <div class="rounded-lg bg-muted px-4 py-2">
                                    <code class="text-sm font-mono text-foreground">wget -q -O- <?= base_url() ?>postmaster/leads</code>
                                </div>
                            </div>

                            <div class="grid grid-cols-1 items-start gap-3 md:grid-cols-[192px_1fr]">
                                <label class="pt-0 text-right text-sm font-medium text-foreground"><?= lang('last_postmaster_run') ?></label>
                                <div class="text-sm font-semibold text-foreground">
                                    <?php
                                    $last_postmaster_run = config_item('last_postmaster_run');
                                    if (!empty($last_postmaster_run)) {
                                        echo display_datetime($last_postmaster_run, true);
                                    } else {
                                        echo "-";
                                    } ?>
                                </div>
                            </div>
                        </div>

                        <div class="mt-5 flex items-center justify-between border-t border-border pt-4">
							<div></div>
                            <button type="submit" class="inline-flex items-center justify-center gap-2 rounded-lg bg-primary px-6 py-2.5 text-sm font-medium text-primary-foreground shadow-sm hover:bg-primary/90 transition-colors">
                                <i class="text-xs" data-lucide="save"></i>
                                <span><?= lang('save_changes') ?></span>
                            </button>

                            <div data-toggle="tooltip" data-placement="top" title="<?= lang('save_email_then_test') ?>">
                                <a href="<?= base_url() ?>admin/settings/test_email/Leads" class="inline-flex items-center justify-center gap-2 rounded-lg bg-success px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-success/90 transition-colors">
                                    <i class="text-xs" data-lucide="check-circle"></i>
                                    <span><?= lang('test_email_settings') ?></span>
                                </a>
                            </div>
                        </div>
                    <?php } ?>
                </div>
            </div>
        </form>
    </div>
    <!-- End Form -->
</div>

<script>
    (function () {
        var buttons = document.querySelectorAll('[data-email-integration-toggle]');
        buttons.forEach(function (button) {
            button.addEventListener('click', function () {
                var target = document.querySelector(button.getAttribute('data-target'));
                var icon = button.querySelector('[data-lucide="chevron-down"], .lucide-chevron-down');
                if (!target) {
                    return;
                }

                var isHidden = target.classList.toggle('hidden');
                button.setAttribute('aria-expanded', isHidden ? 'false' : 'true');
                if (icon) {
                    icon.classList.toggle('rotate-180', !isHidden);
                }
            });
        });
    })();
</script>
