<?php
$group = $this->uri->segment(5);
$language = $this->uri->segment(4);
if (empty($language)) {
    $system_lang = $this->admin_model->get_lang();
    if (!empty($system_lang)) {
        $language = get_any_field('tbl_languages', array('name' => $system_lang), 'code');
    } else {
        $language = 'en';
    }
}
if (!empty($group)) {
    $group = $group;
} else {
    $group = 'user';
}
$template_group = $group;

switch ($template_group) {
    case "extra":
        $default = "estimate_email";
        break;
    case "invoice":
        $default = "invoice_message";
        break;
    case "tasks":
        $default = "task_assigned";
        break;
    case "bugs":
        $default = "bug_assigned";
        break;
    case "project":
        $default = "client_notification";
        break;
    case "ticket":
        $default = "ticket_client_email";
        break;
    case "hrm":
        $default = "leave_request_email";
        break;
    case "user":
        $default = "activate_account";
        break;
}
$sub_menu = $this->uri->segment(6);
if (!empty($sub_menu)) {
    $sub_menu = $sub_menu;
} else {
    $sub_menu = $default;
}
$setting_email = $sub_menu;

$email['extra'] = array("credit_note_email" => array("{credit_note_REF}", "{CLIENT}", "{CURRENCY}", "{AMOUNT}", "{credit_note_LINK}", "{SITE_NAME}"), "estimate_email" => array("{ESTIMATE_REF}", "{CLIENT}", "{CURRENCY}", "{AMOUNT}", "{ESTIMATE_LINK}", "{SITE_NAME}"), "estimate_overdue_email" => array("{ESTIMATE_REF}", "{CLIENT}", "{DUE_DATE}", "{CURRENCY}", "{AMOUNT}", "{ESTIMATE_LINK}", "{SITE_NAME}"), "proposal_email" => array("{PROPOSAL_REF}", "{CLIENT}", "{CURRENCY}", "{AMOUNT}", "{PROPOSAL_LINK}", "{SITE_NAME}"), "proposal_overdue_email" => array("{PROPOSAL_REF}", "{CLIENT}", "{DUE_DATE}", "{CURRENCY}", "{AMOUNT}", "{PROPOSAL_LINK}", "{SITE_NAME}"), "message_received" => array("{RECIPIENT}", "{SENDER}", "{MESSAGE}", "{SITE_URL}", "{SITE_NAME}"), "quotations_form" => array("{CLIENT}", "{DATE}", "{CURRENCY}", "{AMOUNT}", "{NOTES}", "{QUOTATION_LINK}", "{SITE_NAME}"), "goal_achieve" => array("{Goal_Type}", "{achievement}", "{total_achievement}", "{start_date}", "{End_date}"), "goal_not_achieve" => array("{Goal_Type}", "{achievement}", "{total_achievement}", "{start_date}", "{End_date}"));
$email['invoice'] = array("invoice_message" => array("{SITE_NAME}", "{CLIENT}", "{CURRENCY}", "{AMOUNT}"), "invoice_reminder" => array("{SITE_NAME}", "{CLIENT}", "{CURRENCY}", "{AMOUNT}"), "payment_email" => array("{SITE_NAME}", "{INVOICE_CURRENCY}", "{PAID_AMOUNT}"), "invoice_overdue_email" => array("{SITE_NAME}", "{REF}", "{CLIENT}", "{CURRENCY}", "{AMOUNT}", "{DUE_DATE}"), "refund_confirmation" => array("{SITE_NAME}", "{CLIENT}", "{CURRENCY}", "{AMOUNT}", "{INVOICE_DATE}"), "invoice_item_refund_request" => array("{SITE_NAME}", "{CLIENT}", "{CURRENCY}", "{AMOUNT}", "{INVOICE_DATE}"));
$email['tasks'] = array("task_assigned" => array("{SITE_NAME}", "{TASK_NAME}", "{ASSIGNED_BY}"), "tasks_comments" => array("{SITE_NAME}", "{POSTED_BY}", "{TASK_NAME}", "{COMMENT_MESSAGE}"), "tasks_attachment" => array("{SITE_NAME}", "{UPLOADED_BY}", "{TASK_NAME}"), "tasks_updated" => array("{SITE_NAME}", "{TASK_NAME}", "{ASSIGNED_BY}"));
$email['bugs'] = array("bug_assigned" => array("{SITE_NAME}", "{BUG_TITLE}", "{ASSIGNED_BY}"), "bug_comments" => array("{SITE_NAME}", "{POSTED_BY}", "{BUG_TITLE}", "{COMMENT_MESSAGE}"), "bug_attachment" => array("{SITE_NAME}", "{UPLOADED_BY}", "{BUG_TITLE}"), "bug_updated" => array("{SITE_NAME}", "{STATUS}", "{BUG_TITLE}", "{MARKED_BY}"), 'bug_reported' => array("{SITE_NAME}", "{ADDED_BY}", "{BUG_TITLE}"));
$email['project'] = array("client_notification" => array("{SITE_NAME}", "{CLIENT_NAME}", "{PROJECT_NAME}"), "assigned_project" => array("{SITE_NAME}", "{PROJECT_NAME}"), 'complete_projects' => array("{SITE_NAME}", "{PROJECT_NAME}", "{CLIENT_NAME}"), "project_comments" => array("{SITE_NAME}", "{PROJECT_NAME}", "{POSTED_BY}", "{COMMENT_MESSAGE}"), "project_attachment" => array("{SITE_NAME}", "{PROJECT_NAME}", "{UPLOADED_BY}"), 'responsible_milestone' => array("{SITE_NAME}", "{PROJECT_NAME}", "{MILESTONE_NAME}", "{ASSIGNED_BY}"), 'project_overdue_email' => array("{SITE_NAME}", "{PROJECT_NAME}", "{CLIENT}", "{DUE_DATE}"));
$email['ticket'] = array("ticket_client_email" => array("{SITE_NAME}", "{CLIENT_EMAIL}", "{TICKET_CODE}"), "ticket_closed_email" => array("{SITE_NAME}", "{REPORTER_EMAIL}", "{TICKET_CODE}", "{STAFF_USERNAME}", "{TICKET_STATUS}", "{NO_OF_REPLIES}"), "ticket_reply_email" => array("{SITE_NAME}", "{TICKET_CODE}", "{TICKET_STATUS}"), "ticket_staff_email" => array("{SITE_NAME}", "{TICKET_CODE}", "{REPORTER_EMAIL}"), "auto_close_ticket" => array("{SITE_NAME}", "{TICKET_CODE}", "{REPORTER_EMAIL}", "{SUBJECT}", "{TICKET_STATUS}"), "ticket_reopened_email" => array("{SITE_NAME}", "{RECIPIENT}", "{SUBJECT}", "{USER}"));
$email['user'] = array("activate_account" => array("{SITE_NAME}", "{ACTIVATE_URL}", "{USERNAME}", "{EMAIL}", "{PASSWORD}"), "change_email" => array("{SITE_NAME}", "{NEW_EMAIL}", "{NEW_EMAIL_KEY_URL}"), "forgot_password" => array("{SITE_NAME}", "{PASS_KEY_URL}"), "registration" => array("{SITE_NAME}", "{SITE_URL}", "{USERNAME}", "{EMAIL}", "{PASSWORD}"), "reset_password" => array("{SITE_NAME}", "{USERNAME}", "{EMAIL}", "{NEW_PASSWORD}"), 'wellcome_email' => array("{NAME}", "{COMPANY_NAME}", "{COMPANY_URL}"));

