<div class="invoice-modern">
    <?php echo message_box('success'); ?>
    <?php echo message_box('error'); ?>

    <?php
	$created = can_action('140', 'created');
	$edited = can_action('140', 'edited');
	$deleted = can_action('140', 'deleted');

	$proposal_info = isset($proposals_info) ? $proposals_info : null;
	$proposal_id = !empty($proposal_info) && !empty($proposal_info->proposals_id) ? $proposal_info->proposals_id : null;

	$related_module = '';
	$related_module_id = '';
	$currency_selected = config_item('default_currency');
	if (!empty($proposal_info)) {
		$related_module = $proposal_info->module;
		$related_module_id = $proposal_info->module_id;
		if (!empty($proposal_info->currency)) {
			$currency_selected = $proposal_info->currency;
		}
	} elseif (!empty($module)) {
		$related_module = $module;
		$related_module_id = $module_id;
	}

	$client_id = ($related_module == 'client') ? $related_module_id : '';
	$leads_id = ($related_module == 'leads') ? $related_module_id : '';

	$client_label = !empty($client_id) ? client_name($client_id) : '';
	$lead_label = '';
	if (!empty($leads_id)) {
		$lead_row = $this->db->select('lead_name')->where('leads_id', $leads_id)->get('tbl_leads')->row();
		$lead_label = !empty($lead_row) ? $lead_row->lead_name : '';
	}

	$reference_no = '';
	if (!empty($proposal_info) && !empty($proposal_info->reference_no)) {
		$reference_no = $proposal_info->reference_no;
	} else {
		if (empty(config_item('proposal_number_format'))) {
			$reference_no .= config_item('proposal_prefix');
		}
		if (config_item('increment_proposal_number') == 'FALSE') {
			$this->load->helper('string');
			$reference_no .= random_string('nozero', 6);
		} else {
			$reference_no .= $this->proposal_model->generate_proposal_number();
		}
	}

	$proposal_date = !empty($proposal_info) && !empty($proposal_info->proposal_date) ? $proposal_info->proposal_date : date('Y-m-d');
	$due_date = !empty($proposal_info) && !empty($proposal_info->due_date) ? $proposal_info->due_date : date('Y-m-d');

	$status_selected = !empty($proposal_info) && !empty($proposal_info->status) ? $proposal_info->status : 'draft';
	$proposal_status_options = array(
		'draft' => lang('draft'),
		'sent' => lang('sent'),
		'open' => lang('open'),
		'revised' => lang('revised'),
		'declined' => lang('declined'),
		'accepted' => lang('accepted'),
	);

	$discount_type = !empty($proposal_info) && !empty($proposal_info->discount_type) ? $proposal_info->discount_type : '';
	$discount_options = array(
		'' => lang('no') . ' ' . lang('discount'),
		'before_tax' => lang('before_tax'),
		'after_tax' => lang('after_tax'),
	);

	$warehouse_list = $this->db->where('status', 'published')->get('tbl_warehouse')->result();
	$warehouse_selected = !empty($proposal_info) && !empty($proposal_info->warehouse_id) ? $proposal_info->warehouse_id : '';
	$warehouse_label = '';
	if (!empty($warehouse_selected)) {
		$warehouse_label = get_row('tbl_warehouse', array('warehouse_id' => $warehouse_selected), 'warehouse_name');
	}

	$all_user = $this->db->where('role_id != ', 2)->order_by('sort_user', 'ASC')->get('tbl_users')->result();
	$agent_options = array('' => lang('select') . ' ' . lang('assigned') . ' ' . lang('users'));
	if (!empty($all_user)) {
		foreach ($all_user as $v_user) {
			$profile_info = $this->db->where('user_id', $v_user->user_id)->get('tbl_account_details')->row();
			if (!empty($profile_info)) {
				$agent_options[$v_user->user_id] = $profile_info->fullname;
			}
		}
	}
	$selected_agent = !empty($proposal_info) && !empty($proposal_info->user_id) ? $proposal_info->user_id : $this->session->userdata('user_id');
	$selected_agent_label = '';
	if (!empty($selected_agent)) {
		$selected_agent_label = get_row('tbl_account_details', array('user_id' => $selected_agent), 'fullname');
	}

	$tags_value = !empty($proposal_info) && !empty($proposal_info->tags) ? $proposal_info->tags : '';
	$notes_value = !empty($proposal_info) && !empty($proposal_info->notes) ? $proposal_info->notes : $this->config->item('proposal_terms');

	$permissionL = !empty($proposal_info) && !empty($proposal_info->permission) ? $proposal_info->permission : null;

	$currency_options = array();
	$all_currency = $this->db->get('tbl_currencies')->result();
	foreach ($all_currency as $v_currency) {
		$currency_options[$v_currency->code] = $v_currency->name;
	}

	$pdata['itemType'] = 'proposal';
	$pdata['hide_bottom_toolbar'] = true;
	if (!empty($proposal_info)) {
		$pdata['add_items'] = $this->proposal_model->ordered_items_by_id($proposal_info->proposals_id, 'proposal', true);
		$pdata['info'] = $proposal_info;
	}
	?>

    <script src="<?php echo base_url(); ?>assets/plugins/bootstrap-tagsinput/fm.tagator.jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.js"></script>



    <div class="space-y-6">
        <?php if (!empty($created) || !empty($edited)) { ?>
        <?= form_open(base_url('admin/proposals/save_proposals/' . $proposal_id), array('class' => 'space-y-6', 'data-parsley-validate' => '', 'novalidate' => '', 'enctype' => 'multipart/form-data')); ?>
        <div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
            <div class="xl:col-span-8 space-y-6">
                <div class="rounded-xl border border-border bg-card p-6 space-y-5">
                    <div
                        class="flex items-center gap-2 text-sm font-semibold text-foreground border-b border-border pb-3">
                        <i data-lucide="file-text" class="h-5 w-5"></i>
                        <h2 class="text-base font-semibold text-foreground">
                            <?= lang('proposal') . ' ' . lang('details') ?></h2>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <?= form_input_group('reference_no', lang('reference_no'), $reference_no, 'text', true, array('placeholder' => lang('reference_no'))); ?>
                        <?= form_datepicker('proposal_date', lang('proposal_date'), $proposal_date, true, array('data-max' => '#due_date', 'data-auto-close' => 'true')); ?>
                        <?= form_datepicker('due_date', lang('expire_date'), $due_date, true, array('data-min' => '#proposal_date', 'data-auto-close' => 'true')); ?>
                        <?= form_select_group('status', lang('status'), $proposal_status_options, $status_selected, false); ?>
                        <?= form_select_group('discount_type', lang('discount_type'), $discount_options, $discount_type, false, array('data-discount-type' => '1')); ?>

                        <?php if (!empty($warehouse_list)) { ?>
                        <?= form_lookup_group(
								'warehouse_id',
								lang('warehouse'),
								$warehouse_selected,
								$warehouse_label,
								false,
								array('placeholder' => lang('select') . ' ' . lang('warehouse')),
								'',
								array('type' => 'warehouse')
							); ?>
                        <?php } ?>
                    </div>
                </div>

                <div class="rounded-xl border border-border bg-card p-6 space-y-5">
                    <div class="flex items-center gap-2 text-sm font-semibold text-foreground">
                        <i data-lucide="link" class="h-5 w-5"></i>
                        <h2 class="text-base font-semibold text-foreground"><?= lang('related_to') ?></h2>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                        <?= form_select_group('module', lang('related_to'), array('' => lang('none'), 'leads' => lang('leads'), 'client' => lang('client')), $related_module, true, array('id' => 'proposal_module')); ?>
                    </div>
                    <?php if (!empty($module) && !empty($module_id)) { ?>
                    <input type="hidden" name="un_module" value="<?= html_escape($module) ?>">
                    <input type="hidden" name="un_module_id" value="<?= html_escape($module_id) ?>">
                    <?php } ?>
                    <div id="proposal_related_fields" class="space-y-4">
                        <div data-related-module="leads"
                            class="grid grid-cols-1 md:grid-cols-2 gap-5 <?= ($related_module == 'leads') ? '' : 'hidden' ?>">
                            <?= form_lookup_group('leads_id', lang('select') . ' ' . lang('leads'), $leads_id, $lead_label, false, array('placeholder' => lang('search') . ' ' . lang('leads')), 'md:col-span-1', array('type' => 'lead')); ?>
                            <?= form_select_group('currency', lang('currency'), $currency_options, $currency_selected, true, array('data-live-search' => 'true')); ?>
                        </div>
                        <div data-related-module="client"
                            class="grid grid-cols-1 md:grid-cols-2 gap-5 <?= ($related_module == 'client') ? '' : 'hidden' ?>">
                            <?= form_lookup_group('client_id', lang('select') . ' ' . lang('client'), $client_id, $client_label, false, array('placeholder' => lang('search') . ' ' . lang('client')), 'md:col-span-1', array('type' => 'client')); ?>
                        </div>
                    </div>
                </div>



                <div class="rounded-xl border border-border bg-card p-6 space-y-3">
                    <div class="flex items-center gap-2 text-sm font-semibold text-foreground">
                        <i data-lucide="sticky-note" class="h-5 w-5"></i>
                        <h2 class="text-base font-semibold text-foreground"><?= lang('notes') ?></h2>
                    </div>
                    <?= form_editor('notes', '', $notes_value, false, array()); ?>
                </div>
            </div>
            <div class="xl:col-span-4 space-y-6">
                <div class="rounded-xl border border-border bg-card p-6 space-y-5">
                    <div class="flex items-center gap-2 text-sm font-semibold text-foreground">
                        <i data-lucide="user-check" class="h-5 w-5"></i>
                        <h2 class="text-base font-semibold text-foreground"><?= lang('assignment') ?></h2>
                    </div>
                    <?= form_lookup_group(
						'user_id',
						lang('assigned') . ' ' . lang('users'),
						$selected_agent,
						$selected_agent_label,
						false,
						array('placeholder' => lang('select') . ' ' . lang('assigned') . ' ' . lang('users')),
						'',
						array('type' => 'staff')
					); ?>
                    <?= form_tags_group($tags_value); ?>
                    <?php
						$proposals_id = !empty($proposal_info) ? $proposal_info->proposals_id : null;
						echo custom_form_Fields(11, $proposals_id);
						?>
                </div>

                <div class="rounded-xl border border-border bg-card p-6">
                    <?= form_permission_modern($permission_user, $permissionL); ?>
                </div>
            </div>
        </div>

        <?php $this->load->view('admin/items/selectItem', $pdata); ?>

        <div class="flex flex-wrap items-center justify-end gap-2">
            <button type="submit"
                class="inline-flex items-center gap-2 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500">
                <i data-lucide="save" class="h-4 w-4"></i>
                <?= lang('save') ?>
            </button>
            <a href="<?= base_url('admin/proposals') ?>"
                class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-4 py-2 text-sm font-semibold text-foreground hover:bg-muted">
                <i data-lucide="x" class="h-4 w-4"></i>
                <?= lang('cancel') ?>
            </a>
        </div>
        <?= form_close(); ?>
        <?php } else { ?>
        <div class="rounded-2xl border border-border bg-card p-6 shadow-sm">
            <div class="text-sm text-muted-foreground"><?= lang('permission_denied') ?></div>
        </div>
        <?php } ?>
    </div>

    <script>
    (function() {
        var moduleSelect = document.getElementById('proposal_module');
        var relatedFields = document.getElementById('proposal_related_fields');

        function toggleRelatedFields(value) {
            if (!relatedFields) return;
            relatedFields.querySelectorAll('[data-related-module]').forEach(function(block) {
                var isActive = block.getAttribute('data-related-module') === value;
                block.classList.toggle('hidden', !isActive);
                block.querySelectorAll('select, input').forEach(function(el) {
                    if (isActive) {
                        el.removeAttribute('disabled');
                    } else {
                        el.setAttribute('disabled', 'disabled');
                    }
                });
            });
        }

        if (moduleSelect) {
            moduleSelect.addEventListener('change', function() {
                toggleRelatedFields(moduleSelect.value);
            });
            toggleRelatedFields(moduleSelect.value);
        }

        if (window.ins_data) {
            window.ins_data(base_url + 'admin/proposals/proposals_state_report');
        }
    })();
    </script>
</div>
