<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>
<?php
$estimate_id = !empty($estimates_info->estimates_id) ? $estimates_info->estimates_id : 0;

$reference_no = '';
if (empty(config_item('invoice_number_format'))) {
    $reference_no .= config_item('invoice_prefix');
}
if (config_item('increment_invoice_number') == 'FALSE') {
    $this->load->helper('string');
    $reference_no .= random_string('nozero', 6);
} else {
    $reference_no .= $this->estimates_model->generate_invoice_number();
}

$client_id = !empty($estimates_info->client_id) ? $estimates_info->client_id : '';
$client_label = '';
if (!empty($client_id)) {
    $client_info = $this->db->select('name, language')->where('client_id', $client_id)->get('tbl_client')->row();
    $client_label = !empty($client_info->name) ? $client_info->name : '';
}

$project_id = !empty($estimates_info->project_id) ? $estimates_info->project_id : '';
$project_label = '';
if (!empty($project_id)) {
    $project_info = $this->db->select('project_name')->where('project_id', $project_id)->get('tbl_project')->row();
    $project_label = !empty($project_info->project_name) ? $project_info->project_name : '';
}

$warehouse_id = !empty($estimates_info->warehouse_id) ? $estimates_info->warehouse_id : '';
$warehouse_label = '';
if (!empty($warehouse_id)) {
    $warehouse_info = $this->db->select('warehouse_name')->where('warehouse_id', $warehouse_id)->get('tbl_warehouse')->row();
    $warehouse_label = !empty($warehouse_info->warehouse_name) ? $warehouse_info->warehouse_name : '';
}

$selected_agent = !empty($estimates_info->user_id) ? $estimates_info->user_id : $this->session->userdata('user_id');
$selected_agent_label = !empty($selected_agent) ? fullname($selected_agent) : '';
$invoice_date = !empty($estimates_info->estimate_date) ? $estimates_info->estimate_date : date('Y-m-d');
$due_date = !empty($estimates_info->due_date) ? $estimates_info->due_date : date('Y-m-d');
$discount_type = !empty($estimates_info->discount_type) ? $estimates_info->discount_type : '';
$notes = !empty($estimates_info->notes) ? $estimates_info->notes : $this->config->item('default_terms');
$permissionL = !empty($estimates_info->permission) ? $estimates_info->permission : null;
$client_visible = !empty($estimates_info->client_visible) && $estimates_info->client_visible == 'Yes' ? 'Yes' : 'No';
$show_quantity_as = !empty($estimates_info->show_quantity_as) ? strtolower((string) $estimates_info->show_quantity_as) : 'qty';
if (!in_array($show_quantity_as, array('qty', 'hours', 'qty_hours'), true)) {
    $show_quantity_as = 'qty';
}
$discount_percent = !empty($estimates_info) && isset($estimates_info->discount_percent) ? $estimates_info->discount_percent : 0;
$adjustment = !empty($estimates_info) && isset($estimates_info->adjustment) ? $estimates_info->adjustment : 0;
$tax_rates = $this->db->order_by('tax_rate_name', 'ASC')->get('tbl_tax_rates')->result();
$estimate_items = !empty($estimates_info) ? $this->estimates_model->ordered_items_by_id($estimates_info->estimates_id) : array();

$discount_options = array(
    '' => lang('no') . ' ' . lang('discount'),
    'before_tax' => lang('before_tax'),
    'after_tax' => lang('after_tax'),
);
$recurring_options = array(
    'none' => lang('none'),
    '7D' => lang('week'),
    '1M' => lang('month'),
    '3M' => lang('quarter'),
    '6M' => lang('six_months'),
    '1Y' => lang('1year'),
    '2Y' => lang('2year'),
    '3Y' => lang('3year'),
);

$client_lang = !empty($client_info->language) ? $client_info->language : 'english';
$currency = !empty($client_id)
    ? $this->estimates_model->client_currency_symbol($client_id)
    : $this->estimates_model->check_by(array('code' => config_item('default_currency')), 'tbl_currencies');
unset($this->lang->is_loaded[5]);
$this->lang->load('sales_lang', $client_lang, TRUE, FALSE, '', TRUE);

?>

