<?php if (isset($invoice) || isset($add_items)) {
    $i = 1;
    $items_indicator = 'newitems';

    if (isset($invoice)) {
        $add_items = $invoice->items;
        $items_indicator = 'items';
    }

    /**
     * NOTE
     * Type of invoice since proforma use same template as invoice called
     * $this->load->view('admin/invoice_items/item_table_editable',['invoice'=>$proforma, 'docType' => 'proforma']);
     * we need the type to can condition on taxes processing which use diferent function than invoice
     */

    if (!isset($docType)) {
        $docType = 'invoice';
    }

} ?>

<div class="table-responsive s_table">
    <div class="table invoice-items-table items table-main-invoice-edit has-calculations no-mtop">
        <!-- Item add -->
        <div class="main itemAddForm">
            <?php //HEADING ?>
            <div class="main-row flex flex-row mb-5 border-solid border-b-2 border-gray-200">
                <div class="dragger-container">
                    <div class="dragger-spacer"></div>
                </div>
                <?php //fields first line ?>
                <div class="flex flex-row w-full item">

                    <!-- Denumire produs -->
                    <div class="col-item column__description">
                        <span class="xnbr"><i class="fal fa-exclamation-circle" aria-hidden="true" data-toggle="tooltip" data-title="<?php echo _l('item_description_new_lines_notice'); ?>"></i> <?php echo _l('inv_item_short_description'); ?></span>
                        <input type="hidden" name="type"/>
                        <input type="hidden" name="item_id"/>
                        <select name="" id="select-recc" class="form-control mg-b-4 <?php if (empty($invoice->recurring)) echo 'd-none'; ?>">
                            <option value="">--- <?php echo _l('Recurenta') ?> ---</option>
                            <option value="[SAPTAMANA]"><?php echo _l('[SAPTAMANA]'); ?></option>
                            <option value="[SAPTAMANA TRECUTA]"><?php echo _l('[SAPTAMANA TRECUTA]'); ?></option>
                            <option value="[SAPTAMANA URMATOARE]"><?php echo _l('[SAPTAMANA URMATOARE]'); ?></option>
                            <option value="[LUNA]"><?php echo _l('[LUNA]'); ?></option>
                            <option value="[LUNA VIITOARE]"><?php echo _l('[LUNA VIITOARE]'); ?></option>
                            <option value="[LUNA TRECUTA]"><?php echo _l('[LUNA TRECUTA]'); ?></option>
                            <option value="[AN]"><?php echo _l('[AN]'); ?></option>
                            <option value="[ANUL TRECUT]"><?php echo _l('[ANUL TRECUT]'); ?></option>
                            <option value="[ANUL URMATOR]"><?php echo _l('[ANUL URMATOR]'); ?></option>
                        </select>
                        <input type="text" id="add_item_description" name="description" class="form-control" placeholder="<?php echo _l('inv_item_short_description_placeholder'); ?>">
                    </div>

                    <!-- Descriere produs -->
                    <div class="col-item column__long_description column__cf <?php if (!(bool)$invoice_settings['use_description']) { ?>hide <?php } ?>">
                        <?php if ((bool)$invoice_settings['use_description']) { ?>
                            <span class="xnbr"><?php echo _l('inv_item_description'); ?></span>
                            <textarea name="long_description" rows="1" class="form-control" placeholder="<?php echo _l('inv_item_description__placeholder'); ?>"></textarea>
                        <?php } ?>
                        <?php
                        $custom_fields = get_custom_fields('items');
                        foreach ($custom_fields as $cf) {
                            echo '<th width="15%" align="left" class="custom_field">' . $cf['name'] . '</th>';
                        }
                        ?>
                        <?php echo render_custom_fields_items_table_add_edit_preview(); ?>
                    </div>

                    <!-- Cod produs -->
                    <div class="col-item column__sku <?php if (!(bool)$invoice_settings['use_product_code']) { ?>hide <?php } ?>">
                        <span class="xnbr"><?php echo _l('inv_item_sku'); ?></span>
                        <input type="text" name="sku" id="invoice_item_sku" class="form-control" placeholder="<?php echo _l('inv_item_sku__placeholder'); ?>">
                    </div>

                    <!-- U.M -->
                    <div class="col-item column__unit">
                        <?php
                        $qty_heading = _l('invoice_table_quantity_heading');

                        if (isset($invoice) && $invoice->show_quantity_as == 2 || isset($hours_quantity)) {
                            $qty_heading = _l('invoice_table_hours_heading');
                        } else if (isset($invoice) && $invoice->show_quantity_as == 3) {
                            $qty_heading = _l('invoice_table_quantity_heading') . '/' . _l('invoice_table_hours_heading');
                        }

                        $qty_heading = _l('inv_item_unit');
                        ?>
                        <span class="qty align-center xnbr"><?php echo $qty_heading; ?></span>
                        <input type="text" placeholder="<?php echo _l('inv_item_unit__placeholder'); ?>" data-toggle="tooltip" data-title="<?= _l('inv_item_unit__tooltip'); ?>" name="unit" class="form-control input-transparent text-right">
                    </div>

                    <!-- Cantitate -->
                    <div class="col-item column__quantity">
                        <span class="xnbr"><?php echo _l('inv_item_quantity'); ?></span>
                        <input type="number" name="quantity" value="1" class="form-control" placeholder="<?php echo _l('inv_item_quantity__placeholder'); ?>">
                    </div>

                    <!-- Cota Tva -->
                    <div class="col-item column__taxes <?php if (!$settings['vat_payer'] == 1) { ?>hide<?php } ?>">
                        <?php if ($settings['vat_payer'] == 1) { ?>
                            <span class="xnbr"><?php echo _l('inv_item_tax'); ?></span>
                            <?php
                            $default_tax = unserialize(get_option('default_tax'));
                            $select = '<select class="selectpicker display-block tax main-tax" data-width="100%" name="taxname" X-multiple data-none-selected-text="' . _l('no_tax') . '">';

                            foreach ($taxes as $tax) {
                                $selected = '';

                                if (is_array($default_tax)) {
                                    if (in_array($tax['name'] . '|' . $tax['taxrate'], $default_tax)) {
                                        $selected = ' selected ';
                                    }
                                }
                                $select .= '<option value="' . $tax['name'] . '|' . $tax['taxrate'] . '"' . $selected . 'data-taxrate="' . $tax['taxrate'] . '" data-taxname="' . $tax['name'] . '" data-subtext="' . $tax['name'] . '">' . $tax['taxrate'] . '%</option>';
                            }

                            $select .= '</select>';
                            echo $select;
                            ?>
                        <?php } ?>
                    </div>

                    <!-- Moneda -->
                    <div class="col-item column__currency">
                        <div>
                            <span class="xnbr"><?php echo _l('inv_item_currency'); ?></span>
                            <?php

                            $currency_attr = array('data-show-subtext' => true);
                            $currency_attr = apply_filters_deprecated('invoice_currency_disabled', [$currency_attr], '2.3.0', 'invoice_currency_attributes');

                            foreach ($currencies as $currency) {

                                if ($currency['isdefault'] == 1) {
                                    $currency_attr['data-base'] = $currency['id'];
                                }

                                if (isset($invoice)) {
                                    if ($currency['id'] == $invoice->currency) {
                                        $selected = $currency['id'];
                                    }
                                } else {
                                    if ($currency['isdefault'] == 1) {
                                        $selected = $currency['id'];
                                    }
                                }
                            }

                            $currency_attr = hooks()->apply_filters('invoice_currency_attributes', $currency_attr);
                            ?>
                            <?php echo render_select('invoice_item_currency', $currencies, array('id', 'name', 'symbol'), null, $selected, $currency_attr); ?>
                        </div>

                        <div>
                            <div class="rateRowInput">
                                <span class="xnbr text-sm">Curs <span class="needSelectedCurrency font-semibold"></span></span>
                                <input type="number" readonly name="invoice_item_currency_rate" class="form-control invoice_item_currency_rate" placeholder="" value="">
                            </div>
                        </div>

                    </div>

                    <!-- Pret -->
                    <div class="col-item column__price">
                        <div>
                            <span class="xnbr"><?php echo _l('inv_item_price'); ?> <span class="needSelectedCurrencyAdd font-semibold"></span></span>
                            <div>
                                <input data-inputmask="'alias': 'decimal', 'allowMinus' : true" name="rate" id="rate" class="form-control" placeholder="<?php echo _l('inv_item_price__placeholder'); ?>">
                            </div>

                            <div class="priceRowInput">
                                <span class="xnbr text-sm">Pret</span>
                                <input type="number" readonly name="invoice_item_price_converted" class="form-control invoice_item_price_converted" placeholder="" value="">
                            </div>
                        </div>
                    </div>

                    <!-- Action button -->
                    <div class="col-item column__actions_add mt-5">
                        <?php
                        $new_item = 'undefined';
                        if (isset($invoice)) {
                            $new_item = true;
                        }
                        ?>
                        <button type="button" id="itemable_item_add" onclick="crm_add_invoice_item_2('undefined','undefined',<?php echo $new_item; ?>); return false;" Xonclick="add_item_to_table('undefined','undefined',<?php echo $new_item; ?>); return false;" class="btn btn-info invoice_btn invoiceSave">
                            <i class="fal fa-check"></i></button>
                    </div>
                </div>
            </div>
        </div>

        <!--
        <div id="invoice_itamable_items" class="mb-40"></div>
                -->


        <!-- Item edit -->
        <div class="list_items ui-sortable">
            <?php if (isset($invoice) || isset($add_items)) {
                $i = 1;
                $items_indicator = 'newitems';

                if (isset($invoice)) {
                    $add_items = $invoice->items;
                    $items_indicator = 'items';
                }
                foreach ($add_items as $item) {
                    $manual = false;
                    ?>
                    <div class="sortable item flex flex-row mb-5 border-solid border-b-2 border-gray-200" id="item-id-<?= $item['id']; ?>" item="<?= $item['id']; ?>">
                        <!-- Dragger -->
                        <div class="dragger-container">
                            <div class="dragger dragger-spacer">
                                <?php
                                if (!is_numeric($item['qty'])) {
                                    $item['qty'] = 1;
                                }

                                if ($settings['vat_payer'] == 1) {

                                    /**
                                     * Cases when the docType is diferent
                                     * since other document types use this items template
                                     */
                                    switch ($docType) {
                                        case 'proforma':
                                            $invoice_item_taxes = get_proforma_item_taxes($item['id']);
                                            break;

                                        default:
                                            $invoice_item_taxes = get_invoice_item_taxes($item['id']);
                                            break;
                                    }

                                    // passed like string
                                    if ($item['id'] == 0) {
                                        $invoice_item_taxes = $item['taxname'];
                                        $manual = true;
                                    }
                                }

                                echo form_hidden('' . $items_indicator . '[' . $i . '][itemid]', $item['id']);

                                $amount = $item['rate'] * $item['qty'];
                                $amount = app_format_number($amount);
                                // order input

                                ?>
                                <input type="hidden" class="order" name="<?= $items_indicator ?>[<?= $i ?>][order]">
                            </div>
                        </div>

                        <!-- Item -->
                        <div class="flex flex-row w-full">

                            <!-- Denumire produs -->
                            <div class="col-item column__description">
                                <input type="text" name="<?= $items_indicator ?>[<?= $i; ?>][description]" required class="form-control" value="<?= clear_textarea_breaks($item['description']) ?>">
                            </div>

                            <!-- Descriere produs -->
                            <div class="col-item column__long_description column__cf <?php if (!(bool)$invoice_settings['use_description']) { ?>hide <?php } ?>">
                                <?php if ((bool)$invoice_settings['use_description']) { ?>
                                    <textarea name="<?= $items_indicator ?>[<?= $i; ?>][long_description]" class="form-control" rows="1"><?= clear_textarea_breaks($item['long_description']) ?></textarea>
                                <?php } ?>

                                <!-- CF -->
                                <?php echo render_custom_fields_items_table_in($item, $items_indicator . '[' . $i . ']'); ?>
                            </div>

                            <!-- Cod produs -->
                            <div class="col-item column__sku <?php if (!(bool)$invoice_settings['use_product_code']) { ?>hide <?php } ?>">
                                <input type="text" placeholder="" name="<?= $items_indicator ?>[<?= $i; ?>][sku]" class="form-control input-transparent text-right" value="<?= $item['sku'] ?>">
                            </div>

                            <!-- U.M -->
                            <div class="col-item column__unit">
                                <?php
                                $unit_placeholder = '';

                                if (!$item['unit']) {
                                    $unit_placeholder = _l('unit');
                                    $item['unit'] = '';
                                }
                                ?>
                                <input type="text" placeholder="<?= $unit_placeholder ?>" name="<?= $items_indicator ?>[<?= $i; ?>][unit]" required class="form-control input-transparent text-right" value="<?= $item['unit'] ?>">
                            </div>

                            <!-- Cantitate -->
                            <div class="col-item column__quantity">
                                <input type="number" onblur="crm_calculate_total();" onchange="crm_calculate_total();" data-quantity name="<?= $items_indicator ?>[<?= $i; ?>][qty]" required value="<?= $item['qty'] ?>" class="form-control">
                            </div>

                            <!-- Cota Tva -->
                            <div class="col-item column__taxes <?php if (!$settings['vat_payer'] == 1) { ?>hide<?php } ?>">
                                <?php if ($settings['vat_payer'] == 1) { ?>
                                    <div class="taxrate"><?= $this->misc_model->get_taxes_dropdown_template('' . $items_indicator . '[' . $i . '][taxname][]', $invoice_item_taxes, 'invoice', $item['id'], true, $manual) . ''; ?></div>
                                <?php } ?>
                            </div>

                            <!-- Moneda -->
                            <div class="col-item column__currency">
                                <div>
                                    <!--item currency-->
                                    <?php
                                    $currency_attr = ['data-show-subtext' => true, 'required' => 'required'];
                                    $currency_attr = apply_filters_deprecated('invoice_currency_disabled', [$currency_attr], '2.3.0', 'invoice_currency_attributes');

                                    foreach ($currencies as $currency) {
                                        if ($currency['isdefault'] == 1) {
                                            $currency_attr['data-base'] = $currency['id'];
                                        }
                                        if (isset($invoice)) {
                                            if ($currency['id'] == $invoice->currency) {
                                                //$selected = $currency['id'];
                                            }

                                            if ($currency['id'] == $item['currency']) {
                                                $selected = $currency['id'];
                                            }

                                        } else {
                                            if ($currency['isdefault'] == 1 && !$item['currency']) {
                                                $selected = $currency['id'];
                                            } else {
                                                $selected = $item['currency'];
                                            }
                                        }
                                    }
                                    $has_same_currency = false;
                                    if (isset($invoice)) {
                                        if ($selected == $invoice->currency) {
                                            $has_same_currency = true;
                                        } else {
                                            $has_same_currency = false;
                                        }
                                    }


                                    $currency_attr = hooks()->apply_filters('invoice_currency_attributes', $currency_attr);
                                    ?>
                                    <?php echo render_select($items_indicator . '[' . $i . '][currency]', $currencies, array('id', 'name', 'symbol'), null, $selected, $currency_attr, null, null, 'dropdown_currency'); ?>
                                    <!--@end item currency-->
                                </div>
                                <!-- #CURS -->
                                <div class="rateRowInput hidden <?= !$has_same_currency ? 'block' : "hidden"; ?>">
                                    <span class="xnbr text-sm font-semibold">Curs</span>
                                    <input readonly type="number" step="0.0001" name="<?= $items_indicator ?>[<?= $i; ?>][currency_rate]" class="form-control invoice_item_currency_rate" placeholder="" value="<?= $item['currency_rate'] == 0 ? 1 : $item['currency_rate']; ?>">
                                </div>
                            </div>

                            <!-- Pret -->
                            <div class="col-item column__price">
                                <div>

                                    <div><input
                                                data-inputmask="'alias': 'decimal', 'allowMinus' : false"
                                                data-toggle="tooltip"
                                                title="<?= _l('numbers_not_formatted_while_editing') ?>"
                                                onblur="crm_calculate_total();"
                                                onchange="crm_calculate_total();"
                                                name="<?= $items_indicator ?>[<?= $i; ?>][rate]"
                                                value="<?= $item['rate']; ?>" class="form-control item_rate">
                                    </div>
                                    <?php /*<span  align="right">Line total: <?= $amount ?></span> */ ?>
                                </div>

                                <!-- #Pret -->
                                <div class="priceRowInput <?= !$has_same_currency ? 'block' : "hidden"; ?>">
                                    <span class="xnbr text-sm">Pret <span class="needSelectedCurrency font-semibold"></span></span>
                                    <input type="number" readonly name="<?= $items_indicator ?>[<?= $i; ?>][price_converted]" class="form-control invoice_item_price_converted" placeholder="" value="<?= round($item['price_converted'], 2); ?>">
                                </div>
                            </div>

                            <!-- Action button -->
                            <div class="col-item column__actions">
                                <div>
                                    <button href="#" class="btn btn-danger invoice-del pull-left invoiceSave" onclick="crm_delete_item(this,<?= $item['id'] ?>); return false;">
                                        <i class="fal fa-times"></i></button>
                                    <?php
                                    if (isset($item['task_id'])) {
                                        if (!is_array($item['task_id'])) {
                                            echo form_hidden('billed_tasks[' . $i . '][]', $item['task_id']);
                                        } else {
                                            foreach ($item['task_id'] as $task_id) {
                                                echo form_hidden('billed_tasks[' . $i . '][]', $task_id);
                                            }
                                        }
                                    } else if (isset($item['expense_id'])) {
                                        echo form_hidden('billed_expenses[' . $i . '][]', $item['expense_id']);
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php
                    $i++;
                }
            }
            ?>
        </div>
    </div>
</div>
