<?php $this->load->view('site/layout'); ?>

<?php
if ($this->session->userdata('language') == "english") {
    $language_set = "arabic";
} else {
    $language_set = "english";
}
if ($language_set == "english") {
    ?>
    <link href="<?php echo base_url() ?>public/plugins/custom/fullcalendar/fullcalendar.bundle.rtl.css" rel="stylesheet" type="text/css" />
<?php } else { ?>
    <link href="<?php echo base_url() ?>public/plugins/custom/datatables/datatables.bundle.css" rel="stylesheet" type="text/css" />


<?php } ?>
<style>
    .add_icon{
        float: right;
        padding-right: 15px;
        cursor: pointer;
    }
    #invoice_items tr{
        margin-bottom: 10px;
    }
    .select2{
        width: 100% !important;
    }
    .total_price{
        background-color: #eaedf2;
        height: calc(1.5em + 1.3rem + 2px);
    }
    .btn:hover {
        color: #fff !important;
    }
    .address_option{
        margin-right: 10px;
        margin-left: 10px;
        margin-bottom: 20px;
    }
    .delete_item{
        margin-top: 26px;
    }
    .num_width{
        width: 10%;
    }
    .comment_width{
        width: 25%;
    }
    .price{
        height: 38px;
    }
    .submit_add_address_form{
        color: #fff !important;
    }
    .inv_total{
        background-color: #eaedf2;
    }
    .btn:hover {
        color: #ccc !important;
    }
</style>
<?php $this->load->view('site/navbar'); ?>
<div class="kt-content  kt-grid__item kt-grid__item--fluid kt-grid kt-grid--hor" id="kt_content">

    <!-- begin:: Content Head -->
    <div class="kt-subheader  kt-grid__item" id="kt_subheader">
        <div class="kt-container  kt-container--fluid ">
            <div class="kt-subheader__main">
                <h3 class="kt-subheader__title"><a href="<?php echo base_url() ?>Dashboard/"><?php echo $this->lang->line('dashboard'); ?></a></h3>
                <span class="kt-subheader__separator kt-hidden"></span>
                <div class="kt-subheader__breadcrumbs">
                    <a href="#" class="kt-subheader__breadcrumbs-home"><i class="flaticon2-shelter"></i></a>
                    <span class="kt-subheader__breadcrumbs-separator"></span>
                    <a href="<?= base_url('orders/') ?>" class="kt-subheader__breadcrumbs-link">
                        <?= $call_center ? $this->lang->line('orders') : $this->lang->line('invoices') ?> </a>
                    <span class="kt-subheader__breadcrumbs-separator"></span>
                </div>

            </div>
        </div>
    </div>
    <div class="kt-portlet">
        <div class="kt-portlet__head">
            <div class="kt-portlet__head-label">
                <h3 class="kt-portlet__head-title">
                    <?= $call_center ? $this->lang->line('add_order') : $this->lang->line('add-an-invoice') ?>
                </h3>
            </div>
        </div>
        <?php echo form_open_multipart(base_url('' . $thispage . '/add/' . $call_center)); ?>
        <!-- <form class="kt-form kt-form--label-right"> -->
        <div class="kt-portlet__body">
            <?php if ($this->session->flashdata('msg') || validation_errors() !== '' || isset($msg) || $error_msg != ''): ?>
                <div class="form-group form-group-last">
                    <div class="alert alert-danger" role="alert">
                        <div class="alert-icon"><i class="flaticon-warning kt-font-brand"></i></div>
                        <div class="alert-text">
                            <?= validation_errors(); ?>
                            <?= isset($msg) ? $msg : ''; ?>
                            <?= $this->session->flashdata('msg') ?>
                            <?= $error_msg ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            <?php if ($this->session->flashdata('success')): ?>
                <div class="form-group form-group-last">
                    <div class="alert alert-success" role="alert">
                        <div class="alert-icon"><i class="flaticon2-checkmark"></i></div>
                        <div class="alert-text">
                            <?= $this->session->flashdata('success') ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            <div class="form-group row">
<!--                          <label for="example-text-input" class="col-3 col-form-label"><?php //echo $this->lang->line('products')                                                                                                                                                                                                                 ?></label>
<div class="col-9">
<select class="form-control " name="id_producer[]"  multiple="multiple" required>
                <?php //$count=0; foreach($bills_producer as $row){ ?>
<option  value="<?//= $row['id']; ?>"><?//= $row['name']; ?></option>

                <?php //} ?>
