<?php 
$nonce = substr(str_shuffle(MD5(microtime())), 0, 10);
$ticketing_fields_hide = smc_session()['default_setting']['maintenance_fields_to_hide'] != '' ? explode(",", smc_session()['default_setting']['maintenance_fields_to_hide']) : [];
// echo "<pre>";die(print_r($ticketing_fields_hide));
 
//print_r($ticketing_status);

//$t=$edit_arr['main']['ticketing_reply_id'];
//echo "<script>alert('$t');</script>";
?>
<link href="<?php echo LIBS_URL; ?>summernote/summernote.css" rel="stylesheet">
<script src="<?php echo LIBS_URL; ?>summernote/summernote.min.js"></script>
<style>
    #product_details_main_div{
        background-color: aliceblue;
        padding-top: 10px;
        padding-bottom: 10px;
        padding-right: 15px;
        padding-left: 15px;
        margin-left: -5px;
        margin-right: -5px;
    }
    .fa{
        cursor:pointer;
    }
    .AddButtons .fa-minus{
        color:#ed9421;
    }
    .AddButtons .fa-plus{
        color:#4c0870; 
    }
    #ticketing_reply_html{
        padding-left: 5px;
        padding-top: 5px;
        border: 1px Solid #e6e6e6;
    }
</style>
<div class="container-fluid container-fixed-lg bg-white">
    <div class="panel panel-transparent">
        <div class="panel-heading">
            <div class="panel-title"><?php print $title; ?></div>
        </div>
        <div class="panel-body">
            <div class="row"><?php echo Forms::AlertDiv('ticketing_alert'); ?></div>
            <form method="POST" id="ticketing_form" onsubmit="return false">
                <input type="hidden" id="ticketing_id" name="ticketing_id" value="<?php echo $ticketing_id; ?>"/>
                <input type="hidden" id="ticketing_reply_id" name="ticketing_reply_id" value="<?php echo $ticketing_id == 0 ? '' : $edit_arr['main']['maintenance_reply_id']; ?>"/>
                <div class="row form-group">
                    <div class="col-md-3">
                        <label><?php echo CommonLanguage::getMessage('customer'); ?>
                            <span class="red-star">*</span>
                            <?php if($permissions->hasPermission('viewCustomer')){?>
                            <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/CustomerList?is_pop=1&new=1" style="color:#4c0870;cursor:pointer"></span>
                            <?php }?>
                        </label>
                        <input type="hidden" name="customer_id" id="customer_id" class="full-width" value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['customer_id'];?>" data-select-name="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['Customer_Name'];?>" required/>
                    </div> 
                    <div class="col-md-3">
                        <label><?php echo CommonLanguage::getMessage('maintenance_type'); ?>
                            <span class="red-star">*</span>
                            <?php if($permissions->hasPermission('maintenance_type_list')){?>
                            <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Ticketing/maintenance_type_list?is_pop=1&new=1" style="color:#4c0870;cursor:pointer"></span>
                            <?php }?>
                        </label>
                        <input type="hidden" name="ticketing_type_id" id="ticketing_type_id" class="full-width"  value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['maintenance_type_id'];?>" data-select-name="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['maintenance_type_name'];?>" required/>
                    </div> 
                    <div class="col-md-3">
                        <label><?php echo CommonLanguage::getMessage('Date'); ?>
                            <span class="red-star">*</span>
                        </label>
                        <input type="text" name="ticketing_date" id="ticketing_date" class="form-control" value="<?php echo $ticketing_id ==0 ? date('Y-m-d'): $edit_arr['main']['maintenance_date'];?>" required/>
                    </div>
                    <div class="col-md-3">
                        <input type="hidden" name="old_ticketing_status_id" id="old_ticketing_status_id" value="<?php echo $ticketing_id ==0 ? '': $edit_arr['main']['maintenance_status_id'];?>"/>
                        <label><?php echo CommonLanguage::getMessage('maintenance_status'); ?>
                            <span class="red-star">*</span>
                        </label>
                        <select id="ticketing_status_id" class="full-width" data-init-plugin="select2" <?php  echo $permissions->hasPermission('change_maintenance_status') ? '' : 'disabled';?> >
                            <?php  foreach($ticketing_status as $val){?>
                            <option value="<?php echo $val['ticketing_status_id'];?>" <?php echo ($ticketing_id != 0 &&  $edit_arr['main']['maintenance_status_id']== $val['ticketing_status_id'])  ? 'selected' : '';?> ><?php echo $val['ticketing_status_name'];?></option>
                            <?php }?>
                        </select>
                    </div> 


                   
                    
                </div>
                
                <div class="row form-group">
                    <div class="col-md-3">
                        <label><?php echo CommonLanguage::getMessage('serial_number'); ?>
                            <span class="red-star">*</span>
                        </label>
                        <input type="text" name="customer_additional_phone" id="customer_additional_phone" class="form-control" value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['serial_number'];?>"   />
                    </div> 

                   <!-- <div class="col-md-3">
                        <label><?php echo CommonLanguage::getMessage('schedule_date'); ?>
                            <span class="red-star">*</span>
                        </label>
                        <input type="text" name="ticketing_schedule_date" id="ticketing_schedule_date" class="form-control" value="<?php echo $ticketing_id ==0 ? date('Y-m-d H:i'): $edit_arr['main']['maintenance_schedule_date'];?>" required/>
                    </div>-->
                    <div class="col-md-3 <?php echo in_array(8, $ticketing_fields_hide)? 'hidden':''; ?>">
                        <label><?php echo CommonLanguage::getMessage('color'); ?>
                        </label>
                        <input  type="text" name="phone_color" id="phone_color" class="form-control" value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['color'];?>"  />
                    </div>
                     

                    <div class="col-md-3 <?php echo in_array(1, $ticketing_fields_hide)? 'hidden':''; ?>">
                        <label><?php echo CommonLanguage::getMessage('phone_name'); ?>
                            
                        </label>
                        <input type="text" name="phone_name" id="phone_name" class="form-control" value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['phone_name'];?>"  />
                    </div>

                    <div class="col-md-3 hidden">
                        <label><?php echo CommonLanguage::getMessage('voice_path'); ?>
                        </label>
                        <input type="text" name="nonce_file" id="nonce_file" class="form-control" value="<?php  echo $ticketing_id  == 0 ? '' :  $edit_arr['main']['nonce'];?>"  />
                    </div>
                    <div class="col-md-3 ">
                        <label><?php echo CommonLanguage::getMessage('Employee'); ?>
                        <span class="red-star">*</span>

                        </label>
                        <input class="Employee_ID full-width" id="Employee_ID" name="Employee_ID" type="hidden" required  />
                    </div>
                    
                    </div>

                    <div class="row form-group">
                    <div class="col-md-3  <?php echo in_array(2, $ticketing_fields_hide)? 'hidden':''; ?> ">
                        <label><?php echo CommonLanguage::getMessage('phone_brand'); ?>
                        </label>
                        <input type="text" name="phone_brand" id="phone_brand" class="form-control" value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['phone_brand'];?>"  />
                    </div>
                    <div class="col-md-3  <?php echo in_array(0, $ticketing_fields_hide)? 'hidden':''; ?>">
                        <label><?php echo CommonLanguage::getMessage('IMEI'); ?>
                        </label>
                        <input  type="text" name="ime" id="ime" class="form-control" value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['ime'];?>"  />
                    </div>
                    <div class="col-md-3  <?php echo in_array(5, $ticketing_fields_hide)? 'hidden':''; ?>">
                        <label><?php echo CommonLanguage::getMessage('invoice_number'); ?>
                        </label>
                        <input  type="text" name="invoice_number" id="invoice_number" class="form-control" value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['invoice_number'];?>"  />
                    </div>
                    <div class="col-md-3  <?php echo in_array(7, $ticketing_fields_hide)? 'hidden':''; ?>">
                        <label><?php echo CommonLanguage::getMessage('password'); ?>
                        </label>
                        <input  type="text" name="phone_password" id="phone_password" class="form-control" value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['password'];?>"  />
                    </div>

                    

                </div>
                <div class="row form-group" >
                    <div class="col-md-3  <?php echo in_array(8, $ticketing_fields_hide)? 'hidden':''; ?>">
                        <label><?php echo CommonLanguage::getMessage('exchange_rate'); ?>
                        </label>
                        <input  type="text" name="exchange_rate" id="exchange_rate" class="form-control" value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['exchange_rate'];?>"  />
                    </div>

                    <div class="col-md-3">
                        <label><?php echo CommonLanguage::getMessage('color'); ?>
                            <?php if ($permissions->hasPermission('GeneralSetting')) { ?>
                                <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/GeneralSetting?is_pop=1&new=1" style="color:#4c0870;cursor:pointer"></span>
                            <?php } ?>
                        </label>
                        <input type="hidden" name="color_id" id="color_id" class="full-width" value="<?php echo $ticketing_id  == 0 ? '' :  $edit_arr['main']['color_id']; ?>" data-select-name="<?php echo $ticketing_id  == 0 ? '' :  $edit_arr['main']['color_name']; ?>" />
                    </div>
                    <div class="col-md-3">
                        <label><?php echo CommonLanguage::getMessage('type'); ?>
                            <?php if ($permissions->hasPermission('view_brand')) { ?>
                                <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Inventory/viewBrand?is_pop=1&new=1" style="color:#4c0870;cursor:pointer"></span>
                            <?php } ?>
                        </label>
                        <input type="hidden" name="type_id" id="type_id" class="full-width" value="<?php echo $ticketing_id  == 0 ? '' :  $edit_arr['main']['type_id']; ?>" data-select-name="<?php echo $ticketing_id  == 0 ? '' :  $edit_arr['main']['type_name']; ?>" />
                    </div>
                    <div class="col-md-3">
                        <label><?php echo CommonLanguage::getMessage('other_note'); ?>
                        </label>
                        <textarea name="other_note" id="other_note" class="full-width" value="<?php echo $ticketing_id  == 0 ? '' :  $edit_arr['main']['other_note']; ?>"><?php echo $ticketing_id  == 0 ? '' :  $edit_arr['main']['other_note']; ?></textarea>
                    </div>

                </div>
                <div class="row form-group" >
                    <div class="col-md-12 m-t-10 summernote-wrapper">
                        <label><?php echo CommonLanguage::getMessage('maintenance_note'); ?>
                        <span class="red-star">*</span>

                        </label>
                         <div id="ticketing_reply_description" class="ticketing_reply_description"><?php  echo  $ticketing_id  ==0 ? '' : $edit_arr['main']['maintenance_note'];?></div>
                     </div>
                </div>
                <div class="row m-t-10 form-group">                  
                    <div class="col-md-6 hidden">                   
                        <input type="file" id="attachment_url" class="form-control" name="attachment_url[]" multiple onchange="ValidateForNewAttachment(this,['.jpg', '.gif', '.jpeg', '.png', '.pdf', '.txt', '.csv',  '.zip', '.log', '.docx'])">
                        <h5 class="semi-bold">Allowed File Extensions: .jpg, .gif, .jpeg, .png, .pdf, .txt, .csv,  .zip, .log, .docx</h5>
                        <div class="display-flex reply_attachment_div">
                            <?php
                            if ($ticketing_id !=0 && is_dir(dirBase . "uploads/ticketing/" . $ticketing_id . "/" . $edit_arr['main']['maintenance_reply_id'])) {
                                $dir = scandir(dirBase . "uploads/ticketing/" . $ticketing_id . "/" . $edit_arr['main']['maintenance_reply_id']);
                                foreach ($dir as $file_name) {
                                    if (substr($file_name, 0, 1) != '..' && substr($file_name, 0, 1) != '.' && $file_name) {
                                        $path_info = dirBase . "uploads/ticketing/" . $ticketing_id . "/" . $edit_arr['main']['maintenance_reply_id'] . "/" . $file_name;
                                        $extension = pathinfo($path_info)['extension'];
                            ?>
                            <div class=" main_attachment_row display-flex m-r-10"  data-attachment-name="<?php echo $file_name; ?>">
                                <?php if (in_array($extension, ['png', 'gif', 'jpeg', 'png', 'jpg'])) { ?>
                                <img class="image_popup" popup-src="<?php echo SITE_LINK . 'uploads/ticketing/' . $ticketing_id . '/' . $edit_arr['main']['maintenance_reply_id'] . '/' . $file_name; ?>" src="<?php echo SITE_LINK . 'uploads/ticketing/' . $ticketing_id . '/' . $edit_arr['main']['maintenance_reply_id'] . '/' . $file_name; ?>" style="max-width:50px;max-height:50px;cursor:pointer;">
                                <?php } else { ?>
                                <a target="_blank" href="<?php echo SITE_LINK . 'uploads/ticketing/' . $ticketing_id . '/' . $edit_arr['main']['maintenance_reply_id'] . '/' . $file_name; ?>"><?php echo $extension; ?></a>
                                <?php } ?>
                            </div>
                            <?php
                                    }
                                }
                            }
                            ?>
                        </div>
                    </div>
                    <div class="col-md-6  <?php echo in_array(6, $ticketing_fields_hide)? 'hidden':''; ?>">                  
                    <i class="fa fa-microphone" aria-hidden="true"></i> 
                    <input type="button" id="record" class="btn" value="click and hold to record" />
        <script type="text/javascript">
            window.nonce = "<?php echo $nonce; ?>"
            window.is_record = 'false';
            // courtesy https://medium.com/@bryanjenningz/how-to-record-and-play-audio-in-javascript-faa1b2b3e49b
            const recordAudio = () => {
              return new Promise(async resolve => {
                const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                const mediaRecorder = new MediaRecorder(stream);
                const audioChunks = [];

                mediaRecorder.addEventListener("dataavailable", event => {
                  audioChunks.push(event.data);
                });

                const start = () => mediaRecorder.start();

                const stop = () =>
                  new Promise(resolve => {
                    mediaRecorder.addEventListener("stop", () => {
                      const audioBlob = new Blob(audioChunks);
                      const audioUrl = URL.createObjectURL(audioBlob);
                      const audio = new Audio(audioUrl);
                      const play = () => audio.play();
                      resolve({ audioBlob, audioUrl, play });
                    });

                    mediaRecorder.stop();
                  });

                resolve({ start, stop });
              });
            }

            /* simple timeout */
            const sleep = time => new Promise(resolve => setTimeout(resolve, time));

            /* init */
            (async () => {
                const btn = document.querySelector("#record");
                const recorder = await recordAudio();
                let audio; // filled in end cb
                var count = 0;
                const recStart = e => {
                    if(count == 0){
                        recorder.start();
                        btn.initialValue = btn.value;
                        btn.value = "recording...";
                        count =1;
                    }
                }
                const recEnd = async e => {

                    if(count == 1){
                        btn.value = btn.initialValue;
                        console.log(btn.initialValue);
                        audio = await recorder.stop();
                        // audio.play();
                        uploadAudio(audio.audioBlob);
                        count = 2;
                    }
                    if(count == 2){
                        btn.disabled = true;
                        count =3;
                    }

                }

                const uploadAudio = a => {
                    if (a.size > (10 * Math.pow(1024, 2))) {
                        document.body.innerHTML += "Too big; could not upload";
                        return;
                    }
                    const f = new FormData();
                    window.is_record = 'true';
                    f.append("nonce", window.nonce);
                    f.append("payload", a);

                    fetch("TicketingAjax/save_audio", {
                        method: "POST",
                        body: f
                    })
                    .then((response) => {
                        console.log(response);
                    });
                }

                
                btn.addEventListener("mousedown", recStart);
                btn.addEventListener("touchstart", recStart);
                window.addEventListener("mouseup", recEnd);
                window.addEventListener("touchend", recEnd);

                                btn.addEventListener("mousedown", recStart);
                                btn.addEventListener("touchstart", recStart);
                                window.addEventListener("mouseup", recEnd);
                                window.addEventListener("touchend", recEnd);

            })();
        </script>
                        
                    </div>
                </div>
             <!--   <div id="product_details_main_div">
                    <div class="row form-group <?php  echo $permissions->hasPermission('show_ticketing_product_details') ? '' : 'hidden';?>">
                        <?php if( !in_array(2, $ticketing_fields_hide) ){?> 
                        <div class="col-md-3">
                            <label><?php print CommonLanguage::getMessage('Depot'); ?>
                                <?php if($permissions->hasPermission('ListDepot')){?>
                                <span class="fa fa-plus-circle m-l-5 openFrame" data-src="Stock/ListDepot?is_pop=1&is_modal_shown=1" style="color:#4c0870;cursor:pointer"></span>
                                <?php }?>
                            </label>
                            <input type="hidden" id="depot_id" class="full-width" autocomplete="off" value="<?php  echo $ticketing_id  !=0 ? $edit_arr['main']['depot_id'] :  (smc_session()['user_accounts']['depot_id'] ? smc_session()['user_accounts']['depot_id'] : smc_session()['default_depot_id']);?>" data-select-name="<?php  echo $ticketing_id != 0 ?  $edit_arr['main']['depot_name']: (smc_session()['user_accounts']['Depot_Name'] ? smc_session()['user_accounts']['Depot_Name'] : smc_session()['default_depot_name']);?>"   <?php  echo $permissions->hasPermission('change_ticketing_depot') ? '' : 'disabled';?>>
                        </div> 
                        <?php } if( !in_array(3, $ticketing_fields_hide) ){?>
                        <div class="col-md-3 ">
                            <label><?php echo CommonLanguage::getMessage('Currency'); ?>
                            </label>
                            <input type="hidden" name="currency_id" id="currency_id" class="full-width" value="<?php  echo $ticketing_id != 0 ? $edit_arr['main']['currency_id'] : $default_currency_id;?>"  data-select-name="<?php  echo $ticketing_id != 0 ? $edit_arr['main']['currency_name'] : $default_currency_name;?>" />
                        </div>
                        <?php } if( !in_array(4, $ticketing_fields_hide) ){?>
                        <div class="col-md-3 ">
                            <label><?php echo CommonLanguage::getMessage('paid_amount'); ?>
                            </label>
                            <input type="number" name="paid_amount" id="paid_amount" class="form-control" value="<?php  echo $ticketing_id  ==0 ? '' :  $edit_arr['main']['paid_amount'];?>"  />
                        </div> 
                        <?php } if( !in_array(5, $ticketing_fields_hide) ){?>
                        <div class="col-md-3 ">
                            <label><?php echo CommonLanguage::getMessage('payment_account'); ?>
                            </label>
                            <input type="hidden" id="payment_account_id" class="full-width" value="<?php echo $ticketing_id != 0 ? $edit_arr['main']['payment_account_id'] : smc_session()['user_accounts']['cash_account_id'] ?>" data-select-name='<?php echo $ticketing_id != 0 ? $edit_arr['main']['Account_Name'] : smc_session()['user_accounts']['c_name'] ?>' <?php  echo $permissions->hasPermission('change_ticketing_payment_account') ? '' : 'disabled';?>/>
                        </div> 
                        <?php } ?>
                    </div>
                    <div class="row form-group <?php  echo $permissions->hasPermission('show_ticketing_product_details') ? '' : 'hidden';?>">
                        <div class="col-md-2 col-xs-6"><label><?php echo CommonLanguage::getMessage('Product'); ?></label></div>
                        <div class="col-md-2 col-xs-6"><label><?php echo CommonLanguage::getMessage('UOM'); ?></label></div>
                        <div class="col-md-1 col-xs-6"><label><?php echo CommonLanguage::getMessage('Quantity'); ?></label></div>
                        <div class="col-md-1 col-xs-6"><label><?php echo CommonLanguage::getMessage('Price'); ?></label></div>
                        <div class="col-md-1 col-xs-6"><label><?php echo CommonLanguage::getMessage('discount'); ?></label></div>
                        <div class="col-md-1 col-xs-6 <?php echo !in_array(6, $ticketing_fields_hide) ? '' : 'hidden' ?>"><label><?php echo CommonLanguage::getMessage('is_free'); ?></label></div>
                        <div class="col-md-2 col-xs-6 <?php echo !in_array(7, $ticketing_fields_hide) ? '' : 'hidden' ?>"><label><?php echo CommonLanguage::getMessage('is_consignment'); ?> <span class="fa fa-info-circle" title="<?php  echo CommonLanguage::getMessage('transfer_to_consignment_depot');?>"></span></label></div>
                        <div class="col-md-1 col-xs-6"><label><?php echo CommonLanguage::getMessage('total'); ?></label></div>
                        <div class="col-md-1 col-xs-6"></div>
                    </div>
                    <?php  if($ticketing_id == 0 || empty($edit_arr['products'])){?>
                    <div class="row product-row m-t-10" index="0">
                        <div class=" col-md-2 col-xs-6"><input type="hidden" class="product_id full-width" /></div> 
                        <div class=" col-md-2 col-xs-6"><input type="hidden" class="uom_id full-width" /></div> 
                        <div class=" col-md-1 col-xs-6"><input type="number" class="quantity form-control" placeholder="Quantity" ></div>
                        <div class=" col-md-1 col-xs-6"><input type="number" class="price form-control" placeholder="Price" readonly></div>
                        <div class=" col-md-1 col-xs-6"><input type="number" class="discount form-control" placeholder="Discount" ></div>
                        <div class=" col-md-1 col-xs-6 <?php echo !in_array(6, $ticketing_fields_hide) ? '' : 'hidden' ?>"><input type="checkbox" class="is_free"></div>
                        <div class=" col-md-2 col-xs-6 <?php echo !in_array(7, $ticketing_fields_hide) ? '' : 'hidden' ?>"><input type="checkbox" class="is_consignment"></div>
                        <div class="col-md-1 col-xs-6"><span class="bold total_row" data-total="0">0</span></div>
                        <div class="col-md-1 AddButtons">
                            <span class="fa fa-plus m-t-10"></span>
                            <span class="fa fa-minus m-t-10"></span>
                        </div>
                    </div>
                    <?php }else{ 
    if(!empty($edit_arr['products'])) { 
        foreach($edit_arr['products'] as $products){?>
                    <div class="row product-row m-t-10" index="0">
                        <div class=" col-md-2 col-xs-6"><input type="hidden" class="product_id full-width"  value="<?php  echo $products['product_id'];?>" data-select-name="<?php  echo $products['Product_Name'];?>"/></div> 
                        <div class=" col-md-2 col-xs-6"><input type="hidden" class="uom_id full-width" value="<?php  echo $products['uom_id'];?>" data-select-name="<?php  echo $products['UOM_Name'];?>"/></div> 
                        <div class=" col-md-1 col-xs-6"><input type="number" class="quantity form-control" placeholder="Quantity"  value="<?php  echo $products['quantity'];?>"></div>
                        <div class=" col-md-1 col-xs-6"><input type="number" class="price form-control" placeholder="Price" value="<?php  echo $products['price'];?>"  readonly></div>
                        <div class=" col-md-1 col-xs-6"><input type="number" class="discount form-control" placeholder="Discount" value="<?php  echo $products['discount'];?>" ></div>
                        <div class=" col-md-1 col-xs-6"><input type="checkbox" class="is_free" <?php echo empty($products['is_free']) ? '': 'checked';?> ></div>
                        <div class=" col-md-2 col-xs-6"><input type="checkbox" class="is_consignment" <?php echo empty($products['is_consignment']) ? '': 'checked';?>></div>
                        <div class="col-md-1 col-xs-6"><span class="bold total_row" data-total="<?php  echo $products['net_total'];?>"><?php  echo CommonFunctions::formatNumber($products['net_total']);?></span></div>
                        <div class="col-md-1 AddButtons">
                            <span class="fa fa-plus m-t-10"></span>
                            <span class="fa fa-minus m-t-10"></span>
                        </div>
                    </div>
                    <?php } 
    }
}?>
                </div>-->
            </form>
            <?php  if(($ticketing_id== 0) || ($ticketing_id != 0)){?>
            <div class="row">
                <div class="col-md-3 pull-right">
                    <button id="submit_ticketing" class=" btn btn-complete pull-right" ><?php echo CommonLanguage::getMessage('Save'); ?></button>
                </div>
            </div>
            <?php }?>

            <?php echo Forms::ModalLoader('ticketing_loader'); ?>
        </div>
    </div>
