<?php
	$db =& get_instance();
	$userdetails=$db->userdetails();

	$allows = array(
		'user'   => [1 => 1, 2 => 2, 3=>3 , 4=>4, 5=>5 ,7=>7, 8=>8, 9=>9, 10=>10, 11=>11,12=>12,13=>13],
		'admin'  => [1 => 1, 2 => 2, 3=>3 , 4=>4, 5=>5 , 6=>6, 7=>7, 8=>8, 9=>9, 10=>10, 11=>11, 13=>13],
		'client' => [2 => 2, 3=>3 , 6=>6, 7=>7, 8=>8, 9=>9],
	);

	$user_level_changed = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'user_level_changed'")->row()->id;
	$allows['user'][$user_level_changed] = $user_level_changed;
	
	$vendor_create_product = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_create_product'")->row()->id;
	$new_order_for_vendor = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'new_order_for_vendor'")->row()->id;
	
	$new_vendor_deposit_request = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'new_vendor_deposit_request'")->row()->id;
	$vendor_deposit_request_updated = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_deposit_request_updated'")->row()->id;
	
	$allows['admin'][$vendor_create_product] = $vendor_create_product;
	$allows['admin'][$new_order_for_vendor] = $new_order_for_vendor;
	
	$allows['user'][$new_vendor_deposit_request] = $new_vendor_deposit_request;
	$allows['user'][$vendor_deposit_request_updated] = $vendor_deposit_request_updated;
	$allows['admin'][$new_vendor_deposit_request] = $new_vendor_deposit_request;
	$allows['admin'][$vendor_deposit_request_updated] = $vendor_deposit_request_updated;

	$vendor_product_status_0 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_product_status_0'")->row()->id;
	$vendor_product_status_1 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_product_status_1'")->row()->id;
	$vendor_product_status_2 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_product_status_2'")->row()->id;
	$vendor_product_status_3 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_product_status_3'")->row()->id;
	$vendor_order_status_complete = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_order_status_complete'")->row()->id;

	$vendor_create_form = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_create_form'")->row()->id;
	$vendor_form_status_0 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_form_status_0'")->row()->id;
	$vendor_form_status_1 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_form_status_1'")->row()->id;
	$vendor_form_status_2 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_form_status_2'")->row()->id;
	$vendor_form_status_3 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_form_status_3'")->row()->id;

	$order_on_vendor_program = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'order_on_vendor_program'")->row()->id;
	$vendor_create_ads = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_create_ads'")->row()->id;
	$vendor_ads_status_0 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_ads_status_0'")->row()->id;
	$vendor_ads_status_1 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_ads_status_1'")->row()->id;
	$vendor_ads_status_2 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_ads_status_2'")->row()->id;
	$vendor_ads_status_3 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_ads_status_3'")->row()->id;

	$vendor_create_program = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_create_program'")->row()->id;
	$vendor_program_status_0 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_program_status_0'")->row()->id;
	$vendor_program_status_1 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_program_status_1'")->row()->id;
	$vendor_program_status_2 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_program_status_2'")->row()->id;
	$vendor_program_status_3 = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'vendor_program_status_3'")->row()->id;

	$withdrwal_status_change = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'withdrwal_status_change'")->row()->id;
	$send_register_mail_api = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'send_register_mail_api'")->row()->id;
	$wallet_noti_on_hold_wallet = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'wallet_noti_on_hold_wallet'")->row()->id;

	$subscription_status_change = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'subscription_status_change'")->row()->id;
	$allows['user'][$subscription_status_change] = $subscription_status_change;

	$subscription_expire_notification = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'subscription_expire_notification'")->row()->id;
	$allows['user'][$subscription_expire_notification] = $subscription_expire_notification;

	$subscription_buy = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'subscription_buy'")->row()->id;
	$allows['admin'][$subscription_buy] = $subscription_buy;
	$allows['user'][$subscription_buy] = $subscription_buy;

	$new_user_request = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'new_user_request'")->row()->id;
	$allows['admin'][$new_user_request] = $new_user_request;
	$allows['user'][$new_user_request] = $new_user_request;
	$new_user_approved = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'new_user_approved'")->row()->id;
	$allows['admin'][$new_user_approved] = $new_user_approved;
	$allows['user'][$new_user_approved] = $new_user_approved;
	$new_user_declined = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = 'new_user_declined'")->row()->id;
	$allows['admin'][$new_user_declined] = $new_user_declined;
	$allows['user'][$new_user_declined] = $new_user_declined;
	
	$allows['admin'][$send_register_mail_api] = $send_register_mail_api;
	$allows['user'][$send_register_mail_api] = $send_register_mail_api;
	
	$allows['user'][$withdrwal_status_change] = $withdrwal_status_change;

	$allows['user'][$vendor_product_status_0] = $vendor_product_status_0;
	$allows['user'][$vendor_product_status_1] = $vendor_product_status_1;
	$allows['user'][$vendor_product_status_2] = $vendor_product_status_2;
	$allows['user'][$vendor_product_status_3] = $vendor_product_status_3;
	$allows['user'][$vendor_order_status_complete] = $vendor_order_status_complete;
	
	$allows['user'][$vendor_form_status_0] = $vendor_form_status_0;
	$allows['user'][$vendor_form_status_1] = $vendor_form_status_1;
	$allows['user'][$vendor_form_status_2] = $vendor_form_status_2;
	$allows['user'][$vendor_form_status_3] = $vendor_form_status_3;

	$allows['user'][$order_on_vendor_program] = $order_on_vendor_program;
	$allows['user'][$vendor_ads_status_0] = $vendor_ads_status_0;
	$allows['user'][$vendor_ads_status_1] = $vendor_ads_status_1;
	$allows['user'][$vendor_ads_status_2] = $vendor_ads_status_2;
	$allows['user'][$vendor_ads_status_3] = $vendor_ads_status_3;

	$allows['user'][$vendor_program_status_0] = $vendor_program_status_0;
	$allows['user'][$vendor_program_status_1] = $vendor_program_status_1;
	$allows['user'][$vendor_program_status_2] = $vendor_program_status_2;
	$allows['user'][$vendor_program_status_3] = $vendor_program_status_3;
	
	$allows['admin'][$vendor_product_status_0] = $vendor_product_status_0;
	$allows['admin'][$vendor_create_form] = $vendor_create_form;
	$allows['admin'][$vendor_create_ads] = $vendor_create_ads;
	$allows['admin'][$vendor_form_status_0] = $vendor_form_status_0;
	$allows['admin'][$vendor_create_program] = $vendor_create_program;
	$allows['admin'][$vendor_program_status_0] = $vendor_program_status_0;
	$allows['admin'][$vendor_ads_status_0] = $vendor_ads_status_0;
	
	$allows['user'][$wallet_noti_on_hold_wallet] = $wallet_noti_on_hold_wallet;

	$ticketMailTemplates = ['ticket_created_email', 'ticket_reply_email', 'ticket_status_email'];

	foreach ($ticketMailTemplates as $unique_id) {
		$templateID = (int)$this->db->query("SELECT id FROM mail_templates WHERE unique_id = '{$unique_id}'")->row()->id;
		if(!empty($templateID)) {
			$allows['admin'][$templateID] = $allows['user'][$templateID] = $templateID;
		}
	}