</select>
</div>-->
            </div>
            <div class="form-group row">
                <label for="example-search-input" class="col-3 col-form-label"><?php echo $this->lang->line('the-students') ?></label>
                <div class="col-8">
                    <select multiple name="id_user[]" class="topnav form-control students" >
                        <?php
                        $count = 0;
                        foreach ($bills_user as $row) {
                            $selected = '';
                            if ($this->session->flashdata('student_id') && $this->session->flashdata('student_id') == $row['id']) {
                                $selected = 'selected';
                            }
                            if ($this->input->post('id_user') && is_array($this->input->post('id_user')) && in_array($row['id'], $this->input->post('id_user'))) {
                                $selected = 'selected';
                            }
                            ?>
                            <option <?= $selected ?> value="<?= $row['id'] ?>" data-id="<?= $row['id'] ?>"><?= $row['username'] . ' - ' . $row['phone'] ?></option>
                        <?php } ?>
                    </select>
                </div>
                <div class="col-1" style="margin-top: -13px;cursor: pointer;">
                    <i class="flaticon-plus text-primary fa-3x" onclick="add_student()" title="<?= $this->lang->line('add') . ' ' . $this->lang->line('student') ?>"></i>
                </div>
            </div>
            <br/>
            <h2><?= $this->lang->line('select_addresses') ?></h2>
            <div id="addresses"></div>
            <hr/>
            <h2><strong><?= $this->lang->line('products') ?></strong></h2>
            <input type="hidden" name="products_count" id="products_count" value="1" />
            <table id="invoice_items">

                <tr id="first" class="produtcs_">
                    <td><label class="form-label"><?= $this->lang->line('product') ?></label><select class="form-control product" name="id_producer[]" >
                            <option value><?= $this->lang->line('select') ?></option>
                            <?php
                            foreach ($bills_producer as $row) {
                                $selected = '';
                                if ($this->input->post() && $this->input->post('id_producer')[0] == $row['id']) {
                                    $selected = 'selected';
                                }
                                ?>
                                <option <?= $selected ?> value="<?= $row['id']; ?>"><?= $row['name']; ?></option>
                            <?php } ?>
                        </select>
                        <div class="product_additions">

                        </div>
                    </td>

                    <td class="num_width"><label class="form-label"><?= $this->lang->line('the-amount') ?></label>
                        <input type="hidden" class="product_price" />
                        <?php if (get_ap('edit_price_in_inv', $this->operator_id)) { ?>
                            <input type="text" name="amount[]" value="<?= isset(set_value('amount')[0]) ? set_value('amount')[0] : '' ?>" class="form-control price" placeholder="<?= $this->lang->line('the-amount') ?>" />
                        <?php } else { ?>
                            <input type="hidden" name="amount[]" value="<?= isset(set_value('amount')[0]) ? set_value('amount')[0] : '' ?>" class="price_hidden" />
                            <span class="price form-control" style="width:100%"><?= $this->lang->line('the-amount') ?></span>
                        <?php } ?>
                    </td>
                    <td class="num_width quantity_container"><div class="qu_div"><label class="form-label"><?= $this->lang->line('quantity') ?></label>
                            <input type="text" name="quantity[]" value="<?= isset(set_value('quantity')[0]) ? set_value('quantity')[0] : '' ?>" class="form-control quantity" placeholder="<?= $this->lang->line('quantity') ?>" /></div></td>
                    <td class="num_width"><label class="form-label"><?= $this->lang->line('discount') ?></label>
                        <input type="text" name="discount[]" value="<?= isset(set_value('discount')[0]) ? set_value('discount')[0] : '' ?>" class="form-control discount" placeholder="<?= $this->lang->line('discount') ?>" /></td>
                    <td class="total_price_container num_width"><label class="form-label"><?= $this->lang->line('total_price') ?></label>
                        <span class="form-control total_price" ></span></td>
                    <td class="datepicker_container num_width"><label class="form-label"><?= $this->lang->line('start-date') ?></label>
                        <input type="text" name="start_date[]" value="<?= isset(set_value('start_date')[0]) ? set_value('start_date')[0] : '' ?>" class="form-control datepicker" placeholder="<?= $this->lang->line('start-date') ?>" /></td>
                    <td class="datepicker_container num_width"><label class="form-label"><?= $this->lang->line('end-date') ?></label>
                        <input type="text" name="end_date[]" value="<?= isset(set_value('end_date')[0]) ? set_value('end_date')[0] : '' ?>" class="form-control datepicker" placeholder="<?= $this->lang->line('end-date') ?>" /></td>
                    <td class="comment_width"><label class="form-label"><?= $this->lang->line('comment') ?></label>
                        <textarea rows="1" name="comment[]" class="form-control" placeholder="<?= $this->lang->line('comment') ?>" ><?= isset(set_value('comment')[0]) ? set_value('comment')[0] : '' ?></textarea></td>
                    <td>
                        &nbsp;&nbsp;
                        <i class="fas fa-calendar-plus text-primary fa-2x additions_btn" title="<?= $this->lang->line('additions') ?>" style="cursor: pointer"></i>
                        &nbsp;&nbsp;
                        <i class="fas fa-window-close text-danger fa-2x delete_item" title="Delete Item" style="cursor: pointer"></i>
                        <div class="additions">

                        </div>
                    </td>
                </tr>
            </table>
            <br/>
            <br/>
            <div>
                <i class="fa fa-plus text-primary fa-3x add_icon"></i>
            </div>
            <div class="inv_total_container row">
                <div class="col-md-8"></div>
                <div class="col-md-2">
                    <hr style="margin-top: 0px"/>
                    <label class="form-label"><?= $this->lang->line('total_price') ?></label>
                    <span class="form-control inv_total"></span>
                </div>
                <div class="col-md-2"></div>
            </div>
            <br/>
            <br/>
            <?php if ($call_center) { ?>
                <div class="form-group row">
                    <label for="example-search-input" class="col-3 col-form-label"><?php echo $this->lang->line('the_type') ?></label>
                    <div class="col-9">
                        <div class="radio">
                            <input type="radio" name="type"  value="0"  <?= $this->input->post() && set_value('type') === 0 ? 'checked' : '' ?> <?= !$this->input->post() ? 'checked' : '' ?> class="type">
                            <label>   &nbsp;&nbsp;<?php echo $this->lang->line('order') ?>
                            </label>
                        </div>
                        <div class="radio">
                            <input type="radio" name="type"  value="1" <?= $this->input->post() && set_value('type') === 1 ? 'checked' : '' ?> class="type">
                            <label>   &nbsp;&nbsp;<?php echo $this->lang->line('reservation') ?>
                            </label>
                        </div>
                    </div>
                </div>
            <?php } ?>

            <div id="order_data">
                <?php if ($call_center) { ?>
                    <div class="form-group row">
                        <label for="example-search-input" class="col-3 col-form-label"><?php echo $this->lang->line('delivery_type') ?></label>
                        <div class="col-9">
                            <select name="delivery_type" class="form-control" id="delivery_type">
                                <option value="1" <?= $this->input->post() && set_value('delivery_type') === 1 ? 'selected' : '' ?>><?php echo $this->lang->line('home_delivery') ?></option>
                                <option value="0" <?= $this->input->post() && set_value('delivery_type') === 0 ? 'selected' : '' ?>><?php echo $this->lang->line('direct_recieve') ?></option>
                            </select>
                        </div>
                    </div>
                <?php } ?>

                <div class="form-group row">
                    <label for="example-search-input" class="col-3 col-form-label"><?php echo $this->lang->line('discount_type') ?></label>
                    <div class="col-9">
                        <select name="discount_type" class="form-control" id="discount_type">
                            <option value="0" <?= set_value('discount_type') == 0 ? 'selected' : '' ?> ><?php echo $this->lang->line('amount') ?></option>
                            <option value="1" <?= set_value('discount_type') == 1 ? 'selected' : '' ?> ><?php echo $this->lang->line('percentage') ?></option>
                        </select>
                    </div>
                </div>
                <?php if ($call_center) { ?>
                    <input type="hidden" name="paid" value="2" />
                <?php } else { ?>
                    <div class="form-group row">
                        <label for="example-search-input" class="col-3 col-form-label"><?php echo $this->lang->line('payment') ?> <?php echo $this->lang->line('status') ?></label>
                        <div class="col-9">
                            <select name="paid" class="form-control">
                                <option value="1" <?= set_value('paid') == 1 ? 'selected' : '' ?> ><?php echo $this->lang->line('payment-is-made') ?></option>
                                <option value="2" <?= set_value('paid') == 2 ? 'selected' : '' ?> ><?php echo $this->lang->line('not-paid') ?></option>
                            </select>
                            <!--                            <div class="radio">
                                                            <input type="radio" name="paid"  value="1"  checked="" required>
                                                            <label>   <?php //echo $this->lang->line('payment-is-made')                                                                                                                                                                                ?>
                                                            </label>
                                                        </div>
                                                        <div class="radio">
                                                            <input type="radio" name="paid"  value="2">
                                                            <label>   <?php //echo $this->lang->line('not-paid')                                                                                                                                                                                ?>
                                                            </label>
                                                        </div>-->
                            <!--                    <div class="radio">
                                                    <input type="radio" name="paid"  value="3">
                                                    <label>  <?php //echo $this->lang->line('complimentary')                                                                                                                                                                                             ?> 
                                                    </label>
                                                </div>
                                                <div class="radio">
                                                    <input type="radio" name="paid"  value="4">
                                                    <label> <?php //echo $this->lang->line('retriever')                                                                                                                                                                                             ?>
                                                    </label>
                                                </div> -->
                        </div>
                    </div>
                <?php } ?>

                <div class="form-group row">
                    <label class="col-3 col-form-label"><?= $this->lang->line('payment_method') ?></label>
                    <?php $payment_method = array('cash', 'Knit', 'Visa/Master', 'link') ?>
                    <div class="col-9">
                        <select name="payment_method" class="form-control">
                            <?php foreach ($payment_method as $key => $value) { ?>
                                <option value="<?= $key ?>" <?= set_value('payment_method') == $key ? 'selected' : '' ?>><?= $this->lang->line($value) ? $this->lang->line($value) : $value ?></option>  
                            <?php } ?>
                        </select>
                    </div>
                </div>
                <?php if ($call_center) { ?>
                    <div class="form-group row">
                        <label class="col-3 col-form-label"><?= $this->lang->line('expected_delivery_time') ?></label>
                        <div class="col-9">
                            <input type="text" name="expected_delivery_time" class="form-control datetimepicker" value="<?= set_value('expected_delivery_time') ?>" />
                        </div>
                    </div>
                <?php } ?>

                <div class="form-group row">
                    <label for="example-search-input" class="col-3 col-form-label"><?php echo $this->lang->line('the-reason-for-the-discount') ?></label>
                    <div class="col-9">
                        <textarea class="form-control" rows="3" placeholder="<?php echo $this->lang->line('describe') ?>..." name="discount_why"><?= set_value('discount_why') ?></textarea>
                    </div>
                </div>
            </div>
            <div class="form-group row">
                <label for="example-search-input" class="col-3 col-form-label"><?php echo $this->lang->line('note') ?></label>
                <div class="col-9">
                    <textarea class="form-control" rows="3" placeholder="<?php echo $this->lang->line('describe') ?>.." name="note"><?= set_value('note') ?></textarea>
                </div>
            </div>


        </div>
        <div class="kt-portlet__foot">
            <div class="kt-form__actions">
                <div class="row">
                    <div class="col-10">
                        <button type="submit" class="btn btn-primary" name="submit" value="pl"><?php echo $this->lang->line('add') ?></button>
                        <?php if ($call_center) { ?>
                            <button type="submit" class="btn btn-success" name="submit" value="edit_status"><?php echo $this->lang->line('save_and_edit_order') ?></button>
                        <?php } ?>
                    </div>
                </div>
            </div>
        </div>
        </form>
    </div>

    <div class="modal fade" id="add_address" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel"><?= $this->lang->line('add_address') ?></h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <i aria-hidden="true" class="ki ki-close"></i>
                    </button>
                </div>

                <?php
                $lang = $this->session->userdata('language');
                ?>
                <form action="<?= base_url('orders/add_address') ?>" method="post" id="add_address_form" >
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-12">
                                <input type="hidden" name="user_id" id="address_user_id" />
                                <?php
                                foreach ($fields_arr as $key => $val) {
                                    if (in_array($key, $show_fields)) {
                                        if ($key != 'city' && $key != 'blocks' && $key != 'street' && $key != 'jadah' && $key != 'floor' &&
                                                $key != 'door_no' && $key != 'address_link' && $key != 'building_num') {
                                            continue;
                                        }
                                        ?>
                                        <div class="form-group row">
                                            <label for="example-email-input" class="col-3 col-form-label"> <?php echo $val ?> <?= in_array($key, $required_fields) ? '<i class="text-danger">*</i>' : '' ?></label>
                                            <div class="col-9">
                                                <?php
                                                if ($key == 'city') {
                                                    ?>
                                                    <select name="city" class="form-control select2_plug" data-search="true">
                                                        <option  value=""><?php echo $this->lang->line('select'); ?>
                                                            <?php foreach ($region as $key => $value) { ?>
                                                                <?php if ($lang == 'english') { ?><option value="<?php echo $value->english; ?>"><?php echo $value->english; ?></option> <?php } else { ?>
                                                                <option value="<?php echo $value->arabic; ?>"><?php echo $value->arabic; ?></option>
                                                                <?php
                                                            }
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <?php
                                        } else {
                                            ?>
                                            <input type="text" name="<?= $key ?>" id="<?= $key ?>" class="form-control" <?= in_array($key, $required_fields) ? 'required' : '' ?> />
                                        </div>
                                    </div>
                                    <?php
                                }
                                ?>
                                <?php
                            }
                        }
                        ?>
                    </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-light-primary font-weight-bold" data-dismiss="modal">Close</button>
            <a class="btn btn-primary font-weight-bold submit_add_address_form"><?= $this->lang->line('add') ?></a>
        </div> 
        </form>
    </div>
</div>
</div>


<div class="modal fade" id="additions_modal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel"><?= $this->lang->line('additions') ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <i aria-hidden="true" class="ki ki-close"></i>
                </button>
            </div>


<!--                <form action="<?= base_url('orders/add_address') ?>" method="post" id="add_address_form" >-->
            <div class="modal-body">
                <div id="modal_addition_error"></div>
                <div class="row">
                    <div class="col-md-12">
                        <input type="hidden" id="modal_product_id" />
                        <input type="hidden" id="modal_order" />
                        <div id="modal_inputs">

                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-light-primary font-weight-bold" data-dismiss="modal">Close</button>
                <a class="btn btn-primary font-weight-bold submit_add_addition" style="color: #fff"><?= $this->lang->line('add') ?></a>
            </div> 
            <!--</form>-->
        </div>
    </div>
</div>

<div class="modal fade" id="add_student" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel"><?= $this->lang->line('add') . ' ' . $this->lang->line('student') ?></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <i aria-hidden="true" class="ki ki-close"></i>
                </button>
            </div>
            <?php if ($this->session->flashdata('error')) : ?>
                <div class="form-group form-group-last">
                    <div class="alert alert-secondary" role="alert">
                        <div class="alert-icon"><i class="flaticon-warning kt-font-brand"></i></div>
                        <div class="alert-text">
                            <?= $this->session->flashdata('error'); ?>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
            <?php
            $lang = $this->session->userdata('language');
            ?>
            <form action="<?= base_url('orders/add_student/' . $call_center) ?>" method="post" id="add_student_form" >
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <?php
                            $fields_count = 0;
                            $addresses_count = 0;
                            foreach ($show_fields as $key => $val) {
                                if ($val == 'city' || $val == 'blocks' || $val == 'street' || $val == 'jadah' || $val == 'floor' ||
                                        $val == 'door_no' || $val == 'address_link' || $val == 'building_num') {
                                    $addresses_count++;
                                }
                            }
                            $half_fields = ceil((count($show_fields) - $addresses_count) / 2) - 1;
                            foreach ($fields_arr as $key => $val) {
                                //$key = array_search($fields_arr[$f], $fields_arr);
                                if (in_array($key, $show_fields)) {
                                    if ($key == 'city' || $key == 'blocks' || $key == 'street' || $key == 'jadah' || $key == 'floor' ||
                                            $key == 'door_no' || $key == 'address_link' || $key == 'building_num') {
                                        continue;
                                    }
                                    ?>
                                    <div class="form-group row">
                                        <label for="example-email-input" class="col-3 col-form-label"> <?php echo $val ?> <?= in_array($key, $required_fields) ? '<i class="text-danger">*</i>' : '' ?></label>
                                        <?php if ($key == 'phone') { ?>
                                            <div class="col-3">
                                                <?= phone_code_select('phone_code', 'select2_plug') ?>
                                            </div>
                                        <?php } ?>
                                        <div class="<?= $key == 'phone' ? 'col-6' : 'col-9' ?>">
                                            <?php
                                            if ($key == 'country') {
                                                $fields_count++;
                                                ?>
                                                <select name="country" class="form-control select2_plug" data-search="true">
                                                    <option  value=""><?php echo $this->lang->line('select'); ?></option>
                                                    <?php foreach ($nationality as $key => $value) { ?>
                                                        <?php if ($lang == 'english') { ?><option <?= set_value('country') == $value->english ? 'selected' : '' ?> value="<?php echo $value->english; ?>"><?php echo $value->english; ?></option> <?php } else { ?>
                                                            <option <?= set_value('country') == $value->arabic ? 'selected' : '' ?> value="<?php echo $value->arabic; ?>"><?php echo $value->arabic; ?></option>
                                                            <?php
                                                        }
                                                    }
                                                    ?>
                                                </select>
                                            </div>
                                        </div>
                                        <?php
                                        if ($fields_count == $half_fields) {
                                            echo '</div><div class="col-md-6">';
                                        }
                                    } else if ($key == 'sex') {
                                        $fields_count++;
                                        ?>
                                        <select name="sex" class="form-control select2_plug" data-search="true">
                                            <option value="male" <?= set_value('sex') == 'male' ? 'selected' : '' ?>><?php echo $this->lang->line('male'); ?></option>
                                            <option value="female" <?= set_value('sex') == 'female' ? 'selected' : '' ?>><?php echo $this->lang->line('female'); ?></option>
                                        </select>

                                    </div>
                                </div>
                                <?php
                                if ($fields_count == $half_fields) {
                                    echo '</div><div class="col-md-6">';
                                }
                            } else if ($key == 'note') {
                                $fields_count++;
                                ?>
                                <textarea name="note" class="form-control" value="<?= set_value('note') ?>" rows="3"></textarea>

                            </div>
                    </div>
                    <?php
                    if ($fields_count == $half_fields) {
                        echo '</div><div class="col-md-6">';
                    }
                } else {
                    $fields_count++;
                    ?>
                    <input type="text" name="<?= $key ?>" id="<?= $key ?>" value="<?= set_value($key) ?>" class="form-control" />
                </div>
            </div>
            <?php
            if ($fields_count == $half_fields) {
                echo '</div><div class="col-md-6">';
            }
        }
        ?>

        <?php
    }
}
?>
</div>
<div class="modal-footer" style="width: 100%">
    <button type="button" class="btn btn-light-primary font-weight-bold" data-dismiss="modal">Close</button>
    <button type="submit" class="btn btn-primary font-weight-bold"><?= $this->lang->line('add') ?></button>
</div> 
</div>
</div>


<?php $this->load->view('site/footer_2'); ?>
<script>
    $(".select2_plug").select2();
    $(".datepicker_container").hide();
    $(".quantity_container").hide();
    $(".total_price_container").hide();
    $(".product").select2();
<?php if ($this->session->flashdata('error')) : ?>
        $("#add_student").modal('show');
<?php endif; ?>
    $('.students').select2();
    function add_student() {
        document.getElementById("add_student_form").reset();
        $("#add_student").modal('show');
    }

    function update_total_price() {
        var total = 0;
        $('.total_price').each(function () {
            total += parseFloat($(this).text());
        });
        $('.price').each(function () {
            if ($(this).text() != '' && $.isNumeric($(this).text())) {
                if (!$(this).closest('tr').find('.total_price_container').is(":visible")) {
                    total += parseFloat($(this).text());
                }
            }
        });
        $(".inv_total").text(total);
    }
    $(".datepicker").datepicker({
        format: "yyyy-mm-dd",
        todayHighlight: true
    });
    $(".datetimepicker").datetimepicker({
        format: "yyyy-mm-dd H:i:s",
        todayHighlight: true
    });
    $('.type').change(function () {
        if ($('.type:checked').val() == 1) {
            $('#order_data').hide();
        } else {
            $('#order_data').show();
        }
    });
    last_row_deleted = 0;
    $(document).on("click", ".delete_item", function () {
        if ($('.produtcs_').length == 1) {
            $('#first').hide();
            $('#first').find('input').val('');
            $('#first').find('input').prop('disabled', 'disabled');
            $('#first').find('select').val('');
            $('#first').find('select').prop('disabled', 'disabled');
            $('#first').find('textarea').val('');
            $('#first').find('textarea').prop('disabled', 'disabled');
            last_row_deleted = 1;
        } else {
            $(this).closest('tr').remove();
        }
        $("#products_count").val(parseInt($("#products_count").val()) - 1);
    });
    $(".submit_add_address_form").click(function () {
        $.ajax({
            type: "POST",
            url: "<?php echo base_url() ?>Orders/add_address",
            data: $("#add_address_form").serialize(),
            //dataType: 'JSON',
            success: function () {
                $("#add_address").modal('hide');
                $(".students").change();
            }
        });
    });


    $(document).on("click", ".additions_btn", function () {
        var order = $(this).closest("tr").find(".product").index(".product");
        var product_id = $(this).closest("tr").find(".product").val();
        $.ajax({
            type: "POST",
            url: "<?php echo base_url() ?>Orders/get_product_additions",
            data: {'product_id': product_id},
            dataType: 'JSON',
            success: function (result) {
                $("#modal_addition_error").html('');
                $("#modal_product_id").val(product_id);
                $("#modal_order").val(order);
                var html = '';

                for (var i = 0; i < result.length; i++) {

                    var input_type = 'checkbox';
                    if (result[i].choice_type == 0) {
                        var input_type = 'radio';
                    }
                    var star = '';
                    if (result[i].required == 1) {
                        star = '*';
                    }
                    html += '<div class="form-group row">\n\
            <label for="example-text-input" class="col-3 col-form-label">' + result[i].qu + star + '</label>\n\
            <div class="col-9" style="margin-top:10px">';
                    for (var j = 0; j < result[i].options.length; j++) {
                        var checked = '';
                        if (typeof $('.addition_id[value="' + result[i].id + '"]').next('.choice').val() != "undefined") {
                            var choice_val = $('.addition_id[value="' + result[i].id + '"]').next('.choice').val().split(',');
                            if ($.inArray(result[i].options[j][1], choice_val) !== -1) {
                                checked = 'checked';
                            }
                        }
                        html += '<input ' + checked + ' type="' + input_type + '" data-addition_id="' + result[i].id + '" data-price="' + result[i].options[j][2] + '" data-required="' + result[i].required + '" name="modal_add_' + result[i].id + '[]" value="' + result[i].options[j][1] + '" />&nbsp;&nbsp;<label>' + result[i].options[j][0] + '</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                    }

                    html += '</div></div>';
                }
                $("#modal_inputs").html(html);
                $("#additions_modal").modal('show');
            }
        });
    });

    $(".submit_add_addition").click(function () {
        var order = $("#modal_order").val();
        $(".additions:eq(" + order + ")").html('');
        $(".product_additions:eq(" + order + ")").html('');
        $("#modal_addition_error").html('');
        var error = 0;
        var product_price = parseFloat($("tr:eq(" + order + ")").find(".product_price").val());
        var product_id = $("#modal_product_id").val();
        $("#modal_inputs .col-9").each(function () {
            var input_name = $(this).children('input:first').attr('name');
            //var choice = $('input[name="' + input_name + '"]:checked').val();
            var arr = $('input[name="' + input_name + '"]:checked').map(function () {
                return this.value; // $(this).val()
            }).get();
            var choice = arr.join(',');
            var required = $('input[name="' + input_name + '"]:first').data('required');
            if (required == 1 && $('input[name="' + input_name + '"]:checked').length == 0) {
                error = 1;
                $("#modal_addition_error").append('<div class="alert alert-danger alert-dismissible">\n\
            <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>\n\
            <h4><i class="icon fa-warning"></i> ERROR!</h4><?= $this->lang->line('have_to_choose') ?> ' + $(this).parent('.form-group').find(".col-form-label").html() + '\n\
            </div>');
            } else {
                var addition_id = $('input[name="' + input_name + '"]:first').data('addition_id');

                var choice_txt = $('input[name="' + input_name + '"]:checked').map(function () {
                    return $(this).next('label:first').html() + ' -- ' + $(this).data('price'); // $(this).val()
                }).get();
                // var choice_txt = $('input[name="' + input_name + '"]:checked').next('label:first').html();
                var price = 0;
                $('input[name="' + input_name + '"]:checked').each(function () {
                    price += parseFloat($(this).data('price')); // $(this).val()
                });
                // var price = $('input[name="' + input_name + '"]:checked').data('price');

                if ($('input[name="' + input_name + '"]:checked').length > 0) {
                    $(".additions:eq(" + order + ")").append('<input type="hidden" name="addition_id[' + product_id + '][]" value="' + addition_id + '" class="addition_id" />\n\
                    <input type="hidden" name="choice[' + product_id + '][]" class="choice" value="' + choice + '" />');

                    $(".product_additions:eq(" + order + ")").append(choice_txt + '<br/>');

                    product_price += price;
<?php if (get_ap('edit_price_in_inv', $this->operator_id)) { ?>
                        $("tr:eq(" + order + ")").find(".price").val(product_price);
                        $("tr:eq(" + order + ")").find(".price").change();
<?php } else { ?>
                        $("tr:eq(" + order + ")").find(".price").text(product_price);
                        $("tr:eq(" + order + ")").find(".price_hidden").val(product_price);
                        $("tr:eq(" + order + ")").find(".price").change();
<?php } ?>
                }

            }
        });
        if (error == 0) {
            $("#additions_modal").modal('hide');
        }
        var text = $(".product_additions:eq(" + order + ")").html();
        $(".additions:eq(" + order + ")").append('<input type="hidden" name="addition_txt[' + product_id + ']" value="' + text + '" />');
    });

    $(document).on("change", ".product", function (e) {
        console.log(e);
        var ele = $(this);
        $.ajax({
            type: "POST",
            url: "<?php echo base_url() ?>Orders/get_product_price",
            data: {'product_id': $(this).val()},
            dataType: 'JSON',
            success: function (price) {
                if (!price) {
                    ele.closest("tr").find(".price").val(0);
                    return;
                }
                if (ele.closest("tr").find('td:first').find(".post_data").length == 0) {
                    ele.closest("tr").find(".additions").html('');
                    ele.closest("tr").find(".product_additions").html('');
                } else {
                    ele.closest("tr").find('td:first').find(".post_data").remove();
                }

                ele.closest("tr").find(".product_price").val(0);
                if (price.type == 2) {
                    ele.closest("tr").find(".datepicker_container").show();
                    ele.closest("tr").find(".quantity_container").show();
                    ele.closest("tr").find(".qu_div").hide();
                    ele.closest("tr").find(".total_price_container").hide();
                } else {
                    ele.closest("tr").find(".datepicker_container").hide();
                    ele.closest("tr").find(".quantity_container").show();
                    ele.closest("tr").find(".qu_div").show();
                    ele.closest("tr").find(".total_price_container").show();
                }
<?php if (get_ap('edit_price_in_inv', $this->operator_id)) { ?>
                    ele.closest("tr").find(".price").val(parseFloat(price.valuess));
<?php } else { ?>
                    ele.closest("tr").find(".price").text(parseFloat(price.valuess));
                    ele.closest("tr").find(".price_hidden").val(parseFloat(price.valuess));
<?php } ?>
                ele.closest("tr").find(".product_price").val(parseFloat(price.valuess));
                ele.closest("tr").find(".quantity").change();


            }
        });
    });
    //post_inputs=[];
    $(".add_icon").click(function () {
        if (last_row_deleted == 1) {
            $('#first').show();
            $('#first').find('input').removeAttr('disabled');
            $('#first').find('select').removeAttr('disabled');
            $('#first').find('textarea').removeAttr('disabled', 'disabled');
            last_row_deleted = 0;
        } else {
            var count = parseInt($("#products_count").val());
            var product = '';
            $(".product").select2('destroy');
            $("#invoice_items").append('<tr class="produtcs_">' + $("#first").html() + '</tr>');
            $("#invoice_items").find('tr:last-child').find(".datepicker_container").hide();
            $("#invoice_items").find('tr:last-child').find(".form-label").hide();
            $("#invoice_items").find('tr:last-child').find(".price").text('');

            if ($("#invoice_items").find('tr:last-child').find(".post_data").length == 0) {
                $("#invoice_items").find('tr:last-child').find(".product_additions").html('');
                $("#invoice_items").find('tr:last-child').find(".additions").html('');
            }

            //        $("#invoice_items").find('tr:last-child').find(".quantity_container").hide();
            //        $("#invoice_items").find('tr:last-child').find(".total_price_container").hide();

            $(".datepicker").datepicker({
                format: "yyyy-mm-dd",
                todayHighlight: true
            });
            if (typeof post_inputs !== "undefined") {
                product = post_inputs['id_producer'][count];
                $(".price:last").val(post_inputs['amount'][count]);
                $(".discount:last").val(post_inputs['discount'][count]);
                $(".quantity:last").val(post_inputs['quantity'][count]);
                $("input[name='comment[]']:last").val(post_inputs['comment'][count]);
                $("input[name='start_date[]']:last").val(post_inputs['start_date'][count]);
                $("input[name='end_date[]']:last").val(post_inputs['end_date'][count]);
            }
            if (product != '') {
                $(".product:last").val(product);
            }
            $(".product").select2();
        }
        $("#products_count").val(parseInt($("#products_count").val()) + 1);
    });
<?php if ($this->input->post()) { ?>
        post_inputs = '<?= json_encode($this->input->post()) ?>';
        post_inputs = JSON.parse(post_inputs);


    <?php for ($i = 0; $i < $this->input->post('products_count'); $i++) { ?>
        <?php if ($i != 0) {
            ?>
                $(".add_icon").click();
        <?php } ?>
            $(".product:last").closest("td").append('<span class="post_data"></span>');
            $(".product:last").change();
        <?php if ($this->input->post() && is_array($this->input->post('addition_id[' . $this->input->post('id_producer')[$i] . ']'))) { ?>
                $(".product:last").closest("tr").find(".additions").html('');
            <?php for ($j = 0; $j < count($this->input->post('addition_id[' . $this->input->post('id_producer')[$i] . ']')); $j++) {
                ?>
                    $(".product:last").closest("tr").find(".additions").append('<input type="hidden" name="addition_id[<?= $this->input->post('id_producer')[$i] ?>][]" value="<?= $this->input->post('addition_id[' . $this->input->post('id_producer')[$i] . '][' . $j . ']') ?>" />\n\
                                                                                                                                                                                        <input type="hidden" name="choice[<?= $this->input->post('id_producer')[$i] ?>][]" value="<?= $this->input->post('choice[' . $this->input->post('id_producer')[$i] . '][' . $j . ']') ?>" />');
            <?php }
            ?>
                $(".product:last").closest("tr").find(".additions").append('<input type="hidden" name="addition_txt[<?= $this->input->post('id_producer')[$i] ?>]" value="<?= $this->input->post('addition_txt[' . $this->input->post('id_producer')[$i] . ']') ?>" />');
                $(".product:last").closest("tr").find(".product_additions").html('<?= $this->input->post('addition_txt[' . $this->input->post('id_producer')[$i] . ']') ?>');

        <?php }
        ?>
        <?php
    }
}
?>



    $(document).on("change", ".quantity", function () {
<?php if (get_ap('edit_price_in_inv', $this->operator_id)) { ?>
            var price = $(this).closest('tr').find('.price').val();
<?php } else { ?>
            var price = $(this).closest('tr').find('.price').text();
<?php } ?>
        var qu = $(this).val();
        var discount = $(this).closest('tr').find('.discount').val();
        if ($("#discount_type").val() == 1) {
            discount = (qu * price * discount) / 100;
        }
        $(this).closest('tr').find('.total_price').text(((qu * price) - discount).toFixed(2));
        update_total_price();
    });

    $(document).on("change", ".price", function () {
        var qu = $(this).closest('tr').find('.quantity').val();
<?php if (get_ap('edit_price_in_inv', $this->operator_id)) { ?>
            var price = $(this).closest('tr').find('.price').val();
<?php } else { ?>
            var price = $(this).closest('tr').find('.price').text();
<?php } ?>
        var discount = $(this).closest('tr').find('.discount').val();
        if ($("#discount_type").val() == 1) {
            discount = (qu * price * discount) / 100;
        }
        $(this).closest('tr').find('.total_price').text(((qu * price) - discount).toFixed(2));
        update_total_price();
    });

    $(document).on("change", ".discount", function () {
        var qu = $(this).closest('tr').find('.quantity').val();
<?php if (get_ap('edit_price_in_inv', $this->operator_id)) { ?>
            var price = $(this).closest('tr').find('.price').val();
<?php } else { ?>
            var price = $(this).closest('tr').find('.price').text();
<?php } ?>
        var discount = parseFloat($(this).val());
        if ($("#discount_type").val() == 1) {
            discount = (qu * price * discount) / 100;
        }
        $(this).closest('tr').find('.total_price').text(((qu * price) - discount).toFixed(2));
        update_total_price();
    });

    $("#discount_type").change(function () {
        $('.total_price').each(function () {
            var qu = $(this).closest('tr').find('.quantity').val();
<?php if (get_ap('edit_price_in_inv', $this->operator_id)) { ?>
                var price = $(this).closest('tr').find('.price').val();
<?php } else { ?>
                var price = $(this).closest('tr').find('.price').text();
<?php } ?>
            var discount = $(this).closest('tr').find('.discount').val();
            if ($("#discount_type").val() == 1) {
                discount = (qu * price * discount) / 100;
            }
            $(this).closest('tr').find('.total_price').text(((qu * price) - discount).toFixed(2));
            update_total_price();
        });
    });

    $(document).on("click", ".add_address_btn", function () {
        $("#address_user_id").val($(this).attr('data-user-id'));
        $("#add_address").modal('show');
    });

    $(".students").change(function () {
        var student_ids = [];
        $('.students > option:selected').each(function () {
            student_ids.push($(this).data('id'));
        });

        $.ajax({
            type: "POST",
            url: "<?php echo base_url() ?>Orders/get_user_addresses",
            data: {'users': student_ids},
            dataType: 'JSON',
            success: function (data) {
                $("#addresses").html('');
                var address;
                for (var i = 0; i < data.length; i++) {
                    address = '<h3>' + data[i].username + '</h3>';
                    for (var j = 0; j < data[i].addresses.length; j++) {
                        address += '<input class="address_option" type="radio" name="address_' + data[i].id + '" value="' + data[i].addresses[j].id + '" />';
<?php if (in_array('city', $show_fields)) { ?>
                            if (data[i].addresses[j].region != '') {
                                address += "<?= $this->lang->line('region') . ': ' ?>" + data[i].addresses[j].region + ', ';
                            }
<?php } ?>
<?php if (in_array('blocks', $show_fields)) { ?>
                            if (data[i].addresses[j].blocks != '') {
                                address += "<?= $this->lang->line('block_address') . ': ' ?>" + data[i].addresses[j].blocks + ', ';
                            }
<?php } ?>
<?php if (in_array('street', $show_fields)) { ?>
                            if (data[i].addresses[j].street != '') {
                                address += "<?= $this->lang->line('street') . ': ' ?>" + data[i].addresses[j].street + ', ';
                            }
<?php } ?>
<?php if (in_array('jadah', $show_fields)) { ?>
                            if (data[i].addresses[j].jadah != '') {
                                address += "<?= $this->lang->line('jadah') . ': ' ?>" + data[i].addresses[j].jadah + ', ';
                            }
<?php } ?>
<?php if (in_array('building_num', $show_fields)) { ?>
                            if (data[i].addresses[j].building_num != '') {
                                address += "<?= $this->lang->line('building_num') . ': ' ?>" + data[i].addresses[j].building_num + ', ';
                            }
<?php } ?>
<?php if (in_array('floor', $show_fields)) { ?>
                            if (data[i].addresses[j].floor != '') {
                                address += "<?= $this->lang->line('floor') . ': ' ?>" + data[i].addresses[j].floor + ', ';
                            }
<?php } ?>
<?php if (in_array('door_no', $show_fields)) { ?>
                            if (data[i].addresses[j].door_no != '') {
                                address += "<?= $this->lang->line('door-number') . ': ' ?>" + data[i].addresses[j].door_no;
                            }
<?php } ?>
                        address += '<br/>';
                    }
                    if (data[i].addresses.length == 0) {
                        address += '<?= $this->lang->line('no_addresses') ?> <br/>';
                    }
                    address += '<br/><a class="btn btn-outline-primary add_address_btn" data-user-id="' + data[i].id + '"><?= $this->lang->line('add_another_address') ?></a><hr/>';
                    $("#addresses").append(address);
                }
            }
        });
    });
<?php if ($this->session->flashdata('student_id') || $this->input->post()) { ?>
        $(".students").change();
<?php } ?>
</script>