</div>

<div class="modal fade" id="ticketing_reply_modal" data-backdrop="static" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header text-left">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="pg-close fs-20"></i>
                </button>
                <h5 class="add-label h-labels text-left bold hidden"> <?php echo CommonLanguage::getMessage('add_new_reply'); ?></h5>
                <h5 class="edit-label h-labels text-left bold hidden"> <?php echo CommonLanguage::getMessage('edit_last_reply'); ?></h5>
            </div>
            <div class="modal-body">
                <form id="ticketing_reply_form" method="POST" onsubmit="return false">
                    <input type="hidden" id="current_type" name="current_type" />
                    <div class="row form-group">
                        <div class="col-md-12">
                            <label><?php print CommonLanguage::getMessage('ticketing_reply_description'); ?></label>
                            <span class="red-star">*</span>
                            <div id="currnet_ticketing_reply_description" class="ticketing_reply_description"></div>
                        </div>
                    </div>
                    <div class="row m-t-10 form-group">                  
                        <div class="col-md-6">                   
                            <input type="file" id="reply_attachment_url" class="form-control" name="reply_attachment_url[]" multiple onchange="ValidateForNewAttachment(this,['.jpg', '.gif', '.jpeg', '.png', '.pdf', '.txt', '.csv',  '.zip', '.log', '.docx'])">
                            <h5 class="semi-bold">Allowed File Extensions: .jpg, .gif, .jpeg, .png, .pdf, .txt, .csv,  .zip, .log, .docx</h5>
                            <div class="display-flex reply_attachment_div" >
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal"><?php print CommonLanguage::getMessage('Close'); ?></button>
                <button class="btn btn-complete" id="submit_ticketing_reply"><?php print CommonLanguage::getMessage('Save'); ?></button>
            </div>
            <?php echo Forms::ModalLoader('ticketing_reply_loader'); ?>
        </div>
    </div>
