{include file="header.html"}
<ul class="nav nav-tabs mb-1" role="tablist">
	<li class="nav-item">
		<a class="nav-link active" data-toggle="tab" href="#tab-billings" role="tab">{trans("Billings")}</a>
	</li>
	<li class="nav-item">
		<a class="nav-link" data-toggle="tab" href="#tab-settings" role="tab">{trans("Settings")}</a>
	</li>
</ul>
<div class="tab-content">
	<div class="tab-pane active" id="tab-billings" role="tab-panel">
		<FORM METHOD="GET" ACTION="?m=voip" class="form-inline">
			<INPUT TYPE="HIDDEN" NAME="m" VALUE="voip">
			<input type="hidden" id="mode" name="mode" value="billing">
			<div class="form-group">
				<label for="phonelabel" class="m-2">
					{if count($customer_phone_list) > 1}
						{trans("My phones:")}
					{else}
						{trans("My number:")}
					{/if}
				</label>
				{if count($customer_phone_list) > 1}
					<SELECT NAME="phone" CLASS="form-control" id="phonelabel">
						<OPTION VALUE="0">{trans("— all —")}</OPTION>
							{foreach $customer_phone_list as $phone}
							<OPTION VALUE="{$phone}"{if $params.phone == $phone} SELECTED{/if}>{$phone}</OPTION>
							{/foreach}
					</SELECT>
				{else if count($customer_phone_list) == 1}
					{assign var=tmp value=array_values($customer_phone_list)}

					<input type="text" class="form-control" disabled value="{$tmp[0]}">
				{else}
					<input type="text" class="form-control" disabled value="&ndash;&ndash;&ndash;">
				{/if}
			</div>
			<div class="form-group">
				<label for="exampleInputName2" class="m-2">
					{trans("Date range:")}
				</label>
				{date_period_preset from="#datefrom" to="#dateto"}
				<label for="datefrom">
					{trans("from")}
				</label>
				<INPUT TYPE="text" id="datefrom" NAME="date_from" CLASS="lms-ui-date form-control m-1" VALUE="{if isset($params.frangefrom)}{$params.frangefrom}{/if}">
				<label class="ml-2" for="dateto">
					{trans("to")}
				</label>
				<INPUT TYPE="text" id="dateto" NAME="date_to" CLASS="lms-ui-date form-control m-1" VALUE="{if isset($params.frangeto)}{$params.frangeto}{/if}">
			</div>
			<div class="form-group">
				<label for="fdirection" class="m-2">
					{trans("<!voip>Direction")}
				</label>
				<select name="fdirection" id="fdirection" class="form-control">
					<option value="0">{trans("— all —")}</option>
					<option value="{$smarty.const.BILLING_RECORD_DIRECTION_INCOMING}"
						{if $params.fdirection == $smarty.const.BILLING_RECORD_DIRECTION_INCOMING} selected{/if}>{trans("<!voip>incoming")}</option>
					<option value="{$smarty.const.BILLING_RECORD_DIRECTION_OUTGOING}"
						{if $params.fdirection == $smarty.const.BILLING_RECORD_DIRECTION_OUTGOING} selected{/if}>{trans("<!voip>outgoing")}</option>
				</select>
			</div>
			<div class="form-group">
				<label for="ftype" class="m-2">
					{trans("<!voip>Type")}
				</label>
				<select name="ftype" id="ftype" class="form-control">
					<option value="">{trans("— all —")}</option>
					<option value="{$smarty.const.BILLING_RECORD_TYPE_VOICE_CALL}"
						{if is_numeric($params.ftype) && $params.ftype == $smarty.const.BILLING_RECORD_TYPE_VOICE_CALL} selected{/if}>{trans("<!voip>voice call")}</option>
					<option value="{$smarty.const.BILLING_RECORD_TYPE_VIDEO_CALL}"
						{if is_numeric($params.ftype) && $params.ftype == $smarty.const.BILLING_RECORD_TYPE_VIDEO_CALL} selected{/if}>{trans("<!voip>video call")}</option>
					<option value="{$smarty.const.BILLING_RECORD_TYPE_SMS}"
						{if $params.ftype == $smarty.const.BILLING_RECORD_TYPE_SMS} selected{/if}>{trans("<!voip>SMS")}</option>
					<option value="{$smarty.const.BILLING_RECORD_TYPE_MMS}"
						{if $params.ftype == $smarty.const.BILLING_RECORD_TYPE_MMS} selected{/if}>{trans("<!voip>MMS")}</option>
					<option value="{$smarty.const.BILLING_RECORD_TYPE_DATA_TRANSFER}"
						{if $params.ftype == $smarty.const.BILLING_RECORD_TYPE_DATA_TRANSFER} selected{/if}>{trans("<!voip>data transfer")}</option>
				</select>
			</div>
			<div class="form-group">
				<label for="fstatus" class="m-2">
					{trans("<!voip>Status")}
				</label>
				<select name="fstatus" id="fstatus" class="form-control">
					<option value="0">{trans("— all —")}</option>
					<option value="{$smarty.const.BILLING_RECORD_STATUS_ANSWERED}"
						{if $params.fstatus == $smarty.const.BILLING_RECORD_STATUS_ANSWERED} selected{/if}>{trans("answered")}</option>
					<option value="{$smarty.const.BILLING_RECORD_STATUS_NO_ANSWER}"
						{if $params.fstatus == $smarty.const.BILLING_RECORD_STATUS_NO_ANSWER} selected{/if}>{trans("no answer")}</option>
					<option value="{$smarty.const.BILLING_RECORD_STATUS_BUSY}"
						{if $params.fstatus == $smarty.const.BILLING_RECORD_STATUS_BUSY} selected{/if}>{trans("<!voip>busy")}</option>
					<option value="{$smarty.const.BILLING_RECORD_STATUS_SERVER_FAILED}"
						{if $params.fstatus == $smarty.const.BILLING_RECORD_STATUS_SERVER_FAILED} selected{/if}>{trans("server error")}</option>
                    <option value="{$smarty.const.BILLING_RECORD_STATUS_UNKNOWN}"
                            {if $params.fstatus == $smarty.const.BILLING_RECORD_STATUS_UNKNOWN} selected{/if}>{trans("unknown")}</option>
				</select>
			</div>
			{button type="submit" id="billing" class="btn btn-danger m-2" icon="search" label="Search"}
			{button type="submit" id="minibilling" class="btn btn-secondary m-2" icon="phone" label="Minibilling"}
		</FORM>
		<table class="table table-sm table-condensed">
			<TR>
				{assign var=pagin_result value=$pagination->getPages()}
				{if count($pagin_result.pages) > 1}
					<TD CLASS="lms-ui-pagination text-center" COLSPAN="100%" STYLE="padding:10px 0;">
						{include file="pagination.html"}
					</TD>
				{else}
					<TD COLSPAN="100%" STYLE="padding:10px 0;"></TD>
					{/if}
			</TR>
		</table>
		{box title="Billing list"}
		{if $billings}
			<TABLE CLASS="table table-striped table-sm table-condensed">
				<thead>
					<TR>
						<th>{trans("Date")}</th>
						<th>{trans("Caller:")}</th>
						<th>{trans("Callee:")}</th>
						<th>{trans("<!voip>Total time")}</th>
						<th>{trans("<!voip>Billed time")}</th>
						<th>{trans("<!voip>Direction")}</th>
						<th>{trans("<!voip>Type")}</th>
						<th>{trans("<!voip>Status")}</th>
						<th>{trans("Price:")}</th>
						<th>{trans("Others:")}</th>
					</TR>
				</thead>
				{section name=i loop=$billings start=(($pagination->getCurrentPage()-1)*$pagination->getItemsPerPage()) max=$pagination->getItemsPerPage()}
					<TR>
						<TD>{$billings[i].begintime|date_format:"Y-m-d H:i:s"}</TD>
						<TD>{$billings[i].caller}</TD>
						<TD>{$billings[i].callee}</TD>
						<td>
							{if $billings[i].type == $smarty.const.BILLING_RECORD_TYPE_VOICE_CALL}
								{$billings[i].totaltime|duration_format}
							{else}
								-
							{/if}
						</td>
						<td>
							{if $billings[i].type == $smarty.const.BILLING_RECORD_TYPE_VOICE_CALL}
								{$billings[i].billedtime|duration_format}
							{elseif $billings[i].type == $smarty.const.BILLING_RECORD_TYPE_DATA_TRANSFER}
								{$billings[i].billedtime|size_format}
							{else}
								-
							{/if}
						</td>
						<td colspan="2">
							{if $billings[i].type == $smarty.const.BILLING_RECORD_TYPE_DATA_TRANSFER}
								{trans("<!voip>data transfer")}
							{elseif $billings[i].direction == $smarty.const.BILLING_RECORD_DIRECTION_OUTGOING}
								{if $billings[i].type == $smarty.const.BILLING_RECORD_TYPE_VOICE_CALL}
									{trans("<!voip>outgoing call")}
								{elseif $billings[i].type == $smarty.const.BILLING_RECORD_TYPE_SMS}
									{trans("<!voip>outgoing SMS")}
								{elseif $billings[i].type == $smarty.const.BILLING_RECORD_TYPE_MMS}
									{trans("<!voip>outgoing MMS")}
								{/if}
							{elseif $billings[i].direction == $smarty.const.BILLING_RECORD_DIRECTION_INCOMING}
								{if $billings[i].type == $smarty.const.BILLING_RECORD_TYPE_VOICE_CALL}
									{trans("<!voip>incoming call")}
								{elseif $billings[i].type == $smarty.const.BILLING_RECORD_TYPE_SMS}
									{trans("<!voip>incoming SMS")}
								{elseif $billings[i].type == $smarty.const.BILLING_RECORD_TYPE_MMS}
									{trans("<!voip>incoming MMS")}
								{/if}
							{/if}
						</td>
						<TD>
							{if $billings[i].status == $smarty.const.BILLING_RECORD_STATUS_BUSY}
								{trans("<!voip>busy")}
							{elseif $billings[i].status == $smarty.const.BILLING_RECORD_STATUS_ANSWERED}
								{trans("answered")}
							{elseif $billings[i].status == $smarty.const.BILLING_RECORD_STATUS_NO_ANSWER}
								{trans("no answer")}
							{elseif $billings[i].status == $smarty.const.BILLING_RECORD_STATUS_SERVER_FAILED}
								{trans("server error")}
                            {elseif $billings[i].status == $smarty.const.BILLING_RECORD_STATUS_UNKNOWN}
                                {trans("unknown")}
							{/if}
						</TD>
						<TD>{$billings[i].price|money_format}</TD>
						<TD STYLE="text-align: right; color: black;">
							{if !empty($billings[i].billedtime)}
								{if $billings[i].direction == $smarty.const.BILLING_RECORD_DIRECTION_OUTGOING}
									{assign var=flags value=$billings[i].caller_flags}
								{elseif $billings[i].direction == $smarty.const.BILLING_RECORD_DIRECTION_INCOMING}
									{assign var=flags value=$billings[i].callee_flags}
								{else}
									{assign var=flags value=0}
								{/if}
								{if $flags & $smarty.const.VOIP_ACCOUNT_FLAG_CUSTOMER_RECORDING}
									{documentview id="{$billings[i].id}"
										type="audio/mp3"
										name="{trans("ID:")} {$billings[i].id}, {trans("Date:")} {$billings[i].begintime|date_format:"Y-m-d H:i:s"}"
										url="?m=voip&record={$billings[i].id}"
										text="<span class=\"ui-icon ui-icon-volume-on\"></span>"}
								{/if}
							{/if}
						</TD>
					</TR>
				{/section}
				<TR>
					{assign var=pagin_result value=$pagination->getPages()}
					{if count($pagin_result.pages) > 1}
						<TD CLASS="lms-ui-pagination text-center" COLSPAN="100%" STYLE="padding:10px 0;">
							{include file="pagination.html"}
						</TD>
					{else}
						<TD COLSPAN="100%" STYLE="padding:10px 0;"></TD>
						{/if}
				</TR>
			</TABLE>
		{else}
			<div class="alert alert-info">{trans("No such data for selected period.")}</div>
		{/if}
		{/box}
	</DIV>
	<div class="tab-pane" id="tab-settings" role="tabpanel">
		<div class="mt-2 form-group form-inline">
			{if is_array($user_accounts) && count($user_accounts) > 1}
				<select id="account-select" class="form-control mr-2">
					<option value="0">{trans("Select account")}</option>
					{foreach $user_accounts as $acc}
						<option value="{$acc.id}">{$acc.login}</option>
					{/foreach}
				</select>
			{/if}
		</div>
		<div class="form-group">
			<div class="custom-control custom-control-inline" title="{trans("You can turn on/off record of your phone calls. Recordings can listen in 'billings' tab.")}">
				{trans("Call recording")}:
			</div>
			<div class="custom-control custom-radio custom-control-inline">
				<input class="custom-control-input" type="radio" name="callrecording" id="callrecordyes" value="1" checked>
				<label class="custom-control-label" for="callrecordyes">
					{trans("yes")}
				</label>
			</div>
			<div class="custom-control custom-radio custom-control-inline">
				<input class="custom-control-input" type="radio" name="callrecording" id="callrecordno" value="0">
				<label class="custom-control-label" for="callrecordno">
					{trans("no")}
				</label>
			</div>
		</div>
		{if is_array($user_accounts) && count($user_accounts) > 1}
			<span class="font-weight-bold" data-toggle="tooltip" data-placement="top" title="{trans("Change indexes for phones assigned to your account.")}">{trans("Assigned phones")}:</span>
			<ul id="customer-phones">
				<ol id="phones-sortable" class="userpanel-phones-sortable"></ol>
			</ul>
		{/if}
		{button id="save-settings" class="btn btn-danger" icon="save" label="Save"}
	</div>
