<?php defined('BASEPATH') or exit('No direct script access allowed'); ?>

<script type="text/javascript">
    if (typeof init_items_sortable !== 'function') {
        window.init_items_sortable = function() {
            return true;
        };
    }
</script>

<?php
$invoice_info = isset($invoice_info) ? $invoice_info : null;
$expense_info = isset($expense_info) ? $expense_info : null;

$category_info = $this->db->where('expense_category_id', $expense_info->category_id)->get('tbl_expense_category')->row();
$category = !empty($category_info->expense_category) ? $category_info->expense_category : lang('undefined_category');

$client_info = $this->invoice_model->check_by(array('client_id' => $expense_info->paid_by), 'tbl_client');
$client_lang = !empty($client_info->language) ? $client_info->language : 'english';
unset($this->lang->is_loaded[5]);
$language_info = $this->lang->load('sales_lang', $client_lang, true, false, '', true);

$client_id = !empty($expense_info->paid_by) ? $expense_info->paid_by : (!empty($invoice_info->client_id) ? $invoice_info->client_id : '');
$project_id = !empty($expense_info->project_id) ? $expense_info->project_id : (!empty($invoice_info->project_id) ? $invoice_info->project_id : '');

$reference_no = '';
if (!empty($invoice_info->reference_no)) {
    $reference_no = $invoice_info->reference_no;
} else {
    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->invoice_model->generate_invoice_number();
    }
}

$invoice_date = !empty($invoice_info->invoice_date) ? $invoice_info->invoice_date : date('Y-m-d');
$due_date = !empty($invoice_info->due_date) ? $invoice_info->due_date : date('Y-m-d', safe_strtotime('+' . config_item('invoices_due_after') . ' days'));

$recurring_enabled = !empty($invoice_info) && $invoice_info->recurring == 'Yes';
$recur_start_date = $recurring_enabled ? date('Y-m-d', safe_strtotime($invoice_info->recur_start_date)) : date('Y-m-d');
$recur_end_date = $recurring_enabled ? date('Y-m-d', safe_strtotime($invoice_info->recur_end_date)) : date('Y-m-d');

$discount_type = !empty($invoice_info->discount_type) ? $invoice_info->discount_type : '';
$permissionL = !empty($invoice_info->permission) ? $invoice_info->permission : null;
$invoices_id = !empty($invoice_info->invoices_id) ? $invoice_info->invoices_id : null;
$selected_agent = !empty($invoice_info->user_id) ? $invoice_info->user_id : $this->session->userdata('user_id');
$notes = !empty($invoice_info->notes) ? $invoice_info->notes : $this->config->item('default_terms');
$client_visible = !empty($invoice_info->client_visible) ? $invoice_info->client_visible : 'No';

$client_options = array('' => lang('select') . ' ' . lang('client'));
$all_client = $this->db->order_by('name', 'ASC')->get('tbl_client')->result();
if (!empty($all_client)) {
    foreach ($all_client as $client_row) {
        $client_options[$client_row->client_id] = ucfirst($client_row->name);
    }
}

$project_options = array('' => lang('none'));
if (!empty($client_id)) {
    $all_project = $this->db->where('client_id', $client_id)->order_by('project_name', 'ASC')->get('tbl_project')->result();
    if (!empty($all_project)) {
        foreach ($all_project as $project_row) {
            $project_options[$project_row->project_id] = $project_row->project_name;
        }
    }
}

$profile = profile();
$warehouse_options = array('' => lang('select') . ' ' . lang('warehouse'));
$warehouse_where = array('status' => 'published');
if (!empty($profile) && $profile->role_id == 3) {
    $warehouse_where['warehouse_id'] = $this->session->userdata('warehouse_id');
}
$warehouse_rows = $this->db->where($warehouse_where)->order_by('warehouse_name', 'ASC')->get('tbl_warehouse')->result();
if (!empty($warehouse_rows)) {
    foreach ($warehouse_rows as $warehouse_row) {
        $warehouse_options[$warehouse_row->warehouse_id] = $warehouse_row->warehouse_name;
    }
}
$warehouse_selected = !empty($invoice_info->warehouse_id) ? $invoice_info->warehouse_id : (!empty($this->session->userdata['warehouse_id']) ? $this->session->userdata['warehouse_id'] : '');
$warehouse_append = '';
if (!empty($profile) && $profile->role_id == 1) {
    $warehouse_append = '<a data-toggle="modal" data-target="#myModal_lg" href="' . base_url() . 'admin/warehouse/create/0/from_warehouse_id" class="inline-flex items-center text-slate-500 hover:text-slate-700 dark:text-slate-300 dark:hover:text-slate-100"><i data-lucide="plus" class="h-4 w-4"></i></a>';
}

