{extends file="$layouts_admin"}

 
{block name="content"}


 <link
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css"
  rel="stylesheet"
/>


<style type="text/css">

.timeline-item {
    border-radius: 3px;
    margin-top: 0;
    background: #fff;
    color: #444;
    margin-left: 60px;
    margin-right: 15px;
    padding: 0;
    position: relative;
    box-shadow: 0 0 13px 0 rgba(74,53,107,.08);
    border: 1px solid #dee2e6;
    box-sizing: content-box;
}

.timeline-body {
    width: 100% !important;
    max-width: 100%;
    word-wrap: break-word;
    overflow-wrap: break-word;
    white-space: normal;
    box-sizing: border-box;
    padding: 10px;
    line-height: 1.5;
}

.timeline-body p {
    margin: 0 0 8px 0;
    word-break: break-word;
}

 .btn-edit-referencia-personal {
         margin-bottom: 4px; 
         background-color: #001b3b; 
         color: white; 
         border: 1px solid rgb(211, 202, 192) !important; 
         box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px; 
         float: inline-end;
    }

   .btn-eliminar-referencia-personal {
      margin-bottom: 4px;
      background-color: red;
      color: white;
      border: 1px solid rgb(211, 202, 192) !important;
      box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;
      float: inline-end;
    }

   .btn-edit-referencia-personal:hover i,
   .btn-eliminar-referencia-personal:hover i {
      color: white; /* Mantén el color blanco del icono en hover */
   }

   .tamano-icono{
      font-size:small;
   }
    
   .centrar-botones{
      text-align: center;
      justify-content: center;
      display: flex;
      padding: 0px;
   }

   .btn-descargar {
         margin-bottom: 4px; 
         background-color: #001b3b; 
         color: white; 
         border: 1px solid rgb(211, 202, 192) !important; 
         box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px; 
         float: inline-end;
    }

   .btn-eliminar {
      margin-bottom: 4px;
      background-color: red;
      color: white;
      border: 1px solid rgb(211, 202, 192) !important;
      box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;
      float: inline-end;
    }

   .btn-descargar:hover i,
   .btn-eliminar:hover i {
      color: white; /* Mantén el color blanco del icono en hover */
   }

   .btn-dowload-style {
        margin-bottom: 8px;
        background-color: #001b3b;
        color: white;
        border: 1px solid rgb(211, 202, 192) !important;
        box-shadow: rgba(60, 64, 67, 0.3) 0px 1px 2px 0px, rgba(60, 64, 67, 0.15) 0px 1px 3px 1px;
        width: 300px;
        margin-top: 6px;
    }

    .btn-dowload-style:hover i  {
      color: white;  
    }