$email['hrm'] = array(
    "leave_request_email" => array("{SITE_NAME}", "{NAME}"), "leave_approve_email" => array("{SITE_NAME}", "{START_DATE}", "{END_DATE}"), "leave_reject_email" => array("{SITE_NAME}", "{START_DATE}", "{END_DATE}"), "overtime_request_email" => array("{SITE_NAME}", "{NAME}"), "overtime_approved_email" => array("{SITE_NAME}", "{DATE}", "{HOUR}"), "overtime_reject_email" => array("{SITE_NAME}", "{DATE}", "{HOUR}"), "payslip_generated_email" => array("{SITE_NAME}", "{NAME}", "{MONTH_YEAR}"), "advance_salary_email" => array("{SITE_NAME}", "{NAME}"), "advance_salary_approve_email" => array("{SITE_NAME}", "{AMOUNT}", "{DEDUCT_MOTNH}"), "advance_salary_reject_email" => array("{SITE_NAME}"), "award_email" => array("{SITE_NAME}", "{NAME}", "{AWARD_NAME}", "{MONTH}"), "new_job_application_email" => array("{SITE_NAME}", "{NAME}", "{JOB_TITLE}", "{EMAIL}", "{MOBILE}", "{COVER_LETTER}"), "call_for_interview" => array("{SITE_NAME}", "{NAME}", "{JOB_TITLE}", "{DESIGNATION}", "{DATE}", "{NOTE}"), "new_notice_published" => array("{SITE_NAME}", "{NAME}", "{TITLE}"), "new_training_email" => array("{SITE_NAME}", "{TRAINING_NAME}", "{ASSIGNED_BY}"), 'deposit_email' => array("{SITE_NAME}", "{AMOUNT}", "{ACCOUNT}", "{BALANCE}"), 'expense_request_email' => array("{SITE_NAME}", "{AMOUNT}", "{NAME}"), 'expense_approved_email' => array("{SITE_NAME}", "{AMOUNT}", "{NAME}"), 'expense_paid_email' => array("{SITE_NAME}", "{AMOUNT}", "{NAME}", "{PAID_BY}"), 'trying_clock_email' => array("{SITE_NAME}", "{IP}", "{NAME}", "{TIME}"), 'clock_in_email' => array("{SITE_NAME}", "{IP}", "{NAME}", "{TIME}"), 'clock_out_email' => array("{SITE_NAME}", "{IP}", "{NAME}", "{TIME}"), 'promotion_email' => array("{NAME}", "{SITE_NAME}", "{DESIGNATIONS}"), 'warning_email' => array("{NAME}", "{SITE_NAME}", "{DESCRIPTION}")
);

