<?php
require_once ROOT_FOLDER .FOLDER. "/config/autoload.php";

function billing_invoice_det_header(){
		global $id;

		if (is_numeric($id)) {
			$show = '';
		} else {
			$show = ' d-none ';
		}
		
    $reto = '
        <br>
        <div class="row mb-0 '.$show.'">
            <div class="col-12">
                <div class="card mb-3">
                    <div class="card-header py-3 " >
						<div class="row">
							<div class="col-6 text-left">
								<p class="text-white m-0 font-weight-bold">Extra Menu</p>						
							</div>
							<div class="col-6 text-right">
								<p class="text-white m-0 font-weight-bold">BILL <span>'.$id.'</span></p>					
							</div>
						</div>   
                    </div>   
                    <div class="card" >
                        <div class="row m-3">
                            <div class="col-auto m-2 text-center">
                                <a href="" data-toggle="modal" data-target="#invoice_detailsPDF-modal" aria-hidden="true">                              
                                    <i class="fa fa-file-pdf-o fa-2x" style="color:  #20B2AA;"></i>
                                    <div class="text-white">Bill PDF</div>
                                </a>
                            </div>
                            <div class="col-auto m-2 text-center">
                                <a href="/apps/billing/cp/edit_invoice_det?hidemenu=1&invoice_no=' . $id . '">
                                     <i class="fas fa-edit fa-2x" style ="color:var(--cms-primary-color);"></i>
                                    <div class="text-white">Edit</div>
                                </a>
                            </div>
                            <div class="col-auto m-2 text-center">
                                <a href="" data-toggle="modal" data-target="#invoice_detailsPDFSHIP-modal" aria-hidden="true" onclick="show_shiplabels();">                              
                                    <i class="fas fa-shipping-fast fa-2x" style="color: #FFA500;"></i>
                                    <div class="text-white">Shipping Labels</div>
                                </a>
                            </div>
                        </div>                                
                    </div>			
                </div>
            </div>
        </div>
        
        <!-- Modal -->
        <div class="modal fade" id="invoice_detailsPDF-modal" style="height:100vh;padding-top: 100px;" tabindex="-1" role="dialog" aria-labelledby="invoice_detailsPDFLabel" aria-hidden="true">
            <div class="modal-dialog" style="max-width: 2000px;" role="document">    
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="invoice_detailsPDFLabel">
                            Invoice: ' . $id . '
                        </h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                    </div>
                    <div class="modal-body" style="height:90vh">
                        <iframe class="mt-2" id="myFrameinvoice_details" style="width:100%;height:100%;" src="/apps/billing/cp/pdf?id=' . $id . '" title="invoice_details"></iframe>                                      
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>                
                    </div>
                </div>    
            </div>
        </div>	
        
        <!-- Modal -->
        <div class="modal fade" id="invoice_detailsPDFSHIP-modal" style="height:100vh;padding-top: 100px;" tabindex="-1" role="dialog" aria-labelledby="invoice_detailsPDFSHIPLabel" aria-hidden="true">
            <div class="modal-dialog" style="max-width: 2000px;" role="document">    
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="invoice_detailsPDFSHIPLabel">
                            Invoice: ' . $id . '
                        </h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">×</span>
                        </button>
                    </div>
                    <div class="modal-body" style="height:90vh">
							<div class="row img-fluid " id="loadingIcon">
                                <div class="col">
                                     <img class="rounded mx-auto d-block" src="/images/loader.gif" style=" height: 400px;width:auto;">
                                </div>
                            </div>
					
                        <iframe class="mt-2" id="myFrameinvoice_shiplabels" style="width:100%;height:100%;"  title="invoice_labels"></iframe>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>                
                    </div>
                </div>    
            </div>
        </div>
		
		<script>
      function show_shiplabels(){
          $("#myFrameinvoice_shiplabels").hide();';
            
			if ($id!='new')
				$reto.=	'var invoiceId = '.$id.';';
			else			
				$reto.=	'var invoiceId = 0;';
			
            $reto.='
			var frameSrc = "/apps/billing/cp/invoices-labels-pdf?id=" + invoiceId;
            $("#myFrameinvoice_shiplabels").attr("src", frameSrc);
			
			   // Show loading icon while content loads
        $("#loadingIcon").show();

        // Hide loading icon once the iframe finishes loading
        $("#myFrameinvoice_shiplabels").on("load", function () {
            $("#loadingIcon").hide();
			$("#myFrameinvoice_shiplabels").show();
        });

        
    };
</script>

    ';
    return $reto;
}