</div>
{if $user_accounts}
<script>
    $( function() {
	    $('[data-toggle="tooltip"]').tooltip();

        {if count($user_accounts) == 1}
            {assign var=useracc value=reset($user_accounts)}
            updateRecordingRadioBtn( {$useracc.flags} );
        {/if}

        $( "#tabs" ).tabs();

        $( ".userpanel-phones-sortable" ).sortable({
            axis: 'y'
        });
        $( ".userpanel-phones-sortable" ).disableSelection();

        $( '#account-select' ).change( function() {
            var accid = $( this ).val();

            if ( accid != 0 ) {
                $.ajax({
                    method: "POST",
                    url: "?m=voip&action=getaccountinfo",
                    data: { "accid" : accid },
                })
                .done(function(data) {
                    if ( !data ) {
                        return 0;
                        console.log( 'error' );
                    }

                    var parsed_data = JSON.parse(data);

                    $( '.userpanel-phones-sortable' ).empty();

                    updateRecordingRadioBtn( parsed_data[0]['flags'] );

                    if (parsed_data.length > 1) {
                        $( '#customer-phones' ).css('display', 'table-row');
                        $.each(parsed_data, function( k, v ) {
                            $("#phones-sortable").append('<li>' + v['phone'] + '</li>');
                        });
                    } else {
                        $( '#customer-phones' ).css('display', 'none');
                    }

                    $( '.settings-tab tbody' ).css('display', 'table-row-group');
                });
            } else {
                $( '.settings-tab tbody' ).css('display', 'none');
            }
        });

        $( '#save-settings' ).click( function() {
            var save_btn = $( this );
            save_btn.attr( 'disabled', true );
            $( '#updateacc-status' ).stop()
                                    .css( 'color', 'black' )
                                    .text( "{trans("Loading")}..." )
                                    .fadeIn();

            var phones = [];
            $.each( $( '.userpanel-phones-sortable' ).children(), function() {
                phones.push( $(this).text() );
            });

            $.ajax({
                method: "POST",
                url: "?m=voip&action=updateaccountinfo",
                data: { "voipaccid" : {if count($user_accounts) > 1}$( '#account-select' ).val(){else}{$useracc['id']}{/if},
                        "recording" : $('input[name=callrecording]:checked').val(),
                        "phones"    : phones }
            })
            .done(function(data) {
                if ( !data ) {
                    $( '#updateacc-status' ).text( "Problem occurred" ).css( 'color', '#900000' ).fadeOut(5000);

                    console.log( 'Update failed.' );
                    return 0;
                }

                $( '#updateacc-status' ).text( "{trans("Saved")}" ).css( 'color', '#004d1a' ).fadeOut(5000);
                console.log( 'Update success.' );
                save_btn.attr( 'disabled', false );
            });
        });

        $('#billing,#minibilling').click(function() {
            var btn = $(this);
            $('#mode').val(btn.attr('id'));
            btn.closest('form').attr('target', function() {
                return btn.is('#minibilling') ? '_blank' : null;
            }).submit();
        });

        /*
         * \brief Function check/uncheck radio button responsibility for customer call recordings.
         *
         * \param  int/string customer flags
         */
        function updateRecordingRadioBtn( flags ) {
            if (flags & {$smarty.const.VOIP_ACCOUNT_FLAG_CUSTOMER_RECORDING}) {
                $( '#callrecordyes' ).prop( 'checked', true );
            } else {
                $( '#callrecordno' ).prop( 'checked', true );
            }
        }
    } );
</script>
{/if}
{include file="footer.html"}