<div class="space-y-5">
    <?= form_open(
        base_url('admin/estimates/converted/' . $estimate_id),
        array(
            'id' => 'from_items',
            'class' => 'space-y-5',
            'data-parsley-validate' => '',
            'novalidate' => '',
            'role' => 'form',
        )
    ); ?>

    <div class="grid grid-cols-1 gap-5 xl:grid-cols-12">
        <div class="space-y-5 xl:col-span-8">
            <div class="rounded-xl border border-border bg-card p-5 shadow-sm">
                <div class="mb-4 flex items-center gap-2 border-b border-border pb-3 text-sm font-semibold text-foreground">
                    <i data-lucide="file-text" class="h-5 w-5"></i>
                    <span><?= lang('invoice') . ' ' . lang('details') ?></span>
                </div>
                <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                    <?= form_input_group('reference_no', lang('reference_no'), $reference_no, 'text', true); ?>
                    <?= form_datepicker('invoice_date', lang('invoice_date'), $invoice_date, true, array('data-max' => '#due_date', 'data-auto-close' => 'true')); ?>
                    <?= form_datepicker('due_date', lang('due_date'), $due_date, true, array('data-min' => '#invoice_date', 'data-auto-close' => 'true')); ?>
                    <?= form_select_group('discount_type', lang('discount_type'), $discount_options, $discount_type, false, array('data-discount-type' => '1')); ?>
                    <?= form_lookup_group(
                        'client_id',
                        lang('client'),
                        $client_id,
                        $client_label,
                        true,
                        array('placeholder' => lang('select') . ' ' . lang('client')),
                        'md:col-span-1',
                        array('type' => 'client')
                    ); ?>
                    <?= form_lookup_group(
                        'project_id',
                        lang('project'),
                        $project_id,
                        $project_label,
                        false,
                        array('placeholder' => lang('select') . ' ' . lang('project')),
                        'md:col-span-1',
                        array('type' => 'project', 'depends' => 'client_id')
                    ); ?>
                    <?= form_lookup_group(
                        'warehouse_id',
                        lang('warehouse'),
                        $warehouse_id,
                        $warehouse_label,
                        false,
                        array('placeholder' => lang('select') . ' ' . lang('warehouse')),
                        'md:col-span-1',
                        array('type' => 'warehouse')
                    ); ?>
                </div>
            </div>

            <div class="rounded-xl border border-border bg-card p-5 shadow-sm">
                <div class="mb-4 flex items-center justify-between gap-3 border-b border-border pb-3">
                    <div class="flex items-center gap-2 text-sm font-semibold text-foreground">
                        <i data-lucide="repeat" class="h-5 w-5"></i>
                        <span><?= lang('recurring') ?></span>
                    </div>
                    <button type="button" id="start_recurring" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-1.5 text-xs font-semibold text-foreground hover:bg-muted">
                        <i data-lucide="calendar-clock" class="h-4 w-4"></i>
                        <?= lang('recurring') ?>
                    </button>
                </div>
                <div id="recurring" class="hidden grid grid-cols-1 gap-4 md:grid-cols-3">
                    <?= form_select_group('recuring_frequency', lang('recur_frequency'), $recurring_options, 'none', false, array('id' => 'recuring_frequency', 'disabled' => 'disabled')); ?>
                    <?= form_datepicker('recur_start_date', lang('start_date'), date('Y-m-d'), false, array('data-auto-close' => 'true')); ?>
                    <?= form_datepicker('recur_end_date', lang('end_date'), date('Y-m-d'), false, array('data-auto-close' => 'true')); ?>
                </div>
            </div>

            <div class="rounded-xl border border-border bg-card p-5 shadow-sm">
                <div class="mb-4 flex items-center gap-2 text-sm font-semibold text-foreground">
                    <i data-lucide="sticky-note" class="h-5 w-5"></i>
                    <span><?= lang('notes') ?></span>
                </div>
                <?= form_textarea_group('notes', '', $notes, 5, false, array('class' => 'textarea_2'), 'stacked'); ?>
            </div>
        </div>

        <div class="space-y-5 xl:col-span-4">
            <div class="rounded-xl border border-border bg-card p-5 shadow-sm">
                <div class="mb-4 flex items-center gap-2 text-sm font-semibold text-foreground">
                    <i data-lucide="user-check" class="h-5 w-5"></i>
                    <span><?= lang('assignment') ?></span>
                </div>
                <div class="space-y-4">
                    <?= form_lookup_group(
                        'user_id',
                        lang('sales') . ' ' . lang('agent'),
                        $selected_agent,
                        $selected_agent_label,
                        true,
                        array('placeholder' => lang('select') . ' ' . lang('sales') . ' ' . lang('agent')),
                        '',
                        array('type' => 'staff')
                    ); ?>
                    <?php
                    $all_payment = get_result('tbl_online_payment');
                    if (!empty($all_payment)) { ?>
                        <div class="space-y-2">
                            <div class="text-sm font-medium text-foreground"><?= lang('payment') . ' ' . lang('settings') ?></div>
                            <div class="grid grid-cols-1 gap-2">
                                <?php foreach ($all_payment as $payment) {
                                    $allow_gateway = 'allow_' . slug_it(strtolower($payment->gateway_name));
                                    $gateway_status = slug_it(strtolower($payment->gateway_name)) . '_status';
                                    if (config_item($gateway_status) == 'active') {
                                        echo form_checkbox($allow_gateway, lang($allow_gateway), true, false, array('value' => 'Yes'));
                                    }
                                } ?>
                            </div>
                        </div>
                    <?php } ?>
                    <?php if (!empty($project_id)) { ?>
                        <?= form_switch_radio('client_visible', lang('visible_to_client'), $client_visible); ?>
                    <?php } ?>
                </div>
            </div>

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

    <div class="rounded-xl border border-border bg-card p-5 shadow-sm">
        <?php
        $this->load->view('admin/common/sales_items_editor', array(
            'items' => $estimate_items,
            'tax_rates' => $tax_rates,
            'show_quantity_as' => $show_quantity_as,
            'discount_percent' => $discount_percent,
            'discount_type' => $discount_type,
            'adjustment' => $adjustment,
            'currency_symbol' => !empty($currency->symbol) ? $currency->symbol : default_currency(),
            'itemType' => 'convertToInvoice',
        ));
        ?>
    </div>

    <div class="flex flex-wrap items-center justify-end gap-2">
        <button type="button" data-dismiss="modal" 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('close') ?>
        </button>
        <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="check" class="h-4 w-4"></i>
            <?= lang('convert_to_invoice') ?>
        </button>
    </div>

    <?= form_close(); ?>
</div>

<script>
    (function () {
        if (typeof window.init_items_sortable === 'function') {
            window.init_items_sortable();
        }
        var recurringButton = document.getElementById('start_recurring');
        var recurringPanel = document.getElementById('recurring');
        var recurringFrequency = document.getElementById('recuring_frequency');
        if (recurringButton && recurringPanel) {
            recurringButton.addEventListener('click', function () {
                recurringPanel.classList.toggle('hidden');
                if (recurringFrequency) {
                    recurringFrequency.disabled = recurringPanel.classList.contains('hidden');
                }
            });
        }
        if (window.lucide) {
            window.lucide.createIcons();
        }
    })();
</script>