?>
<form action="<?= base_url('admin/settings/templates/' . $language . '/') ?><?= $setting_email ?>" method="post" class="space-y-6">
    <div class="rounded-2xl border border-border bg-card shadow-sm">
        <!-- Header -->
        <div class="border-b border-border rounded-t-2xl bg-muted/50 px-6 py-4">
            <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
                <h2 class="text-lg font-semibold text-foreground"><?= lang('email_templates') ?></h2>
                
                <div class="flex flex-col sm:flex-row gap-3">
                    <!-- Language Selector -->
                    <div class="relative inline-block text-left">
                        <button type="button" class="inline-flex h-10 min-w-[150px] items-center justify-center gap-2 rounded-lg border border-border bg-card px-4 text-xs font-semibold text-foreground shadow-sm transition hover:bg-muted focus:outline-none focus:ring-2 focus:ring-primary/20" onclick="toggleDropdown('languageDropdown')">
                            <i data-lucide="languages" class="h-4 w-4"></i>
                            <span><?= lang('languages') ?></span>
                            <i data-lucide="chevron-down" class="h-4 w-4"></i>
                        </button>
                        <?php $languages = $this->db->where('active', 1)->order_by('name', 'ASC')->get('tbl_languages')->result(); ?>
                        <div id="languageDropdown" class="hidden absolute right-0 z-10 mt-2 max-h-72 w-56 origin-top-right overflow-y-auto rounded-xl border border-border bg-card p-1 shadow-lg ring-1 ring-black ring-opacity-5">
                            <div class="py-1">
                                <?php foreach ($languages as $langs) : ?>
                                    <a href="<?= base_url('admin/settings/templates/' . $langs->code . '/') ?>" class="block rounded-md px-3 py-2 text-sm <?= ($language == $langs->code) ? 'bg-primary/10 text-primary font-semibold' : 'text-foreground hover:bg-muted' ?>">
                                        <?= lang(ucwords($langs->name)) ?>
                                    </a>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Template Category Selector -->
                    <div class="relative inline-block text-left">
                        <button type="button" class="inline-flex h-10 min-w-[170px] items-center justify-center gap-2 rounded-lg border border-border bg-card px-4 text-xs font-semibold text-foreground shadow-sm transition hover:bg-muted focus:outline-none focus:ring-2 focus:ring-primary/20" onclick="toggleDropdown('templateDropdown')">
                            <i data-lucide="mail-check" class="h-4 w-4"></i>
                            <span><?= lang('choose_template') ?></span>
                            <i data-lucide="chevron-down" class="h-4 w-4"></i>
                        </button>
                        <div id="templateDropdown" class="hidden absolute right-0 z-10 mt-2 max-h-72 w-56 origin-top-right overflow-y-auto rounded-xl border border-border bg-card p-1 shadow-lg ring-1 ring-black ring-opacity-5">
                            <div class="py-1">
                                <a href="<?= base_url('admin/settings/templates/' . $language . '/') ?>user" class="block rounded-md px-3 py-2 text-sm text-foreground hover:bg-muted">
                                    <?= lang('account_emails') ?>
                                </a>
                                <a href="<?= base_url('admin/settings/templates/' . $language . '/') ?>invoice" class="block rounded-md px-3 py-2 text-sm text-foreground hover:bg-muted">
                                    <?= lang('invoicing_emails') ?>
                                </a>
                                <a href="<?= base_url('admin/settings/templates/' . $language . '/') ?>tasks" class="block rounded-md px-3 py-2 text-sm text-foreground hover:bg-muted">
                                    <?= lang('tasks_email') ?>
                                </a>
                                <a href="<?= base_url('admin/settings/templates/' . $language . '/') ?>bugs" class="block rounded-md px-3 py-2 text-sm text-foreground hover:bg-muted">
                                    <?= lang('bugs_email') ?>
                                </a>
                                <a href="<?= base_url('admin/settings/templates/' . $language . '/') ?>project" class="block rounded-md px-3 py-2 text-sm text-foreground hover:bg-muted">
                                    <?= lang('project_emails') ?>
                                </a>
                                <a href="<?= base_url('admin/settings/templates/' . $language . '/') ?>ticket" class="block rounded-md px-3 py-2 text-sm text-foreground hover:bg-muted">
                                    <?= lang('ticketing_emails') ?>
                                </a>
                                <a href="<?= base_url('admin/settings/templates/' . $language . '/') ?>hrm" class="block rounded-md px-3 py-2 text-sm text-foreground hover:bg-muted">
                                    <?= lang('hrm_emails') ?>
                                </a>
                                <a href="<?= base_url('admin/settings/templates/' . $language . '/') ?>extra" class="block rounded-md px-3 py-2 text-sm text-foreground hover:bg-muted">
                                    <?= lang('extra_emails') ?>
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Body -->
        <div class="p-6 space-y-3">
            <!-- Template Type Tabs -->
            <div class="flex flex-wrap gap-2">
                <?php
                foreach ($email[$template_group] as $label => $temp) :
                    $lang = $label;
                    switch ($label) {
                        case "registration":
                            $lang = 'register_email';
                    }
                    $isActive = ($setting_email == $label);
                    ?>
                    <a href="<?= base_url('admin/settings/templates/' . $language . '/') ?><?= $template_group; ?>/<?= $label; ?>" class="inline-flex items-center justify-center rounded-lg px-4 py-2 text-sm font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-primary/20 <?= $isActive ? 'bg-primary text-primary-foreground shadow-sm' : 'bg-muted text-foreground hover:bg-muted/80' ?>">
                        <?= lang($label) ?>
                    </a>
                <?php endforeach; ?>
            </div>

            <!-- Hidden Fields -->
            <input type="hidden" name="email_group" value="<?= $setting_email; ?>">
            <input type="hidden" name="code" id="code" value="<?= $language ?>">
            <input type="hidden" name="return_url" value="<?= base_url('admin/settings/templates/' . $language . '/') ?><?= $template_group . '/' . $setting_email; ?>">

            <!-- Subject Field -->
            <?= form_input_group(
                'subject',
                lang('subject'),
                get_any_field('tbl_email_templates', array('email_group' => $setting_email, 'code' => $language), 'subject'),
                'text',
                false
            ) ?>

            <!-- Message Field -->
            <div class="space-y-2">
                <label class="block text-sm font-medium text-foreground"><?= lang('message') ?></label>
                
                <!-- Merge Fields -->
                <div class="rounded-lg border border-border bg-muted/30 p-4">
                    <div class="mb-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
                        <?= lang('available_merge_fields') ?>
                    </div>
                    <div class="flex max-h-44 flex-wrap gap-2 overflow-y-auto pr-1">
                        <?php foreach ($email[$template_group][$setting_email] as $ltexts) { ?>
                            <button type="button" class="add_merge_field inline-flex items-center rounded-md border border-border bg-background px-3 py-1.5 text-xs font-medium text-foreground shadow-sm hover:bg-muted transition-colors focus:outline-none focus:ring-2 focus:ring-primary/20">
                                <?= $ltexts ?>
                            </button>
                        <?php } ?>
                    </div>
                </div>

                <?= form_editor(
                    'email_template',
                    '',
                    get_any_field('tbl_email_templates', array('email_group' => $setting_email, 'code' => $language), 'template_body'),
                    false,
                    array('id' => 'emailTemplateEditor', 'rows' => 20, 'data-height' => '420px')
                ) ?>
            </div>
        </div>

        <!-- Footer -->
        <div class="border-t border-border bg-muted/50 px-6 py-4 rounded-b-2xl">
            <div class="flex justify-end">
                <button type="submit" class="inline-flex items-center justify-center gap-2 rounded-lg bg-slate-900 px-6 py-2.5 text-sm font-medium text-white shadow-sm transition-colors hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-primary/20 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-white">
                    <i data-lucide="save" class="h-4 w-4"></i>
                    <span><?= lang('save_changes') ?></span>
                </button>
            </div>
        </div>
    </div>