$agent_options = array('' => lang('select') . ' ' . lang('sales') . ' ' . lang('agent'));
$all_user = $this->db->where('role_id != ', 2)->order_by('sort_user', 'ASC')->get('tbl_users')->result();
if (!empty($all_user)) {
    foreach ($all_user as $user_row) {
        $profile_info = $this->db->where('user_id', $user_row->user_id)->get('tbl_account_details')->row();
        if (!empty($profile_info->fullname)) {
            $agent_options[$user_row->user_id] = $profile_info->fullname;
        }
    }
}

$discount_options = array(
    '' => lang('no') . ' ' . lang('discount'),
    'before_tax' => lang('before_tax'),
    'after_tax' => lang('after_tax'),
);

$client_created = can_action('4', 'created');
$new_client_link = '';
if (!empty($client_created)) {
    $new_client_link = '<a data-toggle="modal" data-target="#myModal" href="' . base_url('admin/client/new_client') . '" class="inline-flex items-center text-slate-500 hover:text-slate-700 dark:text-slate-300 dark:hover:text-slate-100"><i data-lucide="plus" class="h-4 w-4"></i></a>';
}

$custom_fields_html = custom_form_Fields(9, $invoices_id);
$expense = !empty($expense_info) ? array($expense_info->transactions_id) : null;
$pdata['itemType'] = 'invoice';
$pdata['warehouseId'] = $warehouse_selected;
if (!empty($expense_info)) {
    $pdata['add_items'] = $this->items_model->make_all_items($expense_info->project_id, '', '', $expense, true);
}
?>

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

    <?= form_open(base_url('admin/projects/save_invoice/' . $expense_info->project_id), array('class' => 'space-y-6', 'data-parsley-validate' => '', 'novalidate' => '', 'id' => 'transaction-convert-invoice-form')); ?>
        <div class="rounded-2xl border border-border bg-card p-6 shadow-sm">
            <div class="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
                <div>
                    <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"><?= lang('preview_invoice') ?></p>
                    <h1 class="text-2xl font-semibold text-foreground"><?= '[' . $category . '] ' . $expense_info->name ?></h1>
                    <p class="text-sm text-muted-foreground"><?= lang('convert_to_invoice') . ' ' . lang('from') . ' ' . lang('expense') ?></p>
                </div>
                <div class="flex flex-wrap items-center gap-2">
                    <a href="<?= base_url('admin/transactions/view_details/' . $expense_info->transactions_id) ?>" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium text-foreground hover:bg-muted">
                        <i data-lucide="arrow-left" class="h-4 w-4"></i>
                        <?= lang('back') ?>
                    </a>
                    <button type="submit" name="save_as_draft" value="1" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-sm font-medium text-foreground hover:bg-muted">
                        <i data-lucide="save" class="h-4 w-4"></i>
                        <?= lang('save') ?>
                    </button>
                    <button type="submit" name="create" value="1" class="inline-flex items-center gap-2 rounded-lg bg-slate-950 px-3 py-2 text-sm font-medium text-white hover:bg-slate-800 dark:bg-white dark:text-slate-950 dark:hover:bg-slate-100">
                        <i data-lucide="file-plus-2" class="h-4 w-4"></i>
                        <?= lang('create_invoice') ?>
                    </button>
                </div>
            </div>
        </div>

        <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 flex-wrap 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="file-text" class="h-5 w-5"></i>
                            <h2 class="text-base font-semibold text-foreground"><?= lang('invoice') . ' ' . lang('details') ?></h2>
                        </div>
                        <button type="button" id="toggle_recurring" class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground hover:bg-muted">
                            <i data-lucide="repeat" class="h-4 w-4"></i>
                            <?= lang('recurring') ?>
                        </button>
                    </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('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_select_group('client_id', lang('client'), $client_options, $client_id, true, array('class' => 'select_box', 'data-live-search' => 'true', 'onchange' => 'get_project_by_id(this.value)'), '', $new_client_link); ?>
                        <?= form_select_group('project_id', lang('project'), $project_options, $project_id, false, array('class' => 'select_box', 'data-live-search' => 'true', 'id' => 'client_project')); ?>
                        <?= form_select_group('warehouse_id', lang('warehouse'), $warehouse_options, $warehouse_selected, true, array('class' => 'select_box mwarehouse', 'data-live-search' => 'true', 'id' => 'warehouse', 'onchange' => 'getItemByWarehouse(this.value)', 'style' => 'width:100%'), '', $warehouse_append); ?>
                        <?= form_select_group('user_id', lang('sales') . ' ' . lang('agent'), $agent_options, $selected_agent, true, array('class' => 'select_box', 'data-live-search' => 'true')); ?>
                    </div>

                    <input type="hidden" name="warehouseId" class="WarehouseValue" value="<?= html_escape($warehouse_selected) ?>">

                    <div id="recurring_fields" class="rounded-xl border border-dashed border-border p-4 space-y-4 <?= $recurring_enabled ? '' : 'hidden' ?>">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <?= form_select_group(
                                'recuring_frequency',
                                lang('recur_frequency'),
                                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'),
                                ),
                                !empty($invoice_info->recur_frequency) ? $invoice_info->recur_frequency : 'none'
                            ); ?>
                            <?= form_datepicker('recur_start_date', lang('start_date'), $recur_start_date, false, array('data-format' => config_item('date_picker_format'))); ?>
                            <?= form_datepicker('recur_end_date', lang('end_date'), $recur_end_date, false, array('data-format' => config_item('date_picker_format'))); ?>
                        </div>
                    </div>
                </div>

                <div class="rounded-xl border border-border bg-card p-0 overflow-hidden">
                    <?php $this->load->view('admin/items/selectItem', $pdata); ?>
                </div>

                <div class="rounded-xl border border-border bg-card p-6">
                    <?= form_editor('notes', lang('notes'), $notes, false); ?>
                </div>
            </div>

            <aside 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 border-b border-border pb-2">
                        <i data-lucide="settings" class="h-5 w-5"></i>
                        <h2 class="text-base font-semibold text-foreground"><?= lang('settings') ?></h2>
                    </div>

                    <div class="grid grid-cols-1 gap-4">
                        <?php
                        $all_payment = get_result('tbl_online_payment');
                        if (!empty($all_payment)) {
                            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') { ?>
                                    <label class="inline-flex items-center gap-2 rounded-lg border border-border bg-card px-3 py-2 text-xs font-semibold text-foreground">
                                        <input type="checkbox" name="<?= $allow_gateway ?>" value="Yes" <?= (!empty($invoice_info) && !empty($invoice_info->$allow_gateway) && $invoice_info->$allow_gateway == 'Yes') ? 'checked' : '' ?>>
                                        <span><?= lang($allow_gateway) ?></span>
                                    </label>
                                <?php }
                            }
                        } ?>

                        <?php if (!empty($project_id)) { ?>
                            <?= form_switch_radio('client_visible', lang('visible_to_client'), $client_visible); ?>
                        <?php } ?>
                    </div>
                </div>

                <?= form_permission_modern($permission_user, $permissionL); ?>

                <?php if (!empty($custom_fields_html)) { ?>
                    <div class="rounded-xl border border-border bg-card p-6 space-y-4">
                        <div class="text-sm font-semibold text-foreground"><?= lang('custom_field') ?></div>
                        <?= $custom_fields_html ?>
                    </div>
                <?php } ?>
            </aside>
        </div>
    <?= form_close(); ?>