</div>
<iframe id="maintenance_frame" name="ifrm" style="width:0;height:0;visibility: hidden;" ></iframe>

<script>
    var delete_reply_attachments = [],
        max_discount = <?php echo json_encode(smc_session()['user_accounts']['max_discount']); ?>;
    var is_edit = <?php echo $ticketing_id  == 0 ? 'false' : 'true'; ?>;
    $(function () {



        if(is_edit){
            $("#Employee_ID").val('<?php echo   $ticketing_id  != 0  ? $edit_arr['main']['Employee_ID'] : ''; ?>').attr('data-select-name', '<?php  echo  $ticketing_id  != 0   ?  $edit_arr['main']['Employee_full_name'] : ''; ?>');
        }
        build_select2($("#Employee_ID"), "xhr/searchEmployeeUsers");

        build_select2($("#depot_id"), "xhr/depotSearch");
        build_select2($("#payment_account_id"), 'xhr/accIDSearch?type=pay');
        build_select2($("#currency_id"), 'xhr/CurrencySearch');
        build_select2($("#customer_id"), 'xhr/customerSearch');
        build_select2($("#ticketing_type_id"), 'xhr/commonSearch?table=tbl_maintenance_type&col_id=maintenance_type_id&col_name=maintenance_type_name');
        build_select2($("input.product_id"), ("xhr/ProductSearch?ticketing_price=1"));
        build_select2($("input.uom_id"),"xhr/productuomSearch?pid=&ticketing_price=1");
        if($('#ticketing_id').val() != 0){
            $(".product-row").each(function () {
                var product_id = $("input.product_id",$(this)).val();
                build_select2($("input.uom_id",$(this)),"xhr/productuomSearch?pid="+product_id+"&ticketing_price=1");
            });
        }
        $("#product_details_main_div").on('change','input.product_id',function(){
            var parent = $(this).parents('.product-row');
            if($(this).val()){
                $("input.uom_id",parent).val($(this).select2('data').UOM_ID).attr('data-select-name',$(this).select2('data').UOM_Name);
                $("input.price",parent).val($(this).select2('data').price);
            }else
                $("input.uom_id",parent).val('');
            build_select2($("input.uom_id",parent),"xhr/productuomSearch?ticketing_price=1&pid="+$(this).val());
            update_row_total(parent);
        });
        $("#product_details_main_div").on('change','input.uom_id',function(){
            var parent = $(this).parents('.product-row');
            if($(this).val() && !$('input.is_free',parent).is(":checked") && !$('input.is_consignment',parent).is(":checked")){
                $('input.price',parent).val($(this).select2('data').price);
            }else{
                $('input.price',parent).val(0); 
            }
            update_row_total(parent);
        });
        $('#product_details_main_div').on('click','input.is_free,input.is_consignment',function(){
            var parent =  $(this).parents('.product-row');
            if($(this).is(":checked")){
                $('input.price,input.discount',parent).val(0);
                $('input.discount',parent).prop('readonly',true);
            }else{
                $('input.discount',parent).prop('readonly',false);
            }
            update_row_total(parent);
        });
        $('#ticketing_date').datepicker({autoclose:true});
        $('#ticketing_schedule_date').datetimepicker({ format: 'YYYY-MM-DD HH:mm'});
        $('.ticketing_reply_description').summernote({
            height: 150,
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline', 'clear']],
                ['fontname', ['fontname']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['height', ['height']],
                ['table', ['table']],
                ['insert', ['hr']]
            ],
            focus: true
        });
        document.onselectstart = function () {
            return true
        };
        $("#ticketing_form").on("click", ".product-row .AddButtons .fa-plus", function (e) {
            var Parent = $(this).parents(".product-row"),
                NewItem = Parent.clone().insertAfter(Parent);
            $("input",NewItem).val('');
            $("input[type=checkbox]",NewItem).prop('checked',false);
            $(".select2-container",NewItem).remove();
            build_select2($("input.product_id",NewItem), ("xhr/ProductSearch?ticketing_price=1"));
            build_select2($("input.uom_id",NewItem),"xhr/productuomSearch?ticketing_price=1&pid=");
            $(".select2-container", NewItem).show()
        });
        $("#ticketing_form").on("click", ".product-row .AddButtons .fa-minus", function (e) {
            if($(".product-row").length > 1)
                $(this).closest(".product-row").empty().remove();
        });
        $("#submit_ticketing").on("click", function () {
            if (!$("#ticketing_form").valid() || (!$('#ticketing_reply_description').code() && $('#ticketing_id').val() == 0)){
                $(document.body).animate({scrollTop: 0}, 800);
                return;
            }
            var product_details = [],consignment = [],
                invoices=[],products_invoice = [],amount_to_be_paid = 0;
            $('.product-row').each(function(){
                if($('input.product_id',$(this)).val() && 
                   $('input.uom_id',$(this)).val() && 
                   $('input.quantity',$(this)).val()){
                    product_details.push({
                        product_id:$('input.product_id',$(this)).val(),
                        uom_id:$('input.uom_id',$(this)).val(),
                        quantity:$('input.quantity',$(this)).val(),
                        price:$('input.price',$(this)).val(),
                        discount:$('input.discount',$(this)).val(),
                        total:$('span.total_row',$(this)).attr('data-total'),
                        is_free:$('input.is_free',$(this)).is(":checked") ? 1 : 0,
                        is_consignment:$('input.is_consignment',$(this)).is(":checked") ? 1 : 0,
                    });
                    if($('input.is_consignment',$(this)).is(":checked")){
                        consignment.push({
                            product_id:$('input.product_id',$(this)).val(),
                            uom_id:$('input.uom_id',$(this)).val(),
                            quantity:$('input.quantity',$(this)).val(),
                        }); 
                    }else{
                        invoices.push({
                            product_id:$('input.product_id',$(this)).val(),
                            uom_id:$('input.uom_id',$(this)).val(),
                            quantity:$('input.quantity',$(this)).val(),
                            price:$('input.price',$(this)).val(),
                            discount:$('input.discount',$(this)).val()
                        }); 
                        products_invoice.push($('input.product_id',$(this)).val());
                        amount_to_be_paid += parseFloat($('span.total_row',$(this)).attr('data-total'));
                    }
                }
            }); 
            if(product_details.length > 0 && 
               ((!$('#depot_id').val() && $('#depot_id').length  > 0) || (!$('#currency_id').val() && $('#currency_id').length  > 0)) &&
               !$('#product_details_main_div').hasClass('hidden')){
                AddAlert("#ticketing_alert", "<?php  echo CommonLanguage::getMessage('choose_depot_currency');?>", "danger");
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            if(invoices.length > 0 && !$('#product_details_main_div').hasClass('hidden') &&
               parseFloat($('#paid_amount').val()) > amount_to_be_paid ){
                AddAlert("#ticketing_alert", "<?php  echo CommonLanguage::getMessage('paid_amount_less_total');?>", "danger");
                $(document.body).animate({scrollTop: 0}, 800)
                return;
            }
            //            return;
            var Data = new FormData(document.getElementById("ticketing_form"));
            if(window.is_record == 'true'){
                Data.append('nonce', window.nonce);
            }else{
                Data.append('nonce', $('#nonce_file').val());
            }
            Data.append('is_record', window.is_record);
            Data.append('depot_id', $('#depot_id').val());
            Data.append('payment_account_id', $('#payment_account_id').val());
            Data.append('ticketing_status_id', $('#ticketing_status_id').val());
            Data.append('ticketing_reply_description', $('#ticketing_reply_description').code());
            Data.append('customer_name', $('#customer_id').select2('data').text);
            Data.append('currency_symbol', $('#currency_id').select2('data').Currency_Symbol);
            Data.append('product_details', JSON.stringify(product_details));
            Data.append('consignment', JSON.stringify(consignment));
            Data.append('invoices', JSON.stringify(invoices));
            Data.append('products_invoice', JSON.stringify(products_invoice));
            $("#ticketing_loader").removeClass('hidden');
            $.ajax({
                url: "TicketingAjax/submit_maintenance",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        data = {maintenance_id: jqXHR.responseJSON[2]};
                        $("#print_ticket").removeAttr('disabled')
                        if (jqXHR.responseJSON[1] == "success") {
                            $("#submit_ticketing").prop('disabled', true);
                        }
                        $(document.body).animate({scrollTop: 0}, 800)
                        AddAlert("#ticketing_alert", jqXHR.responseJSON[0], jqXHR.responseJSON[1]);
                    }
                    $("#ticketing_loader").addClass('hidden');
                }
            });
        });
        $('#edit_last_reply').on('click',function(){
            delete_reply_attachments = [];
            $('#current_type').val('edit');
            $('#ticketing_reply_modal .edit-label').removeClass('hidden');
            CommonViewById('TicketingAjax/get_maintenance_reply', {ticketing_reply_id:$('#ticketing_reply_id').val()},
                           '#ticketing_reply_loader', function (response) {
                $('#currnet_ticketing_reply_description').code(response['maintenance_reply_description']);
                $('#ticketing_reply_modal .reply_attachment_div').html(response['attachments']);
            });
        });
        $('#add_new_reply').on('click',function(){
            delete_reply_attachments = [];
            $('#current_type').val('add');
            $('#ticketing_reply_modal .add-label').removeClass('hidden');
            $('#currnet_ticketing_reply_description').code('');
            $('#ticketing_reply_modal .reply_attachment_div').empty();
        });
        $("#submit_ticketing_reply").on("click", function () {
            if (!$('#currnet_ticketing_reply_description').code()){
                toastr.error('<?php  echo CommonLanguage::getMessage('fill_ticketing_reply');?>');
                return;
            }
            var Data = new FormData(document.getElementById("ticketing_reply_form"));
            Data.append('ticketing_reply_id',$('#ticketing_reply_id').val());
            Data.append('ticketing_id',$('#ticketing_id').val());
            Data.append('ticketing_reply_description',$('#currnet_ticketing_reply_description').code());
            Data.append('delete_reply_attachments', JSON.stringify(delete_reply_attachments));
            $("#ticketing_reply_loader").removeClass('hidden');
            $.ajax({
                url: "TicketingAjax/submit_maintenance_reply",
                method: "POST",
                data: Data,
                processData: false,
                contentType: false,
                dataType: "JSON",
                complete: function (jqXHR, status) {
                    if (status == 'success') {
                        if (jqXHR.responseJSON[1] == "success") {
                            toastr.success(jqXHR.responseJSON[0]);
                            hideModalAlert('ticketing_reply_modal');
                            var reply_details = jqXHR.responseJSON[2];
                            $('#ticketing_reply_html').html(reply_details['maintenance_reply_description']);
                            $('#ticketing_form .reply_attachment_div').html(reply_details['attachments']);
                        }else{
                            toastr.error(jqXHR.responseJSON[0]);
                        }
                    }
                    $("#ticketing_reply_loader").addClass('hidden');
                }
            });
        });
        $('#product_details_main_div').on('input','input.discount',function(){
              var parent =  $(this).parents('.product-row');
            check_discount($(this),$(this).val());
            update_row_total(parent);
        });
        $('#product_details_main_div').on('input','input.quantity',function(){
             var parent =  $(this).parents('.product-row');
            update_row_total(parent);
        });
        $('.reply_attachment_div').on('click', '.delete_reply_attachment', function () {
            delete_reply_attachments.push($(this).closest('.main_attachment_row').attr('data-attachment-name'));
            $(this).closest('.main_attachment_row').remove();
        });
    });
    function update_row_total(row){
        var quantity = parseFloat($('input.quantity',row).val()) || 0,price = parseFloat($('input.price',row).val()) || 0,
            discount = parseFloat($('input.discount',row).val()) || 0,
            total = quantity * price,
            net_total = parseFloat(total * (1 - discount / 100)) || 0;
        $('.total_row',row).attr('data-total',net_total);
        $('.total_row',row).text(AddCommas(parseFloat(net_total).toFixed(3)));
    }

    function check_discount(me, item_disc) {
        if (item_disc > 0) {
            if (parseFloat(me.val()) > Math.min(parseFloat(max_discount), item_disc))
                me.val(Math.min(parseFloat(max_discount), item_disc));
        }else if(parseFloat(item_disc) < 0){
            me.val(0);
        } else if (parseFloat(me.val()) > parseFloat(max_discount)){
            me.val(parseFloat(max_discount));
        }
    }
</script>