</form>

<script>
$(document).ready(function() {
    // Toggle dropdown menus
    window.toggleDropdown = function(id) {
        const dropdown = document.getElementById(id);
        const allDropdowns = document.querySelectorAll('[id$="Dropdown"]');
        
        allDropdowns.forEach(dd => {
            if (dd.id !== id) {
                dd.classList.add('hidden');
            }
        });
        
        dropdown.classList.toggle('hidden');
    };

    // Close dropdowns when clicking outside
    document.addEventListener('click', function(event) {
        const dropdowns = document.querySelectorAll('[id$="Dropdown"]');
        const buttons = document.querySelectorAll('button[onclick^="toggleDropdown"]');
        
        let clickedButton = false;
        buttons.forEach(btn => {
            if (btn.contains(event.target)) {
                clickedButton = true;
            }
        });
        
        if (!clickedButton) {
            dropdowns.forEach(dd => dd.classList.add('hidden'));
        }
    });

    // Add merge field on click
    $('.add_merge_field').on('click', function(e) {
        e.preventDefault();
        const textarea = document.getElementById('emailTemplateEditor');
        const text = $(this).text().trim();
        
        if (textarea && textarea._tailwindEditor && typeof textarea._tailwindEditor.insertText === 'function') {
            textarea._tailwindEditor.insertText(text);
        } else if (textarea) {
            const startPos = textarea.selectionStart;
            const endPos = textarea.selectionEnd;
            const textBefore = textarea.value.substring(0, startPos);
            const textAfter = textarea.value.substring(endPos, textarea.value.length);
            
            textarea.value = textBefore + text + textAfter;
            textarea.selectionStart = textarea.selectionEnd = startPos + text.length;
            textarea.focus();
        }
    });
});
</script>