</div>

<style>
    .note-editor .note-editable {
        height: 180px;
    }

    .dropdown-menu > li > a {
        white-space: normal;
    }

    .dragger {
        background: url(../../assets/img/dragger.png) 10px 32px no-repeat;
        cursor: pointer;
    }

    .input-transparent {
        box-shadow: none;
        outline: 0;
        border: 0 !important;
        background: 0 0;
        padding: 3px;
    }

    #transaction-convert-invoice-form .prodcutTable {
        border: 0;
        border-radius: 0;
        box-shadow: none;
    }
</style>

<script type="text/javascript">
    $(document).ready(function() {
        var recurringFields = $('#recurring_fields');
        var recurringSelect = $('#recuring_frequency');

        $('#toggle_recurring').on('click', function() {
            recurringFields.toggleClass('hidden');
            recurringSelect.prop('disabled', recurringFields.hasClass('hidden'));
        });

        recurringSelect.prop('disabled', recurringFields.hasClass('hidden'));

        if (typeof init_items_sortable === 'function') {
            init_items_sortable();
        }
    });

    window.get_project_by_id = function(clientId) {
        var projectSelect = document.getElementById('client_project');
        if (!projectSelect) {
            return;
        }

        var emptyOption = '<option value=""><?= lang('none') ?></option>';

        function refreshProjectSelect() {
            if (typeof jQuery !== 'undefined' && typeof jQuery(projectSelect).selectpicker === 'function') {
                jQuery(projectSelect).selectpicker('refresh');
            }
        }

        if (!clientId) {
            projectSelect.innerHTML = emptyOption;
            refreshProjectSelect();
            return;
        }

        if (typeof jQuery !== 'undefined' && typeof jQuery.ajax === 'function') {
            jQuery.ajax({
                url: '<?= base_url('admin/common/get_project_by_client_id/') ?>' + clientId,
                type: 'GET',
                success: function(response) {
                    projectSelect.innerHTML = response || emptyOption;
                    refreshProjectSelect();
                },
                error: function() {
                    projectSelect.innerHTML = emptyOption;
                    refreshProjectSelect();
                }
            });
            return;
        }

        fetch('<?= base_url('admin/common/get_project_by_client_id/') ?>' + clientId, {
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
            .then(function(response) {
                return response.text();
            })
            .then(function(html) {
                projectSelect.innerHTML = html || emptyOption;
                refreshProjectSelect();
            })
            .catch(function() {
                projectSelect.innerHTML = emptyOption;
                refreshProjectSelect();
            });
    };
</script>