function billing_invoice_det_footer(){
    $reto ="
    
    <script>
    $(document).ready(function() {
        // Listen for the modal close event
        $('.modal').on('hidden.bs.modal', function() {   if(this.id!='myModalDeletionConfirm' && this.id!='myModalHelp' )
                location.reload(); // Refresh the page
        });
    });
    </script>


    <script>
	 $(document).ready(function() {
    // Create a new list item element
var newListItem = document.createElement('li');
newListItem.classList.add('nav-item');

// Create a new button element
var newButton = document.createElement('button');
newButton.classList.add('nav-link');
newButton.id = 'Billing_PDF-tab';
newButton.setAttribute('data-toggle', 'tab');
newButton.setAttribute('data-target', '#Billing_PDF-tab-child');
newButton.type = 'button';
newButton.setAttribute('role', 'tab');
newButton.setAttribute('aria-controls', 'Billing_pdf');
newButton.setAttribute('aria-selected', 'true');
newButton.textContent = 'Pdf';

// Append the button to the list item
newListItem.appendChild(newButton);

// Find the parent element (ul) and insert the new list item after \"Billing_Payment-tab\"
var parentElement = document.getElementById('myTab');
var billingPaymentTab = document.getElementById('Billing_Payment-tab').parentNode;
parentElement.insertBefore(newListItem, billingPaymentTab.nextSibling);
	 
	 
	 
	 // Get the value of the 'id' parameter from the hidden item
var idParameter = document.getElementById('id').value;

// Create a new div element for the tab pane
var newTabPane = document.createElement('div');
newTabPane.classList.add('tab-pane', 'fade');
newTabPane.id = 'Billing_PDF-tab-child';
newTabPane.setAttribute('role', 'tabpanel');
newTabPane.setAttribute('aria-labelledby', 'Billing_Payment-tab');

// Create an iframe element
var newIframe = document.createElement('iframe');
newIframe.classList.add('mt-2');
newIframe.id = 'myFrameinvoice_details';
newIframe.style.width = '100%';
newIframe.style.height = '1000px';
newIframe.src = '/apps/billing/cp/pdf?id=' + idParameter + '&view=FitH';
newIframe.title = 'invoice_details';

// Append the iframe to the div
newTabPane.appendChild(newIframe);

// Find the parent element (div with id 'myTabContent') and append the new tab pane
var parentElement = document.getElementById('myTabContent');
parentElement.appendChild(newTabPane);

	 
	 }	)
    </script>

    <script>



    sta=$('#status');
    if (sta.val()=='CLOSED') {
       
       $('#client_id').prop(\"disabled\", true);
       $('#status').prop(\"disabled\", true);
       $('#po_no').prop(\"readonly\", true); 
       $('#ref_no').prop(\"disabled\", true);

       $('#issue_date').prop(\"readonly\", true);
       $('#issue_date').removeClass(\"hasDatepicker\");
       $('#issue_date').removeClass(\"datepicker\");
       $('#issue_date' ).datepicker( \"destroy\" )

       $('#paid_date').prop(\"readonly\", true);
       $('#paid_date').removeClass(\"hasDatepicker\");
       $('#paid_date').removeClass(\"datepicker\");
       $('#paid_date' ).datepicker( \"destroy\" )
       
       $('#due_date').prop(\"readonly\", true);
       $('#due_date').removeClass(\"hasDatepicker\");
       $('#due_date').removeClass(\"datepicker\");
       $('#due_date' ).datepicker( \"destroy\" )

       $('#delivery_date').prop(\"readonly\", true);
       $('#delivery_date').removeClass(\"hasDatepicker\");
       $('#delivery_date').removeClass(\"datepicker\");
       $('#delivery_date' ).datepicker( \"destroy\" )
        $('.class_delete').hide();
        $('.class_save').hide();
        
    }
    </script>"

    
   ;
   
   
   

	$reto.='
	<script>
	
	
	if ($("#issue_date").val()==""){
		$("#issue_date").val("'. date("Y-m-d").'");
	}
	
	</script>';
   
return $reto;
}

function billing_invoice_det_footer_bef_operation(){
    $reto ="";
	
return $reto;
}

function billing_invoice_presentation_each_row_obj($column_name,$value,$value_ori=''){   

	$reto ='';
	
	$style="";
	if ($column_name=='balance' ){
		if ($value_ori>0)
			$style= 'status-canceled text-end';
		else
		if ($value_ori<0)
			$style= 'status-created text-end';
	    
		
		$reto ='<div filter_data_column="'.$column_name.'" class="table-cell text-truncate '.$style.'"  >';
		$reto.=$value."$";    
		$reto.='<input filter_data_column="'.$column_name.'" type="hidden" value="'.$value_ori.'" />';
		$reto.='</div>';		
		return $reto;
	}
	
    if ($column_name=='status' ){   		
		$reto ='<div filter_data_column="'.$column_name.'" class="table-cell text-truncate status-'.strtolower($value).'">';
		$reto.=$value;    
		$reto.='<input filter_data_column="'.$column_name.'" type="hidden" value="'.$value_ori.'" />';
		$reto.='</div>';
	}
    else{
		$reto ='<div filter_data_column="'.$column_name.'" class="table-cell text-truncate">';
		$reto.=$value;    
		$reto.='<input filter_data_column="'.$column_name.'" type="hidden" value="'.$value_ori.'" />';
		$reto.='</div>';
	}
return $reto;
}

function billing_invoice_bef_updateToDB($obj){            

	$inv=Billing_Invoice_ext::with_id($obj->id,true);
	$inv->Calculate_Totals();
	$obj->total=$inv->total;
	$obj->sub_total=$inv->sub_total;
	$obj->tps=$inv->tps;
	$obj->tvq=$inv->tvq;
	$obj->balance=$inv->balance;


	if ($obj->status=='CANCELED')
		$obj->balance=0;


    if ($inv->status!='CREATED' && $obj->status=='CREATED')
		$obj->status=$inv->status;
		
    $reto = json_encode($obj,JSON_NUMERIC_CHECK);    
return $reto;
}

function billing_invoice_aft_updateToDB($obj){            
    $reto = json_encode($obj,JSON_NUMERIC_CHECK);    
return $reto;
}

function billing_invoice_bef_createToDB($obj){            
    if ($obj->issue_date=='')
        $obj->issue_date=Master_GetToday('date');  
	if ($obj->balance=='')
		$obj->balance=0;		
    $reto = json_encode($obj,JSON_NUMERIC_CHECK);    
	return $reto;
}

function billing_invoice_aft_createToDB($obj){            
    //it doesnt have to retunr anything
    // lets bring balances
    $invoices = Billing_Invoice::with_client_id($obj->client_id);
    
    foreach ($invoices as $inv){
		if ($inv->balance=='')
			$inv->balance=0;
		
        if ($inv->balance<0){            
			$pay= new Billing_Payment();
            $pay->invoice_id=$obj->id;
            $pay->payment_date=Master_GetToday('date');
            $pay->payment_type='OTHER';
            $pay->payment_effective_date=Master_GetToday('date');
            $pay->amount=abs($inv->balance);
            $pay->notes='Carried Forward from Invoice -> '.$inv->id;
            $pay->CreateToDB();
			

			
			
			$invo = Billing_Invoice::with_id($inv->id);
           // $invo->balance=0;
           // $invo->UpdateToDB();
			
			
			$pay= new Billing_Payment();
			$pay->id='';
            $pay->invoice_id=$invo->id;
            $pay->payment_date=Master_GetToday('date');
            $pay->payment_type='OTHER';
            $pay->payment_effective_date=Master_GetToday('date');
            $pay->amount=($invo->balance);
            $pay->notes='Carried Forward Applied to Invoice -> '.$invo->id;
            $pay->CreateToDB();
			
        }
    }
return true;
}

function billing_invoice_bef_deleteFromDB($obj){            
    //it doesnt have to retunr anything
return true;
}

function billing_invoice_aft_deleteFromDB($obj){            
    //it doesnt have to retunr anything
return true;
}

function billing_invoice_display_view2_bef_footer(){
echo "	
    <script>
        $(document).ready(function() {
            // Hide the anchor element
            $('a[href=\"javascript:$(\'#exampleModal\').modal(\'show\');\"]').hide();
        });
 
";	
echo '   
    
		

 document.addEventListener("DOMContentLoaded", function() {
        // Get the target <i> element
        var iconElement = document.querySelector(\'i[data-original-title="Backup Table"]\');
        
        // Create a new <span> element
        var spanElement = document.createElement("span");
        spanElement.setAttribute("style", "cursor:pointer;");
        spanElement.setAttribute("data-toggle", "tooltip");
        spanElement.setAttribute("data-placement", "top");
        spanElement.setAttribute("title", "");
        spanElement.setAttribute("data-original-title", "delete");

        // Create a new <button> element
        var newButton = document.createElement("button");
        newButton.textContent = "Pending";
        newButton.setAttribute("data-toggle", "modal");
        newButton.setAttribute("id", "button_filter_pending_bills");
        newButton.setAttribute("type", "button");
        newButton.classList.add(\'btn\', \'btn-success\', \'mr-1\', \'ml-1\');  // Add Bootstrap classes
        newButton.setAttribute("style", "vertical-align: super;border-radius: 13px;");
		
		    
        newButton.onclick = function() {
            openmodal("largeModal");
        };

        // Append the button inside the <span>
        spanElement.appendChild(newButton);

        // Insert the <span> with the button right before the <i> element
        iconElement.parentNode.insertBefore(spanElement, iconElement);
		
		
	
		
			document.getElementById("button_filter_pending_bills").onclick = function() {
				
                    $("#adm_fields_billing_invoice_filterby").val(\'status\');
                    $("#adm_fields_billing_invoice_filtervalue").val(\'CLOSED\');
                    $("#adm_fields_billing_invoice_filterby_operator").val(\'<>\');
                    
                    $("#adm_fields_billing_invoice_filterby2").val(\'status\');
                    $("#adm_fields_billing_invoice_filtervalue2").val(\'CANCELED\');
                    $("#adm_fields_billing_invoice_filterby2_operator").val(\'<>\');

                    SetFields_billing_invoice_page();
	}

    });
	
	
	   </script>
';
}
?>