</style>

    <input
         type="text"
         value="{$url_base}"
         disabled
         hidden
         id="URL_BASE"
    />

    <input
         type="text"
         value="{$url_crm_administrativo}"
         disabled
         hidden
         id="url_crm_administrativo"
    />

    <input class="form-control getCRMPartnertAdmin" type="text" id="getCRMPartnertAdmin" name="getCRMPartnertAdmin" value="{$crm_partnert_administrativo}" hidden disabled>

    <textarea class="getListTicketsStatus" hidden disabled value="{$list_sys_tickets_status_json}" >{$list_sys_tickets_status_json}</textarea>
    <textarea class="getListTicketsCategory" hidden disabled value="{$list_sys_tickets_category_json}" >{$list_sys_tickets_category_json}</textarea>

    <input class="form-control getTimeZone" type="text" id="getTimeZone" name="getTimeZone" value="{$getTimeZone}" hidden disabled>
    <input class="form-control getstatus_id" type="text" id="getstatus_id" name="getstatus_id" value="{$d->status_id}" hidden disabled>


    <div class="row">
        <div class="col">
            <h2>{$d->subject}</h2>
        </div>
        <div class="col text-end">
            <a href="{$_url}tickets/admin/list/" class="btn btn-primary btn-sm" style="margin-bottom: 15px;"><i
                        class="fal fa-long-arrow-left"></i> {$_L['Back to the List']}</a>
        </div>
    </div>

    <div class="row">
        <div class="col-md-4">



            <div class="card border" id="t_options">

                <div class="card-header">
                    <ul class="nav nav-tabs card-header-tabs" role="tablist">
                        <li class="nav-item active" role="presentation"><a data-bs-toggle="tab" href="javascript:;" class="nav-link active" data-bs-target="#details"><i class="fal fa-th"></i> {$_L['Details']}</a></li>
                        
                        {if $crm_partnert_administrativo == 1 }
                            <li class="nav-item" role="presentation"><a class="nav-link" data-bs-toggle="tab" href="javascript:;" data-bs-target="#tasks"><i class="fal fa-tasks"></i> {$_L['Tasks']}</a></li>
                        {/if}

                        
                        
                        <li class="nav-item" role="presentation"><a class="nav-link" data-bs-toggle="tab" href="javascript:;" data-bs-target="#tap_category"><i class="fal fa-tasks"></i> Category </a></li>
                        <li class="nav-item" role="presentation"><a class="nav-link" data-bs-toggle="tab" href="javascript:;" data-bs-target="#tap_documents"><i class="fal fa-tasks"></i> Documents </a></li>

                    </ul>
                </div>




                <div class="card-body">




                    <div class="tab-content">
                        <div id="details" class="tab-pane fade show active ib-tab-box">


                            <div class="row mt-3">
                                <div class="col">
                                    <div> {$_L['Priority']}:
                                        {if $d->urgency == 'Medium' || $d->urgency == 'High'}
                                            <span class="badge badge-outline text-uppercase badge-outline-danger">{ib_lan_get_line($d->urgency)}</span>
                                        {else}
                                            <span class="badge badge-outline text-uppercase badge-outline-success">{ib_lan_get_line($d->urgency)}</span>
                                        {/if}
                                    </div>
                                </div>
                                <div class="col">
                                    <div> {$_L['Status']}: <span id="inline_status">{$d->status}</span></div>
                                </div>
                            </div>




                            <hr>
                            <p><strong>{$_L['Ticket']}:</strong> {$d->tid}</p>
                            <p><strong>{$_L['Customer']}:</strong> <a href="{$_url}contacts/view/{$d->userid}">{$d->account}</a></p>



                            <hr>



                            {*
                                <a class="btn btn-primary" href="#" id="add_reply">{$_L['Add Reply']}</a>
                            *}

                            {*
                            
                                {if $crm_partnert_administrativo == 1 && $d->status_id != 5}

                                    {if $can_edit_sales}
                                        {if $invoice}
                                            <a class="btn btn-success" href="{$_url}invoices/view/{$invoice->id}"  target="_blank" > {$_L['View Invoice']}</a>
                                        {else}
                                            <a class="btn btn-success" id="convertToInvoice" href="javascript:;">{$_L['Create Invoice']}</a>
                                        {/if}
                                    {/if}

                                    <a class="cdelete btn btn-danger" href="#" id="t{$d->id}"><i class="fal fa-trash-alt"></i> </a>

                                    <hr>

                                {/if}

                            *}

                             
 
                             

                            <div class="mb-3">
                                <label for="editable_department">{$_L['Department']}</label>
                                {if $crm_partnert_administrativo == 1 && $d->status_id != 5 }

                                    <select class="form-select" id="editable_department" name="editable_department" size="1">
                                        <option value="None">None</option>
                                        {foreach $departments as $dep}
                                            <option value="{$dep['id']}" {if $department eq $dep['dname']} selected{/if}>{$dep['dname']}</option>
                                        {/foreach}
                                    </select>

                                {else}
                                    <input class="form-control" type="text" id="" name="" value="{$d->dname}" disabled>
                                {/if}
                            </div>

                            <div class="mb-3">
                                <label>{$_L['Assigned to']}</label>

                                {if $crm_partnert_administrativo == 1 && $d->status_id != 5 }
                                    <select class="form-select" id="editable_assigned_to" name="editable_assigned_to" size="1">
                                        <option value="None">{$_L['None']}</option>
                                        {foreach $ads as $ad}
                                            <option value="{$ad['id']}" {if $d->aid eq $ad['id']} selected{/if}>{$ad['fullname']}</option>
                                        {/foreach}
                                    </select>
                                {else}
                                    <input class="form-control" type="text" id="" name="" value="{$d->aname_staff_assigned}" disabled>
                                {/if}

                            </div>

                            {*

                                <div class="mb-3">
                                    <label for="editable_status">{$_L['Status']}</label>

                                    {if $crm_partnert_administrativo == 1 && $d->status_id != 5 }
                                        
                                        <select class="form-select" id="editable_status" name="editable_status" size="1"  >
                                            {foreach $list_sys_tickets_status as $item}
                                                <option value="{$item['id']}">{$item['name']}</option>
                                            {/foreach}
                                        </select>
                                    {else}
                                        <input class="form-control" type="text" id="" name="" value="{$d->status}" disabled>
                                    {/if}
                                </div>

                            *}
                             


                            {if $crm_partnert_administrativo == 1}
                                <div class="mb-3">
                                    <label for="editable_cc">Email - Clients</label>
                                    <input class="form-control" type="text" id="editable_email" name="editable_email" value="{$d->email}" disabled>
                                </div>

                                <div class="mb-3">
                                    <label for="editable_phone">Phone - Clients</label>
                                    <input class="form-control" type="text" id="editable_phone" name="editable_phone" value="{if $c}{$c->phone}{/if}" disabled>
                                </div>

                            {/if}

                            
                            {*
                                <div class="mb-3">
                                    <label for="editable_cc">{$_L['Cc']}</label>
                                    <input class="form-control" type="text" id="editable_cc" name="editable_cc" value="{$d->cc}">
                                </div>

                                <div class="mb-3">
                                    <label for="editable_bcc">{$_L['Bcc']}</label>
                                    <input class="form-control" type="text" id="editable_bcc" name="editable_bcc" value="{$d->bcc}">
                                </div>
                            *}
 
                             
                            <div class="mb-3">
                                <label for="editable_email_tickets">Email - Forms Tickets</label>
                                <input class="form-control" type="text" id="editable_email_tickets" name="editable_email_tickets" value="{if $d}{$d->email_client}{/if}" disabled>
                            </div>

                            <div class="mb-3">
                                <label for="editable_phone_tickets">Phone - Forms Tickets</label>
                                <input class="form-control" type="text" id="editable_phone_tickets" name="editable_phone_tickets" value="{if $d}{$d->phone_client}{/if}" disabled>
                            </div>

                            <div class="mb-3">
                                <label for="editable_contacts_tickets">Contacts - Forms Tickets</label>
                                <input class="form-control" type="text" id="editable_contacts_tickets" name="editable_contacts_tickets" value="{if $d}{$d->contact_client}{/if}" disabled>
                            </div>


                            <input type="hidden" name="tid" id="tid" value="{$d->id}">



                            <form>

                                <hr>

                                <div class="mb-3">
                                    <label for="mi_field_status">{$_L['Status']}</label>

                                    {if $crm_partnert_administrativo == 1 && $d->status_id != 5 }
                                        <select class="form-select mi_field_status" id="mi_field_status" name="mi_field_status" size="1"  >

                                            {foreach $list_sys_tickets_status as $item}
                                                <option value="{$item['id']}">{$item['name']}</option>
                                            {/foreach}
 
                                        </select>
                                    {else}
                                        <input class="form-control" type="text" id="" name="" value="{$d->status}" disabled>
                                    {/if}
                                </div>
                                
                                <div class="mb-3">
                                    <label for="expected_closing_date">Expected closing date</label>
                                    <input class="form-control expected_closing_date" type="text" id="expected_closing_date" name="expected_closing_date" value="{$d->expected_closing_date}" disabled>
                                </div>

                                <div class="mb-3">
                                     
                                    {if $crm_partnert_administrativo == 1 && $d->status_id != 5 }
                                        <label for="exampleInputEmail1">{{__('Note')}}</label>
                                        <textarea class="form-control notes" name="notes" id="notes" rows="3">{$d->notes}</textarea>
                                    {/if}

                                    {if $crm_partnert_administrativo == 1 && $d->status_id == 5 }
                                        <label for="exampleInputEmail1">{{__('Note')}}</label>
                                        <textarea class="form-control"  rows="5" disabled>{$d->notes}</textarea>
                                    {/if}
                                </div>

                                {if $crm_partnert_administrativo == 1 && $d->status_id != 5 }
                                    <button type="submit" id="btn_save_note" class="btn btn-primary">{$_L['Save']}</button>
                                {/if}

                            </form>


                            <hr>

                            <h4>{$_L['Previous Conversations']}</h4>

                            {if count($o_tickets) > 1}

                                <table class="table table-hover">

                                    <tbody>

                                    {foreach $o_tickets as $o_ticket}

                                        {if $o_ticket['id'] == $d->id}
                                            {continue}
                                        {/if}

                                        <tr>
                                            <td>
                                                <em>{date( $config['df'], strtotime($o_ticket['created_at']))}</em>
                                                <br>
                                                <p><a href="{$_url}tickets/admin/view/{$o_ticket['id']}">{$o_ticket['subject']}</a></p>
                                                <span class="label label-default inline-block"> {$_L['Status']}: {$d->status} </span>

                                            </td>
                                        </tr>


                                    {/foreach}

                                    </tbody>
                                </table>

                            {else}

                               <span class="mt-3">{$_L['No Data Available']}</span>

                            {/if}

                        </div>

                        {* this is tap task *}
                        <div id="tasks" class="tab-pane fade ib-tab-box">


                            <form id="ib_add_group" class="form-horizontal push-10-t push-10" method="post">

                                <div class="mb-3">
                                    <label for="task_subject">{$_L['Task']}</label>
                                    <input class="form-control" type="text" id="task_subject" name="task_subject">
                                </div>



                                <div class="mb-3">
                                    <div class="col-xs-12">
                                        <button class="btn btn-primary" id="btn_add_task" type="submit">{$_L['Save']}</button>
                                        <div id="tasks_tools"  style="display: none;">
                                            <hr>

                                            <div class="btn-group">
                                                <button type="button" class="btn btn-success no-shadow" id="btn_mark_tasks_completed" data-bs-toggle="tooltip" data-placement="top" title="{$_L['Mark as Completed']}"><i class="fal fa-check"></i></button>
                                                <button type="button" class="btn btn-primary no-shadow" id="btn_mark_tasks_not_started" data-bs-toggle="tooltip" data-placement="top" title="{$_L['Mark as Not Started']}"><i class="fal fa-clock"></i></button>
                                                <button type="button" class="btn btn-danger no-shadow" id="btn_delete_tasks" data-bs-toggle="tooltip" data-placement="top" title="{$_L['Delete']}"><i class="fal fa-trash-alt"></i></button>
                                            </div>


                                            <hr>
                                        </div>
                                    </div>
                                </div>
                            </form>

                            <div id="tasks_list">

                            </div>


                        </div>
                        {* fin this is tap task *}

                        {* this is tap tap_category *}
                        <div id="tap_category" class="tab-pane fade ib-tab-box">


                            <form class="form-horizontal push-10-t push-10" >

                                {if $crm_partnert_administrativo == 1 && $d->status_id != 5 }
                                <div class="mb-3 row" >

                                    <div class="col-12">
                                        <label for="input_category">Category</label>
                                        <select class="form-select input_category" id="input_category" name="input_category" size="1"  >
                                            <option value="">Select an option</option>
                                            
                                            {foreach $list_sys_tickets_category as $item}
                                                <option value="{$item['id']}">{$item['name']}</option>
                                            {/foreach}
                                        </select>
                                    </div>

                                    <div class="col-12 mt-2">
                                        <button class="btn btn-primary" id="btn_add_category" type="button" style="float: inline-end">{$_L['Save']}</button>
                                    </div>
                                     
                                </div>
                                {/if}


                                <hr>

                                <div class="row containerCategory">

                                    {*
                                        {foreach $listaSysTicketCategoty as $item}
                                            <div class="d-flex justify-content-between align-items-center mb-2">
                                                <div class="text-start flex-fill me-2" style="word-break: break-word; overflow-wrap: break-word;">
                                                    <strong>{$item['sys_tickets_category_name']}</strong>
                                                </div>
                                                <div>
                                                    <button class="btn btn-danger btn-sm" id="btn_delete_category" data-id="{$item['id']}" type="button">
                                                        <i class="fal fa-trash-alt"></i>
                                                    </button>
                                                </div>
                                            </div>
                                            <hr class="my-1">
                                        {/foreach}
                                    *}
                                     

                                </div>
                                
                                <div class="mb-3">
                                    <div class="col-xs-12">
                                        {*
                                            <button class="btn btn-primary" id="btn_add_task" type="submit">{$_L['Save']}</button>

                                               <div id="tasks_tools"  style="display: none;">
                                            <hr>

                                            <div class="btn-group">
                                                    <button type="button" class="btn btn-success no-shadow" id="btn_mark_tasks_completed" data-bs-toggle="tooltip" data-placement="top" title="{$_L['Mark as Completed']}"><i class="fal fa-check"></i></button>
                                                    <button type="button" class="btn btn-primary no-shadow" id="btn_mark_tasks_not_started" data-bs-toggle="tooltip" data-placement="top" title="{$_L['Mark as Not Started']}"><i class="fal fa-clock"></i></button>
                                                    <button type="button" class="btn btn-danger no-shadow" id="btn_delete_tasks" data-bs-toggle="tooltip" data-placement="top" title="{$_L['Delete']}"><i class="fal fa-trash-alt"></i></button>
                                                </div>


                                                <hr>
                                            </div>

                                        *}
                                      
                                    </div>
                                </div>
                            </form>
 


                        </div>
                        {* fin this is tap tap_category *}

                        {*tap_documents*}

                        <div id="tap_documents" class="tab-pane fade ib-tab-box">

                            <div class="row containerDocuments">

                                  

                            </div>

                        </div>


                    </div>
 
                </div>

            </div>

        </div>
        <div class="col-md-8">
            <div class="row">
                <div class="col-md-12" id="create_ticket">


                    <!-- The time line -->
                    <ul class="timeline">
                        <!-- timeline time label -->
                        <li class="time-label">
                  <span>
                    {date( $config['df'], strtotime($d->created_at))}
                  </span>
                        </li>
                        <!-- /.timeline-label -->
                        <!-- timeline item -->
                        <li>



                            {if $d->admin neq '0'}
                                {if $user['img'] eq 'gravatar'}
                                    <img src="http://www.gravatar.com/avatar/{md5($user['email'])}?s=30"
                                         class="img-time-line" alt="{$user['fullname']}">
                                {elseif $user['img'] eq ''}
                                    <img class="img-time-line" src="{$app_url}ui/lib/img/default-user-avatar.png" alt="">
                                {else}
                                    <img src="{{APP_URL}}/{$user['img']}" class="img-time-line" alt="{$user['account']}">
                                {/if}

                            {elseif ($c)}

                                {if $c->img eq 'gravatar'}
                                    <img src="http://www.gravatar.com/avatar/{md5($user['email'])}?s=30"
                                         class="img-time-line" alt="{$user['fullname']}">
                                {elseif $c->img eq ''}
                                    <img class="img-time-line" src="{$app_url}ui/lib/img/default-user-avatar.png" alt="">
                                {else}
                                    <img src="{$c->img}" class="img-time-line" alt="{$user['account']}">
                                {/if}

                            {else}



                            {/if}


                            <div class="timeline-item">



                                <h3 class="timeline-header"><a href="javascript:void(0)">{$d->account}</a></h3>

                                <div class="timeline-body">
                                    {$d->message}
                                    
                                    {*
                                        {if $d->status_id != 5 }
                                            <a href="#" class="btn btn-warning t_edit" data-bs-toggle="tooltip"
                                                data-placement="top" title="" data-original-title="{$_L['Edit']}" id="et{$d->id}"><i
                                                            class="fal fa-pencil"></i> </a>

                                            <hr>
                                        {/if}
                                    *}
                                     
                                     
                                </div>

                                {if ($d->attachments) neq ''}
                                    <div class="timeline-footer">
                                        {Tickets::gen_link_attachments($d->attachments)}
                                    </div>
                                {/if}


                            </div>
                        </li>

                        {* aqui tenemos todo lo que escribimos *}
                        {foreach $replies as $reply}

                            <li class="time-label">
                                <span>
                                    {date( $config['df'], strtotime($reply['created_at']))}
                                </span>
                            </li>

                            <li>

                                {if $reply['admin'] neq '0'}
                                    <img src="{getAdminImage($reply['admin'],30)}" class="img-time-line">
                                {elseif ($c)}

                                    {if $c->img eq ''}
                                        <img class="img-time-line" src="{$app_url}ui/lib/img/default-user-avatar.png"
                                             alt="">
                                    {else}
                                        <img src="{{APP_URL}}/{$c->img}" class="img-time-line" alt="{$user['account']}">
                                    {/if}

                                {else}

                                {/if}

                                <div class="timeline-item">


                                    <h3 class="timeline-header">
                                        <a href="javascript:void(0)">
                                            {$reply['replied_by']}  
                                            
                                            {if $reply['who_sent'] == 1 }
                                                - Sent by CRM Administrative
                                            {else}
                                                - Sent by CRM Clients
                                            {/if}

                                        </a>
                                    </h3>

                                    <div class="timeline-body" {if $reply['reply_type'] eq 'internal'} style="background: #FFF6D9;" {/if}>
                                        {$reply['message']}


                                        {if $d->status_id != 5 }

                                            {if $crm_partnert_administrativo == $reply['who_sent'] }

                                                <hr>

                                                <a href="#" class="btn btn-danger reply_delete"
                                                    data-bs-toggle="tooltip" data-placement="top" title=""
                                                    data-original-title="{$_L['Delete']}" id="dr{$reply['id']}"
                                                    data-uuid="{$reply['UUID']}"
                                                    >
                                                    <i class="fal fa-trash-alt"></i>
                                                </a> 
                                                
                                                &nbsp;
                                                
                                                
                                                {*
                                                     <a href="#" class="btn btn-warning reply_edit"
                                                        data-bs-toggle="tooltip" data-placement="top" title=""
                                                        data-original-title="{$_L['Edit']}" id="er{$reply['id']}">
                                                        <i class="fal fa-pencil"></i>
                                                    </a> 
                                                *}
                                                
                                                &nbsp;

                                                {* en caso de que sea internal *}
                                                {if $reply['reply_type'] eq 'internal'} 
                                                    <a href="#" class="btn btn-primary no-shadow reply_make_public"
                                                                data-bs-toggle="tooltip" data-placement="top" title=""
                                                                data-original-title="{$_L['Public']}" id="rp{$reply['id']}"
                                                                data-uuid="{$reply['UUID']}"
                                                                >
                                                        <i class="fal fa-globe"></i>
                                                    </a> 
                                                {/if}

                                            {/if}

                                        {/if}


                                    </div>

                                    {if ($reply['attachments']) neq ''}
                                        <div class="timeline-footer">
                                            {Tickets::gen_link_attachments_v1($reply['attachments'])}
                                        </div>
                                    {/if}


                                </div>
                            </li>
                        {/foreach}
                        {* ------ *}

                        <!-- END timeline item -->
                        <!-- timeline item -->
                        {if $d->status_id != 5 }
                        <li class="time-label">
                            <span class="bg-green" id="section_add_reply">
                            {__('Add Reply')}
                            </span>
                        </li>
                        <li>
                            {if $user['img'] eq ''}
                                <img class="img-time-line" src="{$app_url}ui/lib/img/default-user-avatar.png" alt="">
                            {else}
                                <img src="{$user['img']}" class="img-time-line" alt="{$user['account']}">
                            {/if}

                            <div class="timeline-item">


                                <div class="timeline-body">
                                    <form class="form-horizontal push-10-t push-10" method="post">
                                        {if $d->status_id != 5 }
                                            <ul class="nav nav-pills mb-3"  role="tablist">
                                                <li class="nav-item"><a id="reply_public" class="nav-link active" href="#">{$_L['Customer']}</a></li>
                                                <li class="nav-item"><a id="reply_internal" class="nav-link" href="#">{$_L['Internal']}</a></li>
                                            </ul>
                                        {/if}

                                        {if !empty($config['openai_api_key'])}
                                            <div class="mb-2">
                                                <button class="btn btn-primary" type="button" id="btn_generate_reply">{__('Generate Reply')}</button>
                                            </div>
                                        {/if}

                                        <div class="mb-3">
                                            <div class="col-xs-12">

                                            <textarea id="content" class="form-control sysedit"
                                                      name="content"></textarea>
                                                <div class="help-block">

                                                    {if $d->status_id != 5 }
                                                        <a data-bs-toggle="modal" href="#modal_add_item"><i
                                                                    class="fal fa-paperclip"></i> {$_L['Attach File']}</a>
                                                        | <a data-bs-toggle="modal" href="#modal_predefined_replies"><i
                                                                    class="fal fa-align-left"></i> {$_L['Predefined Reply']}</a>
                                                    {/if}
                                                </div>
                                            </div>
                                        </div>




                                        <div class="mb-3">
                                            <div class="col-xs-12">

                                                <input type="hidden" name="attachments" id="attachments" value="">
                                                <input type="hidden" name="f_tid" id="f_tid" value="{$d->id}">
                                                <input type="hidden" name="cid" id="cid" value="{$d->userid}">

                                                {if $d->status_id != 5 }
                                                    <button class="btn btn-primary" id="ib_form_submit" type="submit"><i
                                                            class="fal fa-send push-5-r"></i> Submit
                                                    </button>
                                                {/if}

                                                 
                                            </div>
                                        </div>
                                    </form>
                                </div>

                            </div>
                        </li>

                        {/if}

                        <li>
                            <i class="fal fa-life-ring bg-gray"></i>
                        </li>
                    </ul>
                </div>
                <!-- /.col -->
            </div>
        </div>
    </div>
    <div class="modal fade" id="modal_add_item" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title">
                        {$_L['Attach File']}
                    </h4>
                    <button type="button" class="close btn btn-danger" data-bs-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true"><i class="fal fa-times"></i></span>
                    </button>
                </div>
                <div class="modal-body">
                    <form action="" class="dropzone" id="upload_container">

                        <div class="dz-message">
                            <h3> <i class="fal fa-cloud-upload"></i>  {$_L['Drop File Here']}</h3>
                            <br />
                            <span class="note">{$_L['Click to Upload']}</span>
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{$_L['Close']}</button>
                </div>
            </div>
        </div>
    </div>


 
    <div id="modal_predefined_replies" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">{$_L['Predefined Replies']}</h5>
                    <button type="button" class="close btn btn-danger" data-bs-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true"><i class="fal fa-times"></i></span>
                    </button>
                </div>
                <div class="modal-body">
                    <table class="table table-bordered table-hover sys_table" id="clx_datatable">
                        <thead>
                        <tr>
                            <th>{$_L['Name']}</th>
                        </tr>
                        </thead>
                        <tbody>

                        {foreach $predefined_replies as $predefined_replie}
                            <tr>
                                <td><a href="javascript:;" onclick="setPreDefinedContent(event,'{$predefined_replie->id}');">{$predefined_replie->title}</a> </td>
                            </tr>
                        {/foreach}

                        </tbody>

                        <tfoot>
                        <tr>
                            <td>
                                <ul class="pagination">
                                </ul>
                            </td>
                        </tr>
                        </tfoot>

                    </table>
                </div>
            </div>
        </div>

    </div>



    <div class="modal fade" id="ventana_confirmacion" tabindex="-1" aria-labelledby="exampleModalLabel__ventanaconfirmacion" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false" >
        <div class="modal-dialog modal-dialog-centered"  >
            <div class="modal-content" style="background-color:white">
                <div class="modal-header">
                <h3 class="titulo_modal_confirmar">Estas seguro de eliminar</h3>
                    <button type="button" class="btn-close "  id="btn_close_ventana_confirmacion" ></button>
                </div>
                <div class="modal-body" style="background-color:white;border-radius:10px">
                
                    <div class="row">
                    <div class="col-md-12">
                        <div class="panel-container show" id="ibox_form">
                                <div class="panel-content">
                                    <div class="px-2">
                                            <div class="alert alert-danger" id="emsg" style="display: none;">
                                            <span id="emsgbody"></span>
                                            </div>
                                            <input class="tipo_modal_confirmar" hidden disabled/> 
                                            <input class="data_id" hidden disabled/> 
                                            <div class="row">
                                                <div class="col-md-12 col-sm-12">

                                                        <h4 class="mensaje_modal_confirmar" style="text-align:center; color:black">Estas seguro de eliminar</h4>
                                                        
                                                        <p class="mensaje_espera_moda_confirmacion mt-3" style="text-align:center; color:red; font-weight:600">Espere mientras termina el proceso</p>
                                                </div>
                                            
                                            </div>

                                            <div class="row mt-2">
                                                <div class="col-md-12">
                                                        <div style=" float: inline-end; ">
                                                        <button class="btn btn-primary me-2" type="button" id="btn_cerrar_ventana_confirmacion" style="   ">close</button>
                                                        <button class="btn btn-danger " type="button" id="btn_aplicar_ventana_confirmacion" style=" background: red; ">Remove</button>
                                                        </div>
                                                </div>
                                            </div>
                                    </div>
                                </div>
                                </div>
                    </div>
                    </div>
                
                </div>
                
            </div>
        </div>
    </div>