?>

<div class="container-fluid mail-editor-page">
    <div class="row">
        <div class="col-12">

            <!-- Header -->
            <div class="card shadow-sm border-0 mb-4">
                <div class="card-header bg-primary text-white py-3">
                    <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                        <div class="d-flex align-items-center">
                            <i class="bi bi-pencil-square me-2 fs-4"></i>
                            <div>
                                <h4 class="mb-0 fw-bold"><?= __('admin.mail_editor') ?></h4>
                                <small class="opacity-75"><?= htmlspecialchars($templates['name']) ?></small>
                            </div>
                        </div>
                        <a href="<?= base_url('admincontrol/mails') ?>" class="btn btn-outline-light btn-sm">
                            <i class="bi bi-arrow-left me-1"></i><?= __('admin.back') ?>
                        </a>
                    </div>
                </div>
            </div>

            <!-- Editor Form -->
            <div class="card shadow-sm border-0">
                <div class="card-body">
                    <form action="" method="POST" role="form" id="mail_template_form">
                        <input type="hidden" id="template_id" name="id" value="<?= $templates['id'] ?>">
                        
                        <!-- Tab Navigation -->
                        <ul class="nav nav-pills nav-fill mb-4" role="tablist" id="myTab">
                            <?php if($allows['user'][$templates['id']]){ ?>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link active" id="user-tab" data-bs-toggle="pill" data-bs-target="#for-user" type="button" role="tab">
                                        <i class="bi bi-person me-1"></i><?= __('admin.user') ?>
                                    </button>
                                </li>
                            <?php } ?>
                            <?php if($allows['admin'][$templates['id']]){ ?>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link<?= !$allows['user'][$templates['id']] ? ' active' : '' ?>" id="admin-tab" data-bs-toggle="pill" data-bs-target="#for-admin" type="button" role="tab">
                                        <i class="bi bi-shield-check me-1"></i><?= __('admin.admin') ?>
                                    </button>
                                </li>
                            <?php } ?>
                            <?php if($allows['client'][$templates['id']]){ ?>
                                <li class="nav-item" role="presentation">
                                    <button class="nav-link<?= (!$allows['user'][$templates['id']] && !$allows['admin'][$templates['id']]) ? ' active' : '' ?>" id="client-tab" data-bs-toggle="pill" data-bs-target="#for-client" type="button" role="tab">
                                        <i class="bi bi-people me-1"></i><?= __('admin.client') ?>
                                    </button>
                                </li>
                            <?php } ?>
                        </ul>

                        <!-- Tab Content -->
                        <div class="tab-content">
                            <?php if($allows['user'][$templates['id']]){ ?>
                                <div class="tab-pane fade show active template" id="for-user" role="tabpanel">
                                    <div class="mb-4">
                                        <label class="form-label fw-bold"><?= __('admin.subject') ?></label>
                                        <input type="text" class="form-control" name="subject" value="<?= htmlspecialchars($templates['subject']) ?>" placeholder="<?= __('admin.enter_subject') ?>">
                                    </div>
                                    <div class="mb-4">
                                        <label class="form-label fw-bold"><?= __('admin.email_content') ?></label>
                                        <textarea class="form-control summernote-img" name="text" rows="10"><?= $templates['text'] ?></textarea>
                                    </div>
                                </div>
                            <?php } ?>
                            
                            <?php if($allows['admin'][$templates['id']]){ ?>
                                <div class="tab-pane fade<?= !$allows['user'][$templates['id']] ? ' show active' : '' ?> template" id="for-admin" role="tabpanel">
                                    <div class="mb-4">
                                        <label class="form-label fw-bold"><?= __('admin.subject') ?></label>
                                        <input type="text" class="form-control" name="admin_subject" value="<?= htmlspecialchars($templates['admin_subject']) ?>" placeholder="<?= __('admin.enter_subject') ?>">
                                    </div>
                                    <div class="mb-4">
                                        <label class="form-label fw-bold"><?= __('admin.email_content') ?></label>
                                        <textarea class="form-control summernote-img" name="admin_text" rows="10"><?= $templates['admin_text'] ?></textarea>
                                    </div>
                                </div>
                            <?php } ?>
                            
                            <?php if($allows['client'][$templates['id']]){ ?>
                                <div class="tab-pane fade<?= (!$allows['user'][$templates['id']] && !$allows['admin'][$templates['id']]) ? ' show active' : '' ?> template" id="for-client" role="tabpanel">
                                    <div class="mb-4">
                                        <label class="form-label fw-bold"><?= __('admin.subject') ?></label>
                                        <input type="text" class="form-control" name="client_subject" value="<?= htmlspecialchars($templates['client_subject']) ?>" placeholder="<?= __('admin.enter_subject') ?>">
                                    </div>
                                    <div class="mb-4">
                                        <label class="form-label fw-bold"><?= __('admin.email_content') ?></label>
                                        <textarea class="form-control summernote-img" name="client_text" rows="10"><?= $templates['client_text'] ?></textarea>
                                    </div>
                                </div>
                            <?php } ?>
                        </div>

                        <!-- Available Shortcodes -->
                        <div class="alert alert-info mb-4">
                            <div class="d-flex align-items-center mb-2">
                                <i class="bi bi-info-circle me-2"></i>
                                <strong><?= __('admin.available_shortcodes') ?>:</strong>
                            </div>
                            <div class="d-flex flex-wrap gap-2">
                                <?php 
                                    $shortcode = explode(",", $templates['shortcode']);
                                    foreach ($shortcode as $key => $value) {
                                        echo '<span class="badge bg-secondary">[['. htmlspecialchars(trim($value)) .']]</span>';
                                    }
                                ?>
                            </div>
                        </div>

                        <!-- Action Buttons -->
                        <div class="row g-3">
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary w-100">
                                    <i class="bi bi-save me-1"></i><?= __('admin.submit') ?>
                                </button>
                            </div>
                            <div class="col-md-8">
                                <div class="input-group">
                                    <input type="email" id="test_email" class="form-control" name="test_email" placeholder="<?= __('admin.enter_test_email') ?>" required>
                                    <button type="button" class="btn btn-success send-test">
                                        <i class="bi bi-send me-1"></i><?= __('admin.send_test') ?>
                                    </button>
                                </div>
                                <div id="test-result" class="mt-2"></div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    $('#myTab button:first').tab('show');

    $('.send-test').on('click', function() {
        const $this = $(this);
        const testEmail = $('#test_email').val();
        
        if (!testEmail || !testEmail.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/)) {
            if(typeof showToast === 'function') {
                showToast('<?= __('admin.error') ?>', '<?= __('admin.invalid_email_format') ?>', 'error', 3000);
            } else {
                $('#test-result').html('<div class="alert alert-danger"><?= __('admin.invalid_email_format') ?></div>');
            }
            return;
        }
        
        $.ajax({
            type: 'POST',
            dataType: 'json',
            data: $('.tab-pane.active').find('input, select, textarea').serialize() + 
                  "&id=" + $("#template_id").val() + 
                  "&test_email=" + testEmail + 
                  "&send_test=true&test_for=" + $('.tab-pane.active.template').attr("id"),
            beforeSend: function() {
                $this.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span><?= __('admin.sending') ?>...');
            },
            complete: function() {
                $this.prop('disabled', false).html('<i class="bi bi-send me-1"></i><?= __('admin.send_test') ?>');
            },
            success: function(json) {
                if(json['error']) {
                    if(typeof showToast === 'function') {
                        showToast('<?= __('admin.error') ?>', json['error'], 'error', 5000);
                    } else {
                        $('#test-result').html('<div class="alert alert-danger">' + json['error'] + '</div>');
                    }
                }
                if(json['success']) {
                    if(typeof showToast === 'function') {
                        showToast('<?= __('admin.success') ?>', json['success'], 'success', 3000);
                    } else {
                        $('#test-result').html('<div class="alert alert-success">' + json['success'] + '</div>');
                    }
                    $('#test_email').val('');
                }
            }
        });
    });
});
</script>