{/block}

{block name="script"}



    <script>

        //var COLOR_FONDO_VENTANA_CERRAR = "#001b3b";
        //var COLOR_TEXT_VENTANA_CERRAR = "white";

        //var COLOR_FONDO_VENTANA_CONFIRMACION = "red";
        //var COLOR_TEXT_VENTANA_CONFIRMACION = "white";

        var COLOR_FONDO_VENTANA_IR = "#001b3b";
        var COLOR_TEXT_VENTANA_IR = "white";

        var URL_BASE = $("#URL_BASE").val();

        var url_crm_administrativo = $("#url_crm_administrativo").val();

        console.log("url_crm_administrativo");
        console.log(url_crm_administrativo);

        let getCRMPartnertAdmin = $(".getCRMPartnertAdmin").val();

        let getListTicketsStatus    = $(".getListTicketsStatus").val();
        let getListTicketsCategory  = $(".getListTicketsCategory").val();
        let getTimeZone             = $(".getTimeZone").val() || "America/New_York";
        let getstatus_id            = $(".getstatus_id").val();

        var arrayTicketsStatus = [];
        var arrayTicketsCategory = [];

        var arrayImageSticketReplies = [];

        function isEmpty(variable) {
            if (variable === null || variable === undefined) {
                return true;
            }

            if (typeof variable === "string") {
                return variable.trim() === "";
            }

            if (Array.isArray(variable)) {
                return variable.length === 0;
            }

            if (typeof variable === "object") {
                return Object.keys(variable).length === 0;
            }

            return false;
        }

        $(document).ready(function () {

            function sumarDiasConZonaHoraria(timeZone = "America/Tegucigalpa", diasASumar = 5) {
                // Si no se pasa fecha, usar la actual en la zona horaria
                let baseDate = new Date();

                // Usar Intl.DateTimeFormat para manejar zona horaria correctamente
                const formatter = new Intl.DateTimeFormat('en-CA', { // 'en-CA' = YYYY-MM-DD
                    timeZone,
                    year: 'numeric',
                    month: '2-digit',
                    day: '2-digit'
                });

                // Convertir baseDate a timestamp en la zona horaria
                const offsetMs = getTimezoneOffsetMs(baseDate, timeZone);
                const localDate = new Date(baseDate.getTime() + offsetMs);

                // Sumar los días
                localDate.setDate(localDate.getDate() + diasASumar);

                // Formatear resultado: YYYY-MM-DD
                return formatter.format(localDate);
            }

            // --- Función auxiliar: obtener offset de zona horaria ---
            function getTimezoneOffsetMs(date, timeZone) {
                const utcDate = new Date(Date.UTC(
                    date.getUTCFullYear(),
                    date.getUTCMonth(),
                    date.getUTCDate(),
                    date.getUTCHours(),
                    date.getUTCMinutes(),
                    date.getUTCSeconds()
                ));

                const formatter = new Intl.DateTimeFormat('en-US', {
                    timeZone,
                    year: 'numeric', month: 'numeric', day: 'numeric',
                    hour: 'numeric', minute: 'numeric', second: 'numeric',
                    hour12: false
                });

                const parts = formatter.formatToParts(utcDate);
                const values = {};
                parts.forEach(({ type, value }) => {
                    if (type !== 'literal') values[type] = parseInt(value, 10);
                });

                const localDate = new Date(Date.UTC(
                    values.year,
                    values.month - 1,
                    values.day,
                    values.hour,
                    values.minute,
                    values.second
                ));

                return localDate.getTime() - utcDate.getTime();
            }

            if(!isEmpty(getCRMPartnertAdmin))
            {
                if(getCRMPartnertAdmin != 1)
                {
                    //console.log("entramos a " +getCRMPartnertAdmin);

                    $("#editable_department").prop("disabled", true);
                    $("#editable_assigned_to").prop("disabled", true);
                    $("#editable_status").prop("disabled", true);
                }
            }

             
 
            try {
        
                if(!isEmpty(getListTicketsStatus))
                {
                    let parsearData = JSON.parse(getListTicketsStatus);

                    if (Array.isArray(parsearData)) {
                        arrayTicketsStatus = parsearData || [];
                       
                    }
                }

                if(!isEmpty(getListTicketsCategory))
                {
                    let parsearData = JSON.parse(getListTicketsCategory);

                    if (Array.isArray(parsearData)) {
                        arrayTicketsCategory = parsearData || [];
                       
                    }
                }
                

                //console.log("getstatus_id")
                //console.log(getstatus_id)

                if(!isEmpty(getstatus_id))
                {
                    $(".mi_field_status").val(getstatus_id);   
                }

                //console.log(arrayTicketsStatus)
                //console.log(arrayTicketsCategory)

                cargarPrincipal();


            } catch (error) {
                console.error('Error al parsear:', error);
            }


            $('#mi_field_status').on('change', function() {
                var valorSeleccionado = $(this).val();        // Valor (id)
                
                console.log("ID seleccionado: " + valorSeleccionado);
                 
                let findData = arrayTicketsStatus.find((data) => data.id == valorSeleccionado );

                if(findData)
                {
                    console.log("findData");
                    console.log(findData);

                    $(".expected_closing_date").val(sumarDiasConZonaHoraria(getTimeZone, findData.number_days))

                }else{
                    toastr.error("Error having record");
                }


            });

        
            $("#btn_add_category").on('click', function(e) {
                

                let input_category = $('#input_category').val();

                if(isEmpty(input_category)){
                    toastr.error("You must select an option");
                    return;
                }
 
                let information = {
                    tid: $('#tid').val(),
                    category_id: input_category,
                };
 
                $.post(base_url + 'tickets/admin/save_category', information)
                    .done(function (data) {

                    //console.log("data");
                    //console.log(data);
                    //return;

                    if(data.success)
                    {
                        toastr.success(_L['Saved Successfully']);

                        let option = "";

                        let listado = data.listado || []; 

                    

                        listado.forEach((data_v1) =>{
                            option += htmlItemCategory(data_v1);
                        });

                        if(isEmpty(option))
                        {
                            $(".containerCategory").html('<p style="text-align: center; font-weight: 600;">No information to show</p>');
                        }else{
                            $(".containerCategory").html(option);
                        }
        

                        eventDeleteCategory();

                    }else{
                        toastr.error(data.mesagge);
                    }   

                });

            });

             

            $("#btn_aplicar_ventana_confirmacion").off("click")
            .on("click", function () {

                console.log("se dio click");

                $('#btn_aplicar_ventana_confirmacion').prop('disabled', true);
                $('#btn_close_ventana_confirmacion').prop('disabled', true);
                $('#btn_cerrar_ventana_confirmacion').prop('disabled', true);
        
                let opcion_predefinida = $(".tipo_modal_confirmar").val();
                let data_id = $(".data_id").val();

                if(opcion_predefinida == "eliminar_card_documento")
                {
                    $(".mensaje_espera_moda_confirmacion").text("Please wait while the process finishes...");
                    //eliminarDocument(data_id);

                    let information = {
                        tid: $('#tid').val(),
                        category_id: data_id,
                    };
    
                    $.post(base_url + 'tickets/admin/delete_category', information)
                        .done(function (data) {

                        $('#btn_aplicar_ventana_confirmacion').prop('disabled', false);
                        $('#btn_close_ventana_confirmacion').prop('disabled', false);
                        $('#btn_cerrar_ventana_confirmacion').prop('disabled', false);
                        
                        ventanaRegistroExito("Record deleted", "¡The record has been successfully deleted!");

                        console.log("data");
                        console.log(data);
                        //return;

                        if(data.success)
                        {
                            toastr.success(_L['Saved Successfully']);
                            
                            let listado = data.listado || [];

                            //console.log("listado")
                            //console.log(listado)
                            
                            let option = "";
                            listado.forEach((data_v1) =>{
                                option += htmlItemCategory(data_v1);
                            });

                            if(isEmpty(option))
                            {
                                $(".containerCategory").html('<p style="text-align: center; font-weight: 600;">No information to show</p>');
                            }else{
                                $(".containerCategory").html(option);
                            }

                            eventDeleteCategory();

                        }else{
                            toastr.error("");
                        }   

                    });
                }

                
                
            
            });

            $("#btn_cerrar_ventana_confirmacion").off("click")
            .on("click", function () {
                
                $('#btn_aplicar_ventana_confirmacion').prop('disabled', false);
                $('#btn_close_ventana_confirmacion').prop('disabled', false);
                $('#btn_cerrar_ventana_confirmacion').prop('disabled', false);
                $("#ventana_confirmacion").modal("hide");
            
            });

            $("#btn_close_ventana_confirmacion").off("click")
            .on("click", function () {

                $('#btn_aplicar_ventana_confirmacion').prop('disabled', false);
                $('#btn_close_ventana_confirmacion').prop('disabled', false);
                $('#btn_cerrar_ventana_confirmacion').prop('disabled', false);
                
                $("#ventana_confirmacion").modal("hide");
            
            });

            $('.btn_cerrar_confirmacion_modal').click(function() {
                $("#modalMensaje").modal("hide");
            });

            $('.abrir_modal_contacto').click(function() {
                $("#modal_asignar_clientes_contactos").modal("show");
            });

            function ventanaRegistroExito(titulo, mensaje) {
                $(".titulo_modal_confirmar").text(titulo);
                $(".mensaje_modal_confirmar").text(mensaje);
                $(".mensaje_espera_moda_confirmacion").text("");
                $(".tipo_modal_confirmar").val("registro_exito");
                $(".data_id").val("");

                $('#btn_aplicar_ventana_confirmacion').prop('disabled', false);
                $('#btn_close_ventana_confirmacion').prop('disabled', false);
                $('#btn_cerrar_ventana_confirmacion').prop('disabled', false);
                
                $('#btn_cerrar_ventana_confirmacion').css({
                    //'background-color': COLOR_FONDO_VENTANA_CERRAR,
                    //'color': COLOR_TEXT_VENTANA_CERRAR
                });

                $('#btn_aplicar_ventana_confirmacion').css({
                    //'background-color': COLOR_FONDO_VENTANA_CONFIRMACION,
                    //'color': COLOR_TEXT_VENTANA_CONFIRMACION,
                    'display': "none"
                });
            
                $("#ventana_confirmacion").modal("show");
            }


        });

        function generateCardHtmlURL(data) {
            let {
                nombre_original,
                extension,
                UUID,
                UUID_ENC,
                url_crm,
                url,
                nombre_img_sistema
            } = data;

            // Sanitize inputs to prevent XSS
            const sanitize = (str) => {
                const div = document.createElement('div');
                div.textContent = str;
                return div.innerHTML;
            };

            if(!isEmpty(url_crm))
            {
                if (url_crm.endsWith('/')) {
                    url_crm = url_crm.slice(0, -1);
                }
            }

            const sanitizedId = sanitize(UUID_ENC);
            const sanitizedTipoArchivo = sanitize(extension);
            const sanitizedNameArchivo = sanitize(nombre_original);
            const sanitizedDownloadUrl = sanitize(url_crm + url + nombre_img_sistema);
            const sanitizedFileName = sanitizedNameArchivo || 'document.' + sanitizedTipoArchivo.toLowerCase();
 
            //'<button type="button" class="btn btn-sm btn-eliminar waves-effect waves-themed" data-id="' + sanitizedId + '">' +
            //    '<i class="fas fa-trash tamano-icono" aria-hidden="true"></i>' +
            //'</button>' +

            return '<div class="col-12 col-sm-12 pt-2 card_eliminar_' + sanitizedId + '">' +
                        '<div >' +
                            '<div class="card-body p-0">' +
                                '<h5 class="card-title">File type: <span class="card_tipo_archivo">' + sanitizedTipoArchivo + '</span></h5>' +
                                '<h5 class="card-title">File name: <span class="card_nombre_archivo">' + sanitizedNameArchivo + '</span></h5>' +
                                '<div class="row">' +
                                    '<div class="col-12">' +
                                         
                                        '<a class="btn btn-sm btn-descargar waves-effect waves-themed" ' +
                                        'data-id="' + sanitizedId + '" ' +
                                        'href="' + sanitizedDownloadUrl + '" ' +
                                        'target="_blank" ' +
                                        'download="' + sanitizedFileName + '">' +
                                            '<i class="fas fa-download tamano-icono" aria-hidden="true"></i>' +
                                        '</a>' +
                                    '</div>' +
                                '</div>' +
                            '</div>' +
                        '</div>' +
                    '</div><hr>';
                     
                     
        }

        function cargarPrincipal()
        {
            
            let data = {
                id: $('#tid').val(),
            };

            $.ajax({
                type: "POST",
                url: URL_BASE + "tickets/admin/get-list-tickets-category",
                data: JSON.stringify(data),
                contentType: "application/json", // Tipo de contenido JSON
                success: function (response) {
                    
                    //console.log("Respuesta del servidor:", response);
                    // Hacer algo con la respuesta del servidor
        
                    try {
                        let info = JSON.parse(response);

                        if (info.type == "success") {

                            let listado = info.listado || [];

                            console.log("listado")
                            console.log(listado)
 
                            let option = "";
                            listado.forEach((data) =>{
                                option += htmlItemCategory(data );
                            });

                            if(isEmpty(option))
                            {
                                $(".containerCategory").html('<p style="text-align: center; font-weight: 600;">No information to show</p>');
                            }else{
                                $(".containerCategory").html(option);
                            }

                            eventDeleteCategory();

                            let list_syssticketdocument = info.list_syssticketdocument || [];

                            let myOption = "";
                            list_syssticketdocument.forEach((data) =>{
                                myOption += generateCardHtmlURL(data);
                            })

                            $(".containerDocuments").html(myOption);


                        } else if (info.type == "error") {
                            Swal.fire({
                               icon: "error",
                               title: "Oops...",
                               text: info.message,
                            });
                        }

                    } catch (error) {
                        Swal.fire({
                           icon: "error",
                           title: "Oops...",
                           text: error,
                        });

                    }
                },
                error: function (xhr, status, error) {
                    console.error("Error en la solicitud:", error);
                    // Manejar errores aquí
                    Swal.fire({
                       icon: "error",
                       title: "Oops...",
                       text: error,
                    });

                },
            });

            
        }

        function eventDeleteCategory()
        {
            $(".btn_delete_category").on('click', function(e) {
            
                let id = $(this).data("id");

                console.log("id")
                console.log(id)

                if(isEmpty(id)){
                    toastr.error("Id is required");
                    return;
                }


                $(".titulo_modal_confirmar").text("You are sure?");
                $(".mensaje_modal_confirmar").text("Are you sure you want to delete this record?");
                $(".mensaje_espera_moda_confirmacion").text("");
                $(".tipo_modal_confirmar").val("eliminar_card_documento");
                $(".data_id").val(id);

                $("#ventana_confirmacion").modal("show");

                $('#btn_aplicar_ventana_confirmacion').prop('disabled', false);
                $('#btn_close_ventana_confirmacion').prop('disabled', false);
                $('#btn_cerrar_ventana_confirmacion').prop('disabled', false);

                //btn_aplicar_ventana_confirmacion

                $('#btn_aplicar_ventana_confirmacion').css({
                    //'background-color': COLOR_FONDO_VENTANA_CONFIRMACION,
                    //'color': COLOR_TEXT_VENTANA_CONFIRMACION,
                    'display': ""
                });


            });
        }

 
        Dropzone.autoDiscover = false;
        $(function() {

            var tid = {$d->id};

            $( ".mmnt" ).each(function() {
                var ut = $( this ).html();
                $( this ).html(moment.unix(ut).fromNow());
            });

            var _url = $("#_url").val();

            var $ib_form_submit = $("#ib_form_submit");

            var $create_ticket = $("#create_ticket");

            $('#clx_datatable').dataTable(
                {
                    "language": {
                        "emptyTable": "{$_L['No items to display']}",
                        "info":      "{$_L['Showing _START_ to _END_ of _TOTAL_ entries']}",
                        "infoEmpty":      "{$_L['Showing 0 to 0 of 0 entries']}",
                        buttons: {
                            pageLength: '{$_L['Show all']}'
                        },
                        searchPlaceholder: "{__('Search')}"
                    },
                }
            );


            $('#content').redactor({ 
                minHeight: 200,
            });

            var $modal = $('#cloudonex_body');

            var reply_type = 'public';


            var upload_resp;


            var ib_file = new Dropzone("#upload_container",
                {
                    url: _url + "tickets/client/upload_file_v1/",
                    maxFiles: 10,
                    acceptedFiles: "image/jpeg,image/png,image/gif"
                }
            );

            ib_file.on("sending", function() {

                $ib_form_submit.prop('disabled', true);

            });


            // Ticket convert to invoice

            $('#convertToInvoice').on('click',function (e) {
                e.preventDefault();

                app.confirm('Are you sure?', function (yes) {
                    if(yes)
                        {
                            window.location = '{$_url}invoices/create-from-ticket-v1/{$d->id}';
                        }
                });

            });


            ib_file.on("success", function(file,response) {

                $ib_form_submit.prop('disabled', false);


                console.log("response img");
                console.log(response);

                upload_resp = response;

                if(upload_resp.success == 'Yes'){

                    toastr.success(upload_resp.msg);
                    // $file_link.val(upload_resp.file);
                    // files.push(upload_resp.file);
                    //
                    // console.log(files);

                    $('#attachments').val(function(i,val) {
                        return val + (!val ? '' : ',') + upload_resp.file;
                    });

                    if(!isEmpty(response.base64))
                    {   
                        let information = {
                            base64: response.base64,
                            extension: response.extension,
                        };

                        arrayImageSticketReplies.push(information);
                    }
                    


                }
                else{
                    toastr.error(upload_resp.msg);
                }

 

            });



            $ib_form_submit.on('click', function(e) {
                e.preventDefault();
                
                let information = {  
                    message:     $('#content').val(), 
                    reply_type:  reply_type, 
                    attachments: $("#attachments").val(), 
                    f_tid:       $("#f_tid").val(),
                    arrayImageSticketReplies: JSON.stringify(arrayImageSticketReplies),
                    url_crm_administrativo:   url_crm_administrativo,
                };

                console.log("information")
                console.log(information);

                //return;
                //$create_ticket.block({ message: block_msg });

                $.post( _url + "tickets/admin/add_reply/", information )
                    .done(function( data ) {

                        console.log("response");
                        console.log(data);
                        //return;

                        if(data.success == "Yes"){
                            location.reload();
                        }
                        else {
                            $create_ticket.unblock();
                            toastr.error(data.msg);
                        }

                    });


            });


            $("#add_reply").on('click', function(e) {
                e.preventDefault();

                $('html, body').animate({
                    scrollTop: $("#section_add_reply").offset().top - 60
                }, 500);



            });

            $('#notes').redactor(
                {
                    minHeight: 150, // pixels
                    plugins: ['fontcolor']
                }
            );

            $("#btn_save_note").on('click', function(e) {
                e.preventDefault();

                let editable_assigned_to = $('#editable_assigned_to').val();

                if(editable_assigned_to == "None"){
                    toastr.error("You must select a user...");
                    return;
                }

                $('#t_options').block({ message: null });

                let information = {
                    tid: $('#tid').val(),
                    notes: $('#notes').val(),
                    status: $('#mi_field_status').val(),
                    expected_closing_date: $('#expected_closing_date').val(),
                };
 
                $.post(base_url + 'tickets/admin/save_note', information)
                    .done(function (data) {

                    //console.log("data");
                    //console.log(data);

                    if(data.success)
                    {
                        toastr.success(_L['Saved Successfully']);

                        $("#inline_status").html(data.status);

                        if($('#mi_field_status').val() == 5)
                        {
                            location.reload();
                        }

                    }else{
                        toastr.error("");
                    }   

                    $('#t_options').unblock();

                });

            });

            $(".cdelete").click(function (e) {
                e.preventDefault();
                var id = this.id;
                app.confirm(_L['are_you_sure'], function(result) {
                    if(result){
                        window.location.href = base_url + "tickets/admin/delete/" + id;
                    }
                });
            });


            $(".t_edit").click(function (e) {
                e.preventDefault();
                var id = this.id;


                $.fancybox.open({
                    src  : base_url + 'tickets/admin/edit_modal/'+id,
                    type : 'ajax',
                    opts : {
                        afterShow : function( instance, current ) {
                            $('#edit_content').redactor();
                        },
                        touch: false,
                        autoFocus: false,
                        keyboard: false,
                    }
                });

            });


            $(".reply_edit").click(function (e) {
                e.preventDefault();
                var id = this.id;

                $.fancybox.open({
                    src  : base_url + 'tickets/admin/edit_modal/'+id+'/reply',
                    type : 'ajax',
                    opts : {
                        afterShow : function( instance, current ) {
                            $('#edit_content').redactor();
                        },
                        touch: false,
                        autoFocus: false,
                    }
                });


            });



            $('[data-bs-toggle="tooltip"]').tooltip();

            // $modal.on('hidden.bs.modal', function () {
            //     location.reload();
            // });

            $modal.on('click', '.update_ticket_message', function(e){

                e.preventDefault();


                $.post( _url + "tickets/admin/edit_modal_post/", {
                    tid: $('#edit_tid').val(),
                    type: $('#edit_type').val(),
                    message:  $('#edit_content').val(),

                })
                    .done(function( data ) {

                        if ($.isNumeric(data)) {

                            location.reload();

                        }

                        else {

                            toastr.error(data);
                        }

                    });

            });


            $(".reply_delete").click(function (e) {
                e.preventDefault();
                var id = this.id;
                let uuid = $(this).data("uuid");

                app.confirm(_L['are_you_sure'], function(result) {
                    if(result){
                        window.location.href = base_url + "tickets/admin/delete_reply/" + uuid;
                    }
                });
            });


            $("#editable_cc").on("blur",function(e){
                $.post(base_url + 'tickets/admin/update_cc',{ id: tid, value: $(this).val()},function (data) {
                    if ($.isNumeric(data)) {

                        toastr.success('{$_L['Saved Successfully']}');

                    }

                    else {

                        toastr.error(data);
                    }
                })
            });


            $("#editable_bcc").on("blur",function(e){
                $.post(base_url + 'tickets/admin/update_bcc',{ id: tid, value: $(this).val()},function (data) {
                    if ($.isNumeric(data)) {

                        toastr.success('{$_L['Saved Successfully']}');

                    }

                    else {

                        toastr.error(data);
                    }
                })
            });


            $("#editable_email").on("blur",function(e){
                $.post(base_url + 'tickets/admin/update_email',{ id: tid, value: $(this).val()},function (data) {
                    if ($.isNumeric(data)) {

                        toastr.success('{$_L['Saved Successfully']}');

                    }

                    else {

                        toastr.error(data);
                    }
                })
            });


            $("#editable_phone").on("blur",function(e){
                $.post(base_url + 'tickets/admin/update_phone',{ id: tid, value: $(this).val()},function (data) {
                    if ($.isNumeric(data)) {

                        toastr.success('{$_L['Saved Successfully']}');

                    }

                    else {

                        toastr.error(data);
                    }
                })
            });


            $("#editable_hour").on("blur",function(e){
                $.post(base_url + 'tickets/admin/update_hour',{ id: tid, value: $(this).val()},function (data) {
                    if ($.isNumeric(data)) {

                        toastr.success('{$_L['Saved Successfully']}');

                    }

                    else {

                        toastr.error(data);
                    }
                })
            });

            $("#editable_minute").on("blur",function(e){
                $.post(base_url + 'tickets/admin/update_minute',{ id: tid, value: $(this).val()},function (data) {
                    if ($.isNumeric(data)) {

                        toastr.success('{$_L['Saved Successfully']}');

                    }

                    else {

                        toastr.error(data);
                    }
                })
            });


            $("#editable_department").on("change",function(e){
                $.post(base_url + 'tickets/admin/update_department',{ id: tid, value: $(this).val()},function (data) {

                    //console.log("data");
                    //console.log(data);

                    if(data.success)
                    {
                        toastr.success('{$_L['Saved Successfully']}');
                    }else{
                        toastr.error(data.mesagge);
                    }
 
                })
            });


            $('#editable_assigned_to').select2({

            })
                .on("change", function (e) {

                    $.post(base_url + 'tickets/admin/update_assigned_to',{
                        id: {$d->id}, value: $("#editable_assigned_to option:selected").val()
                    },function (data) {

                        console.log("data")
                        console.log(data)

                        if(data.success)
                        {
                            toastr.success('{$_L['Saved Successfully']}');
                        }else{
                            toastr.error(data.mesagge);
                        }

                        /*
                        if ($.isNumeric(data)) {

                            toastr.success('{$_L['Saved Successfully']}');
                        }
                        else {
                            toastr.error(data);
                        }
                        */
                    })
                });


            // $("#editable_assigned_to").on("change",function(e){
            //
            // });

            $("#editable_status").on("change",function(e){
                $.post(base_url + 'tickets/admin/update_status',{ id: tid, value: $(this).val()},function (data) {
                    if ($.isNumeric(data)) {

                        toastr.success('{$_L['Saved Successfully']}');

                        $("#inline_status").html($("#editable_status option:selected").text());

                    }

                    else {

                        toastr.error(data);
                    }
                })
            });





            var $reply_public = $("#reply_public");
            var $reply_internal = $("#reply_internal");


            $reply_public.click(function (e) {
                e.preventDefault();
                $(this).addClass('active');
                $reply_internal.removeClass('active');
                reply_type = 'public';
                $('#content').closest('.redactor-box').find('.redactor-editor').css({
                    backgroundColor: '#FFFFFF'
                });
            });


            $reply_internal.click(function (e) {
                e.preventDefault();
                $(this).addClass('active');
                $reply_public.removeClass('active');
                reply_type = 'internal';
                $('#content').closest('.redactor-box').find('.redactor-editor').css({
                    backgroundColor: '#FFF6D9'
                });
            });


            $(".reply_make_public").click(function (e) {
                e.preventDefault();
                var id = this.id;
                let uuid = $(this).data("uuid");

                app.confirm(_L['are_you_sure'], function(result) {
                    if(result){
                        window.location.href = base_url + "tickets/admin/reply_make_public/" + uuid;
                    }
                });
            });

            function loadTasks() {

                $("#tasks_list").html(block_msg);

                $.get( base_url + "tickets/admin/tasks_list/{$ticket->id}", function( data ) {

                    $("#tasks_list").html(data);



                    $('.task-checkbox').on('change', function (event) {


                        var i_check_id = $(this)[0].id;

                        if($(this)[0].checked){

                            $.get(base_url + 'tickets/admin/set_task_completed/'+i_check_id,function () {
                                loadTasks();
                            });

                        }
                        else{

                            $.get(base_url + 'tickets/admin/set_task_not_started/'+i_check_id,function () {
                                loadTasks();
                            });

                        }

                    });

                });
            }


            loadTasks();


            $("#btn_add_task").click(function (e) {
                e.preventDefault();


                if($("#task_subject").val() == ''){

                    $("#task_subject").focus();

                }

                else {

                    $("#btn_add_task").prop('disabled', true);

                    $.post( base_url + "tasks/post/", { title: $("#task_subject").val(), rel_type: 'Ticket', tid: '{$ticket->id}', rel_id: '{$ticket->id}', cid: {$ticket->userid}, priority: '{$ticket->urgency}' })
                        .done(function( data ) {

                            $("#btn_add_task").prop('disabled', false);

                            if ($.isNumeric(data)) {

                                $("#task_subject").val('');

                                loadTasks();

                            }
                            else{
                                toastr.error(data);
                            }

                        });

                }
            });

            var task_id;

            function has_selected_task_items() {
                if($('.selected').length > 0){

                    $("#tasks_tools").show(200);

                }
                else{
                    $("#tasks_tools").hide(200);
                }
            }

            $("#tasks_list").on('click', '.task_item', function () {

                task_id = this.id;



                if($("#" + task_id).hasClass('selected')){
                    $("#" + task_id).removeClass('selected');
                }
                else{
                    $("#" + task_id).addClass('selected');
                }

                has_selected_task_items();


                // alert(task_id);


            });

            $("#btn_mark_tasks_completed").on('click',function (e) {
                e.preventDefault();
                var arrayOfIds = $.map($(".selected"), function(n, i){
                    return n.id;
                });

                $("#btn_mark_tasks_completed").prop('disabled', true);

                $.post( base_url + "tickets/admin/do_task/", { action: 'completed', ids: arrayOfIds })
                    .done(function( data ) {

                        $("#btn_mark_tasks_completed").prop('disabled', false);

                        loadTasks();

                        $("#tasks_tools").hide(200);

                    });

            });


            $("#btn_mark_tasks_not_started").on('click',function (e) {
                e.preventDefault();
                var arrayOfIds = $.map($(".selected"), function(n, i){
                    return n.id;
                });

                $("#btn_mark_tasks_completed").prop('disabled', true);

                $.post( base_url + "tickets/admin/do_task/", { action: 'not_started', ids: arrayOfIds })
                    .done(function( data ) {

                        $("#btn_mark_tasks_completed").prop('disabled', false);

                        loadTasks();

                        $("#tasks_tools").hide(200);

                    });

            });


            $("#btn_delete_tasks").on('click',function (e) {
                e.preventDefault();

                app.confirm(_L['are_you_sure'], function(result) {
                    if(result){
                        var arrayOfIds = $.map($(".selected"), function(n, i){
                            return n.id;
                        });

                        $("#btn_delete_tasks").prop('disabled', true);

                        $.post( base_url + "tickets/admin/do_task/", { action: 'delete', ids: arrayOfIds })
                            .done(function( data ) {

                                $("#btn_delete_tasks").prop('disabled', false);

                                loadTasks();

                                $("#tasks_tools").hide(200);

                            });
                    }
                });



            });





        });

        function setPreDefinedContent(event,predefined_reply_id) {

            $('#modal_predefined_replies').modal('hide');

            $.get( "{$_url}tickets/admin/get-predefined-reply/" + predefined_reply_id, function( data ) {

                $('#content').redactor('code.set', data);

            });

        }

        window.addEventListener('DOMContentLoaded', () => {
            const btn_generate_reply = document.getElementById('btn_generate_reply');

            if(!isEmpty(btn_generate_reply))
            {
                btn_generate_reply.addEventListener('click', () => {

                    btn_generate_reply.disabled = true;
                    btn_generate_reply.innerHTML = '<i class="fal fa-spinner fa-spin"></i> {__('Generating')}...';
                    let generate_reply_form = new FormData();
                    generate_reply_form.append('ticket_id', {$ticket->id});
                    axios.post('{$base_url}tickets/admin/generate-reply', generate_reply_form).then(function (response) {
                        $('#content').redactor('code.set', response.data);
                        btn_generate_reply.disabled = false;
                        btn_generate_reply.innerHTML = '{__('Generate Reply')}';
                    }).catch(function (error) {
                        console.log(error);
                        btn_generate_reply.disabled = false;
                        btn_generate_reply.innerHTML = '{__('Generate Reply')}';
                    });

                });
            }

             
        });

        function htmlItemCategory(data) {
            let {
                sys_tickets_category_name,
                id
            } = data;


            //console.log("getCRMPartnertAdmin")
            //console.log(getCRMPartnertAdmin)
            //console.log("getstatus_id")
            //console.log(getstatus_id)
 
            if(getCRMPartnertAdmin == 1 && getstatus_id != 5 )
            {
                return '<div class="d-flex justify-content-between align-items-center mb-2">' +
                        '<div class="text-start flex-fill me-2" style="word-break: break-word; overflow-wrap: break-word;">' +
                            '<strong>' + sys_tickets_category_name + '</strong>' +
                        '</div>' +
                        '<div>' +
                            '<button class="btn btn-danger btn-sm btn_delete_category" data-id="' + id + '" type="button">' +
                                '<i class="fal fa-trash-alt"></i>' +
                            '</button>' +
                        '</div>' +
                    '</div>' +
                    '<hr class="my-1">';
            }else{

                if(getCRMPartnertAdmin == 1 && getstatus_id == 5)
                {
                    return '<div class="d-flex justify-content-between align-items-center mb-2">' +
                                '<div class="text-start flex-fill me-2" style="word-break: break-word; overflow-wrap: break-word;">' +
                                    '<strong>' + sys_tickets_category_name + '</strong>' +
                                '</div>' +
                            '</div>' +
                            '<hr class="my-1">';
                }else{

                     return '<div class="d-flex justify-content-between align-items-center mb-2">' +
                                '<div class="text-start flex-fill me-2" style="word-break: break-word; overflow-wrap: break-word;">' +
                                    '<strong>' + sys_tickets_category_name + '</strong>' +
                                '</div>' +
                            '</div>' +
                            '<hr class="my-1">';

                }

            }

             
        }

    </script>
{/block}
