<?php
define('DOCUMENT_ROOT_CLASS','../../');
define('DOCUMENT_ROOT_INC_FOLDER','inc/');
$filepath = realpath(dirname(__FILE__));
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_5"){
    require "../../inc/ajax_header.php";
    $days = !empty($_POST["days"])?$_POST["days"]:0;
    $date = date('Y-m-d', strtotime(date("Y-m-d") . ' +'.$days.' day'));
    echo json_encode(array("span_invoice_due_date"=>date("d M Y",strtotime($date)),"invoice_due_date"=>$date));
    exit();
}
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call"){
    require "../../inc/ajax_header.php";
    $bill_to = $_POST["bill_to"];
    $getData = $commonFunctions->getData('crm_cust_details'," WHERE id = '".$bill_to."'");
    $html = $email = $contact = "";
    foreach ($getData as $rw) {
        $html = "<option value='".$rw['id']."'>".$rw['address']."</option>";
        $email .= $rw['email']."<br>";
        $contact .= $rw['phone']."<br>";
    }
    echo json_encode(array("option"=>$html,"email"=>$email, "contact"=>$contact));
    exit();
}
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_1"){
    require "../../inc/ajax_header.php";
    $warehouse_id = $_POST["warehouse_id"];
    $product_id = $_POST["product_id"];
    $already_selected = array();
    if(!empty($_POST["already_selected"])){
        $already_selected = @$_POST["already_selected"];
    }
    $cond=" AND warehouse_id = '".$warehouse_id."' ";
    if(!empty($product_id)){
        $cond=" AND product_id = '".$product_id."' ";
    }
    $getData = $commonFunctions->getData('invty_pdt_stock_mgt'," WHERE stock_id != 0 ".$cond);
    $html = $product_desc = "";
    $stock_count = $price = 0;
    foreach ($getData as $rw) {
        $product_name = $commonFunctions->getname($rw['product_id'],"invty_pdt_details","label","id");
        $disabled = "";
        if(in_array($rw['product_id'], $already_selected)){
            $disabled = " disabled='' style='display:none;'";
        }
        $html .= "<option value='".$rw['product_id']."' ".$disabled.">".$product_name."</option>";
        if(!empty($product_id)){
            $stock_count = $rw['stock_count'];
            $product_desc = $commonFunctions->getname($rw['product_id'],"invty_pdt_details","description","id");
            $price = $commonFunctions->getname($rw['product_id'],"invty_pdt_details","price","id");
        }
    }
    echo json_encode(array("option"=>$html,"stock_count"=>$stock_count,"price"=>$price,"product_desc"=>$product_desc));
    exit();
}
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_2"){
    require "../../inc/ajax_header.php";
    $total = @$_POST["sub_total_amt"] - $_POST["discount"];
    $added_by = $_SESSION['id'];
    $delivery_note_status = 1;
    if($_POST['delivery_note_flag'] == 3){
        $delivery_note_status = 3;
    }
    $holder_name = $cheque_no = $cheque_date = $bank = $date = $tran_bank = "";
    /*if($_POST['payment_modes'] == 2){ 
        $holder_name = $_POST['cheque_name'];
        $cheque_no = $_POST['cheque_no'];
        $cheque_date = $_POST['cheque_date'];
        $bank = $_POST['cheque_bank'];
    }
    if($_POST['payment_modes'] == 3){ 
        $holder_name = $_POST['holder_name'];
        $date = $_POST['trans_date'];
        $bank = $_POST['bank'];
        $tran_bank = $_POST['transfer_bank'];
    }*/
    $last_id = $commonFunctions->addData('sys_erp_sales_invoice'," (invoice_no,invoice_date,invoice_due_date,branch,bill_to,ship_to,payment_mode,payment_terms,po_number,project_number,discount,tax_rate,sub_total,total,invoice_creator,delivery_note_flag,delivery_note_status,holder_name,cheque_no,cheque_date,bank,date,tran_bank) VALUES ('".$_POST['invoice_number']."','".$_POST['invoice_date']."','".$_POST['invoice_due_date']."','".$_POST['warehouse_id']."','".$_POST['bill_to']."','".$_POST['ship_to']."','".$_POST['payment_modes']."','".$_POST['payment_terms']."','".$_POST['po_number']."','".$_POST['project']."','".$_POST['discount']."','0','".$_POST['sub_total_amt']."','".$total."','".$added_by."','".$_POST['delivery_note_flag']."','".$delivery_note_status."','".$holder_name."','".$cheque_no."','".$cheque_date."','".$bank."','".$date."','".$tran_bank."') ",'');
    if(!empty($last_id)){
        $data_array_details = array();
        for ($i=0; $i < count($_POST["product_id"]); $i++) { 
            $data_array_details["invoice_id"] = $last_id;
            $data_array_details["invoice_no"] = $_POST["invoice_number"];
            $data_array_details["product_id"] = $_POST["product_id"][$i];
            $data_array_details["unit_price"] = $_POST["unit_price"][$i];
            $data_array_details["quantity"] = $_POST["quantity"][$i];
            $data_array_details["product_desc"] = $_POST["product_desc"][$i];
            $data_array_details["total_amt"] = $_POST["total_pro_amt"][$i];

            $commonFunctions->addData('sys_erp_sales_invoice_prdct_details'," (invoice_no,invoice_id,product_id,unit_price,quantity,total_amt,product_desc) VALUES ('".$_POST['invoice_number']."','".$data_array_details['invoice_id']."','".$_POST['product_id'][$i]."','".$_POST['unit_price'][$i]."','".$_POST['quantity'][$i]."','".$_POST['total_pro_amt'][$i]."','".$_POST['product_desc'][$i]."') ",'');

            $cond=" AND warehouse_id = '".$_POST['warehouse_id']."' ";
            $cond=" AND product_id = '".$_POST["product_id"][$i]."' ";
            $getData1 = $commonFunctions->getData('invty_pdt_stock_mgt'," WHERE stock_id != 0 ".$cond);
            $iii = 0;
            foreach ($getData1 as $rw) {
                if($iii == 0){    
                    $old_stock_count = $rw['stock_count'];
                    $stock_count = $old_stock_count - $_POST['quantity'][$i];
                    //Deduction of stock
                    $commonFunctions->updateData('invty_pdt_stock_mgt'," WHERE stock_id = '".$rw["stock_id"]."' "," stock_count='".(int)$stock_count."' ","");
                    $iii = $iii + 1;
                }
            }
        }
        Session::set('msg', '<div class="alert alert-success alert-dismissible mt-3" id="flash-msg">
          <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
          <strong>Success !</strong> Wow, Your Information added Successfully !</div>');
        echo "invoice.php?state=list";
        exit();
    }else{
        Session::set('msg', '<div class="alert alert-danger alert-dismissible mt-3" id="flash-msg">
<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
<strong>Error !</strong> Data not inserted !</div>');
        echo "";
        exit();
    }
}
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_3"){
	require "../../inc/ajax_header.php";
	$resultData = $commonFunctions->getData('crm_cust_details'," WHERE assigned_to_sales = ".@$_SESSION["id"]);
	$html = "";
	$i=1;
	foreach ($resultData as $rw) { 
		$bill_to_html = $rw['name'].'<br>'.$rw['address'].','.$rw['city'].' '.$rw['postcode'].'<br>P: '.$rw['phone'];

		$html .= '<tr>';
		$html .= '<td><input type="hidden" name="'.$rw['id'].'" id="bill_to_'.$rw['id'].'" value="'.$bill_to_html.'"><a href="javascript:void()" onclick=set_bill_to_data("'.$rw['id'].'") style="color: blue;">'.$rw['name'].'</a></td>';
		$html .= '<td><a href="javascript:void()" onclick=set_bill_to_data("'.$rw['id'].'") style="color: blue;">'.$rw['customer_code'].'</a></td><td>'.$rw['phone'].'</td><td>'.$rw['email'].'</td><td>'.$rw['city'].'</td><td>'.$commonFunctions->getName($rw['country'],"sys_erp_adm_countries","label","rowid").$rw['country'].'</td><td>';
		if($rw['status'] == 1){
            $html .= '<span class="badge badge-soft-success">Active</span>';
        }else{ 
        	$html .= '<span class="badge badge-soft-danger">Inactive</span>';
        }
		$html .= '</td></tr>';
	}
	echo $html;
	exit();
}
if(!empty($_POST["action"]) and $_POST["action"] == "ajax_call_4"){
	require "../../inc/ajax_header.php";
	$bill_to = $_POST["bill_to"];
	$resultData = $commonFunctions->getData('crm_cust_details'," WHERE id = '".$bill_to."'");
	$html = "";
	$i=1;
	foreach ($resultData as $rw) { 
		$bill_to_html = $rw['name'].'<br>'.$rw['address'].','.$rw['city'].' '.$rw['postcode'].'<br>P: '.$rw['phone'];

		$html .= '<tr>';
		$html .= '<td><input type="hidden" name="'.$rw['id'].'" id="ship_to_'.$rw['id'].'" value="'.$bill_to_html.'"><a href="javascript:void()" onclick=set_ship_to_data("'.$rw['id'].'") style="color: blue;">'.$rw['name'].'</a></td>';
		$html .= '<td><a href="javascript:void()" onclick=set_ship_to_data("'.$rw['id'].'") style="color: blue;">'.$rw['customer_code'].'</a></td><td>'.$rw['phone'].'</td><td>'.$rw['email'].'</td><td>'.$rw['city'].'</td><td>'.$commonFunctions->getName($rw['country'],"sys_erp_adm_countries","label","rowid").$rw['country'].'</td><td>';
		if($rw['status'] == 1){
            $html .= '<span class="badge badge-soft-success">Active</span>';
        }else{ 
        	$html .= '<span class="badge badge-soft-danger">Inactive</span>';
        }
		$html .= '</td></tr>';
	}
	echo $html;
	exit();
}
require "../../inc/header.php";
$msg = Session::get('msg');
Session::set("msg", NULL);
?>
<style type="text/css">
	.select2-container{
		width: 100% !important;
	}
</style>
    
    <div class="row">
        <div class="col-sm-12">
            <div class="page-title-box">
                <div class="row">
                    <div class="col">
                        <?php 
                        /*$rand = "INV-";
                        $rand .= rand(0,9999999);
                        $rand .= @$commonFunctions->getRowDataCount('sys_erp_sales_invoice','');*/
                        ?>
                        <?php $seriNo = $commonFunctions->getRowDataCount('sys_erp_sales_invoice',''); 
                            $seriNo1 = $commonFunctions->random_num(10 - strlen($seriNo));
                            $rand = "INV-".@$seriNo1.@$seriNo;
                        ?>
                        <h4 class="page-title"><?php echo ($_GET['state'] != "list")?"Invoice # $rand":" Sales / Invoices List "; ?></h4>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="javascript:void(0);">Sales & Purchases</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);">Sales & Invoices</a></li>
                            <li class="breadcrumb-item"><a href="javascript:void(0);"><?php echo ($_GET['state'] != "list")?$rand:"Sales / Invoices"; ?></a></li>
                        </ol>
                    </div><!--end col-->
                    <div class="col-auto align-self-center">
                    	<?php if(@$_GET['state'] != "list"){ ?>
                            <a href="invoice.php?state=list"><button type="button" class="btn btn-outline-secondary">Back to Invoice List </button></a>

                            <button type="button" class="btn btn-primary save_form" id="save_form">
                             	<i class="fa fa-save align-self-center icon-xs"></i> Save Invoice
                            </button>

                        <?php } ?>
                    </div><!--end col-->  
                </div><!--end row-->                                                              
            </div><!--end page-title-box-->
        </div><!--end col-->
    </div><!--end row-->
    <!-- end page title end breadcrumb -->
    <?php if(@$_GET['state'] == "list"): ?>
    <div class="row">
                <div class="col-12">
                    <div class="row justify-content-center">
                        <div class="col-md-6 col-lg-3">
                            <div class="card report-card">
                                <div class="card-body">
                                    <div class="row d-flex justify-content-center">
                                        <div class="col">
                                            <p class="text-dark mb-0 font-weight-semibold">Invoice Created</p>
                                            <h3 class="m-0"><?php echo $commonFunctions->getRowDataCount('sys_erp_sales_invoice',''); ?></h3>
                                            <p class="mb-0 text-truncate text-muted"><span class="text-success"><i class="mdi mdi-trending-up"></i> </span>  </p>
                                        </div>
                                        <div class="col-auto align-self-center">
                                            <div class="report-main-icon bg-light-alt">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-users align-self-center text-muted icon-sm"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>  
                                            </div>
                                        </div>
                                    </div>
                                </div><!--end card-body--> 
                            </div><!--end card--> 
                        </div> <!--end col--> 
                        <div class="col-md-6 col-lg-3">
                            <div class="card report-card">
                                <div class="card-body">
                                    <div class="row d-flex justify-content-center">                                                
                                        <div class="col">
                                            <p class="text-dark mb-0 font-weight-semibold">Amount Paid</p>
                                            <h3 class="m-0">0</h3>
                                            <p class="mb-0 text-truncate text-muted"><span class="text-success"><i class="mdi mdi-trending-up"></i></span></p>
                                        </div>
                                        <div class="col-auto align-self-center">
                                            <div class="report-main-icon bg-light-alt">
                                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-clock align-self-center text-muted icon-sm"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>  
                                            </div>
                                        </div> 
                                    </div>
                                </div><!--end card-body--> 
                            </div><!--end card--> 
                        </div> <!--end col--> 
                        <div class="col-md-6 col-lg-3">
                        </div>
                        <div class="col-md-6 col-lg-3">
                        </div>                          
                    </div>
                    <div class="card">
                        <div class="card-header">
                            <h4 class="card-title"> 
                                <div class="form-row">
                                    <!-- <div class="form-group searchForm col-md-6">    
                                        <a class="btn btn-soft-primary" href="invoice.php?state=add" role="button" ><i class="fas fa-plus mr-2"></i> Create Invoice </a>
                                    </div>  --> 
                                    <div class="form-group searchForm col-md-6">
		                                <?php if(@$_GET['state'] == "list"){ ?>
                                    		<a href="invoice.php?state=add" role="button" ><button type="button" class="btn btn-outline-dark"><i class="fas fa-plus mr-2"></i> Create Invoice</button> </a>
		                                
		                                <?php }else{ ?>
		                                    <!-- <a href="invoice.php?state=list"><button type="button" class="btn btn-outline-secondary">Back to Invoice List </button></a> -->
		                                <?php } ?>
		                            </div>
                                    <div class="form-group searchForm col-md-6">
                                    	<?php if(empty($_GET['state']) OR (!empty($_GET['state']) and $_GET['state'] == "list")): ?>
	                                        <form action="" id="searchForm" method="GET">
	                                            <div class="form-row">
	                                                <div class="form-group searchForm col-md-8">
	                                                    <input type="text" name="search" id="search" placeholder="Search" class="form-control" value="<?php echo @$_GET['search']; ?>">
	                                                    <input type="hidden" name="state" value="<?php echo @$_GET['state']; ?>">
	                                                    <input type="hidden" name="page" value="<?php echo @$_GET['page']; ?>">
	                                                </div>
	                                                <div class="form-group searchForm col-md-4">
	                                                    <button type="submit" id="searchbtn" class="btn btn-primary"> <i class="fa fa-search"></i> Search</button>
	                                                    <button type="button" id="clearbtn" class="btn btn-danger"> <i class="fa fa-trash"></i> Clear</button>
	                                                </div>
	                                            </div>
	                                        </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </h4>
                            <?php echo !empty($msg)?$msg:''; ?>        
                        </div>
               
                        <div class="card-body">
                            <div class="row">
                            <?php endif; ?>

                                <?php if(@$_GET['state'] != "list"): ?>
                                    <?php 
                                    $error_ = 0;
                                        if(@$_GET['inventory_id'] != ''){
                                            $editData = $commonFunctions->getRowData('invty_pdt_stock_mgt'," WHERE stock_id = '".$_GET['inventory_id']."' ");
                                        }
                                    ?>
                                    <div class="col-md-12">
                                        <!--div class="main-card mb-3 card">
                                            <div class="card-body"-->
                                                <form id="invoice_form" action="" method="post" enctype="multipart/form-data">
                                                    <input type="hidden" name="inventory_id" id="inventory_id" value="<?php echo ($_GET['state'] == 'edit')?@$_GET['inventory_id']:0;?>">
                                                    <input type="hidden" name="invoice_number" id="invoice_number" value="<?php echo (!empty($rand))?@$rand:0;?>">

    <div class="row">
        <div class="col-lg-12 mx-auto">
            <div class="card">
                <div class="card-body invoice-head"> 
                    <div class="row">
                        <div class="col-md-5 align-self-center">    
                        	<?php $orgData = $commonFunctions->getRowData("sys_erp_organaization",""); ?>
                            <?php $warehouseData = $commonFunctions->getRowData("invty_wrhus"," WHERE id='".$_SESSION["warehouse_id"]."' "); ?>
                            <img src="<?php echo DOCUMENT_ROOT_CLASS;?>uploads/admin-setting/company/<?php echo @$orgData['erp_sys_org_logo'];?>" alt="logo-large" class="logo-lg logo-dark" height="80">  
                            <img src="<?php echo DOCUMENT_ROOT_CLASS;?>uploads/admin-setting/company/<?php echo @$orgData['erp_sys_org_logo'];?>" alt="logo-large" class="logo-lg logo-light" height="80"> 
                            <!--p class="mt-2 mb-0 text-muted">If account is not paid within 7 days the credits details supplied as confirmation.</p-->                                             
                        </div><!--end col-->    
                        <div class="col-md-7">                                                
                            <ul class="list-inline mb-0float-right">                                                   
                                <li class="list-inline-item">
                                    <div class="pl-3">
                                      <p class="text-muted mb-0"><?php echo @$warehouseData['address'];?></p>
                                      <p class="text-muted mb-0"><?php echo @$warehouseData['city'];?>, P.O.Box <?php echo @$warehouseData['zip_code'];?></p>
                                      <p class="text-muted mb-0">State of <?php echo $commonFunctions->getname(@$warehouseData['province'],"sys_erp_adm_countries_states","label","rowid");?></p>
                                  </div>                                                
                                </li>
                                <li class="list-inline-item">
                                    <div class="pl-3">
                                        <p class="text-muted mb-0">C.R # <?php echo @$orgData['erp_sys_org_cr_num'];?></p>
                                        <p class="text-muted mb-0" style="width: 300px;"><?php echo !empty(@$orgData['erp_sys_email_work'])?@$orgData['erp_sys_email_work']:"&nbsp;";?></p>
                                        <p class="text-muted mb-0"><?php echo @$orgData['erp_sys_org_phone_work'];?></p>
                                    </div>
                                </li>
                                <li class="list-inline-item">
                                    <div class="pl-1">
                                        <img alt='barcode' src='<?php echo DOCUMENT_ROOT_CLASS;?>lib/barcode.php?codetype=Code128&size=40&text=<?php echo $rand;?>&print=true'/>
                                    </div>
                                </li>
                            </ul>
                        </div><!--end col-->     
                    </div><!--end row-->     
                </div><!--end card-body-->
                <div class="card-body">
                    <div class="row">
                        
                        <div class="col-md-3">                                            
                            <div class="float-left">
                                <address class="font-13">
                                    <strong class="font-14">Billed To :</strong> 
                                    <td>
                                        <button type="button" class="bill_to_btn btn btn-light waves-effect waves-dark btn-sm" data-toggle="modal" data-target="#billToModal">
                                            Add
                                        </button>
                                        <div class="modal fade bd-example-modal-xl" id="billToModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
                                            <div class="modal-dialog modal-xl" role="document">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h4 class="modal-title m-0" id="myLargeModalLabel">Select Customer / Client</h4>
                                                        <button type="button" class="close " data-dismiss="modal" aria-label="Close">
                                                        <span aria-hidden="true"><i class="la la-times"></i></span>
                                                        </button>
                                                    </div><!--end modal-header-->
                                                    <p></p>
                                                    <div class="col-lg-12">
                                                        <div class="card">
                                                            <div class="card-header">
                                                                <div class="row align-items-center">
                                                                    <div class="col-lg-5">                      
                                                                        <a href="<?php echo DOCUMENT_ROOT_CLASS;?>crm/customer.php?state=customer-form" target="_blank"><button type="button" class="btn btn-outline-primary">Add Customer</button></a>                     
                                                                    </div><!--end col--> 
                                                                    <div class="col-lg-7">
                                                                        <div class="input-group">
                                                                            <!-- <input type="text" class="form-control" placeholder="Search" aria-label="Recipient's username" aria-describedby="basic-addon2">
                                                                            <button class="btn btn-soft-secondary" type="button" id="button-addon2"><i class="fas fa-search"></i></button> -->
                                                                        </div>                        
                                                                    </div><!--end col-->                                        
                                                                </div>  <!--end row-->                                  
                                                            </div><!--end card-header-->
                                                            <div class="card-body">
                                                                <div class="table-responsive1 browser_users">
                                                                    <table class="datatableCust table table-hover mb-0">
                                                                        <thead class="thead-light">
                                                                            <tr>
                                                                                <th class="border-top-0">Customer Name</th>
                                                                                <th class="border-top-0">Customer ID#</th>
                                                                                <th class="border-top-0">Phone No</th>
                                                                                <th class="border-top-0">Email Address</th>
                                                                                <th class="border-top-0">City</th>                                                    
                                                                                <th class="border-top-0">Country</th>
                                                                                <th class="border-top-0">Status</th>
                                                                            </tr><!--end tr-->
                                                                        </thead>
                                                                        <tbody id="bill_to_tbody">
                                                                                                  
                                                                        </tbody>
                                                                    </table> <!--end table-->                                               
                                                                </div><!--end /div-->
                                                            </div><!--end card-body--> 
                                                        </div><!--end card--> 
                                                    </div> <!--end col-->
                                                    <p></p>
                                                    <div class="modal-footer text-left">
                                                        <p class="mb-0 text-muted text-left">Select the Customer / Client to whom you want to bill.</p> 
                                                        <!--button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button-->
                                                    </div><!--end modal-footer-->
                                                </div><!--end modal-content-->
                                            </div><!--end modal-dialog-->
                                        </div><!--end modal-->
                                    </td>
                                    <br>
                                    
                                    <span class="custAddressBillTo"></span>
                                    <input type="hidden" name="bill_to" id="bill_to" required="">
                                </address>
                            </div>
                        </div><!--end col--> 
                        <div class="col-md-3">
                            <div class="">
                                <address class="font-13">
                                    <strong class="font-14">Shipped To:</strong>
                                    <td>
                                        <button type="button" class="ship_to_btn btn btn-light waves-effect waves-dark btn-sm" data-toggle="modal" data-target="#ship_to_modal">
                                            Add
                                        </button>
                                        <div class="modal fade bd-example-modal-xl" id="ship_to_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
                                            <div class="modal-dialog modal-xl" role="document">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h4 class="modal-title m-0" id="myLargeModalLabel">Select Customer / Client</h4>
                                                        <button type="button" class="close " data-dismiss="modal" aria-label="Close">
                                                        <span aria-hidden="true"><i class="la la-times"></i></span>
                                                        </button>
                                                    </div><!--end modal-header-->
                                                    <p></p>
                                                    <div class="col-lg-12">
                                                        <div class="card">
                                                            <div class="card-header">
                                                                <div class="row align-items-center">
                                                                    <div class="col-lg-5">                      
                                                                        <a href="<?php echo DOCUMENT_ROOT_CLASS;?>crm/customer.php?state=customer-form" target="_blank"><button type="button" class="btn btn-outline-primary">Add Customer</button></a>                     
                                                                    </div><!--end col--> 
                                                                    <div class="col-lg-7">
                                                                        <!-- <div class="input-group">
                                                                            <input type="text" class="form-control" placeholder="Search" aria-label="Recipient's username" aria-describedby="basic-addon2">
                                                                            <button class="btn btn-soft-secondary" type="button" id="button-addon2"><i class="fas fa-search"></i></button>
                                                                        </div> -->                        
                                                                    </div><!--end col-->                                        
                                                                </div>  <!--end row-->                                  
                                                            </div><!--end card-header-->
                                                            <div class="card-body">
                                                                <div class="table-responsive2 browser_users">
                                                                    <table class="datatableCust table table-hover mb-0">
                                                                        <thead class="thead-light">
                                                                            <tr>
                                                                                <th class="border-top-0">Customer Name</th>
                                                                                <th class="border-top-0">Customer ID#</th>
                                                                                <th class="border-top-0">Phone No</th>
                                                                                <th class="border-top-0">Email Address</th>
                                                                                <th class="border-top-0">City</th>                                                    
                                                                                <th class="border-top-0">Country</th>
                                                                                <th class="border-top-0">Status</th>
                                                                            </tr><!--end tr-->
                                                                        </thead>
                                                                        <tbody class="ship_to_tbody">              
                                                                        </tbody>
                                                                    </table> <!--end table-->                                               
                                                                </div><!--end /div-->
                                                            </div><!--end card-body--> 
                                                        </div><!--end card--> 
                                                    </div> <!--end col-->
                                                    <p></p>
                                                    <div class="modal-footer text-left">
                                                        <p class="mb-0 text-muted text-left">Select the Customer / Client to whom you want to bill.</p> 
                                                        <!--button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button-->
                                                    </div><!--end modal-footer-->
                                                </div><!--end modal-content-->
                                            </div><!--end modal-dialog-->
                                        </div><!--end modal-->
                                    </td>
                                    <br>
                                    <span class="custAddressShipTo"></span>
                                    <input type="hidden" name="ship_to" id="ship_to" required="">
                                </address>
                            </div>
                        </div> 
                        <div style="display: none;">
                            <select class="form-control select2" name="warehouse_id" id="warehouse_id">
                                <option value="<?php echo @$_SESSION['warehouse_id'];?>" selected></option>
                            </select>
                        </div>
                        <!--end col-->
                        <!-- <div class="col-md-3">
                        	<strong class="font-14">Branch :</strong>
                        	<button type="button" class="wharehouse_btn btn btn-light waves-effect waves-dark btn-sm" data-toggle="modal" data-target="#wharehouseModal">
                                Add
                            </button>
                            <br>
                            <span class="branch_name"></span>
	                            <div class="modal fade bd-example-modal-x3" id="wharehouseModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
	                                <div class="modal-dialog modal-x3" role="document">
	                                    <div class="modal-content">
	                                    	<div class="modal-header">
	                                            <h4 class="modal-title m-0" id="myLargeModalLabel">Add Branch</h4>
	                                            <button type="button" class="close " data-dismiss="modal" aria-label="Close">
	                                            <span aria-hidden="true"><i class="la la-times"></i></span>
	                                            </button>
	                                        <div class="col-lg-12">
	                                            <div class="card">
	                                                <div class="card-body">
	                                                	<div class="form-row">
	                                                    	<div class="col-lg-12">
	                                                    		<label for="label" class="">Select Branch <span class="error">*</span></label>
	                                                    		<?php $warehouseData = $commonFunctions->getData('invty_wrhus',' WHERE status = 0 '); ?>
									                            <select class="form-control select2" name="warehouse_id" id="warehouse_id" required="">
									                                <option value="" >Select</option>
									                                <?php foreach ($warehouseData as $rw) { ?>
									                                    <option value="<?php echo $rw['id'];?>" <?php echo (@$editData['warehouse_id'] == $rw['id'])?"selected":"";?> ><?php echo $rw['short_name_location']; ?></option>     
									                                <?php } ?>
									                            </select>
									                            <label id="warehouse_id-error" class="error" for="warehouse_id"></label>
	                                                        </div>
	                                                        <div class="col-lg-12"><br>
	                                                        	<button type="button" class="btn btn-secondary add_warehose" >Add</button>
	                                                        </div>
	                                                    </div>
	                                                </div>
	                                            </div>
	                                        </div>
	                                        
	                                    </div>
	                                </div>
	                            </div>

	                            
	                        </div>
	                    </div>-->
	                    <div class="col-md-3"></div>
                        <div class="col-md-3">                                  
                                <table id="datatable" class="table table-bordered dt-responsive nowrap dataTable no-footer dtr-inline" style="border-collapse: collapse; border-spacing: 0px; width: 100%;" role="grid" aria-describedby="datatable_info">
                                    <thead class="thead-light">
                                        <tr>
                                            <th>Invoice Number </th>
                                            <th><?php echo @$rand;?></th>
                                        </tr><!--end tr-->
                                        <tr>
                                            <th>Invoice Date </th>
                                            <th><?php echo date("d M Y");?>
                                                <input type="hidden" name="invoice_date" value="<?php echo date("Y-m-d");?>"></th>
                                        </tr><!--end tr-->
                                        <tr>
                                            <th>Due Date </th>
                                            <th> <span class="span_invoice_due_date"><?php echo date("d M Y");?></span>
                                                <input type="hidden" name="invoice_due_date" class="invoice_due_date" value="<?php echo date("Y-m-d");?>"></th>
                                        </tr><!--end tr-->
                                        <tr>
                                            <th>Delivery Note </th>
                                            <th><span class="delivery_note"></span></th>
                                        </tr><!--end tr-->
                                    </thead>
                                </table>
                        </div><!--end col-->
                    </div><!--end row-->

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="table-responsive2 project-invoice">
                                <table class="table table-bordered mb-0">
                                    <thead class="thead-light">
                                        <tr>
                                            <th>PO Number</th>
                                            <th>Payment Mode</th>
                                            <th>Payment Type</th> 
                                            <th>Project ID</th>
                                        </tr><!--end tr-->
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td>
                                                <!-- CUS PO#<span class="cust_po"></span> <a class="btn btn-sm btn-light cust_po_btn" href="javascript:void(0);" role="button">Add</a> -->
                                                <input type="text" maxlength="64" name="po_number" id="cust_po" value="" class="form-control" placeholder="P.O Number">
                                            </td>
                                            <td>
                                                <?php $payModesData = $commonFunctions->getData('fin_accnt_payment_mode',' WHERE status = 0'); ?>
                                                <select class="form-control select2" name="payment_modes" id="payment_modes" required="">
                                                    <option value="" disabled="" selected=""></option>
                                                    <?php foreach ($payModesData as $rw) { ?>
                                                        <option value="<?php echo $rw['id'];?>"><?php echo $rw['label'];?></option>
                                                    <?php } ?>
                                                </select>
                                                <!-- <span class="paymode"></span> <a class="btn btn-sm btn-light paymode_btn" href="javascript:void(0);" role="button">Add</a>-->

                                                <span id="payment_modes-error" class="error" for="payment_modes"></span> 
                                            </td>
                                            <td>
                                                <?php $payTermsData = $commonFunctions->getData('fin_accnt_payment_trems',''); ?>
                                                <select class="form-control select2" name="payment_terms" id="payment_terms" required="">
                                                    <option value="">Select</option>
                                                    <?php foreach ($payTermsData as $rw) { ?>
                                                        <option value="<?php echo $rw['id'];?>" data-id="<?php echo $rw['no_of_days'];?>"><?php echo $rw['label'];?></option>
                                                    <?php } ?>
                                                </select>
                                                <!-- <span class="paytype"></span> <a class="btn btn-sm btn-light paytype_btn" href="javascript:void(0);" role="button">Add</a>-->
                                                <span id="payment_terms-error" class="error" for="payment_terms"></span> 
                                            </td>
                                            <td>
                                                <input type="text" maxlength="64" name="project" value="" id="project" class="form-control" placeholder="Project">
                                                <!-- CUS PID#<span class="project_id_label"></span> <a class="btn btn-sm btn-light project_id_label_btn" href="javascript:void(0);" role="button">Add</a> -->
                                            </td>
                                        </tr><!--end tr-->
                                    </tbody>
                                </table><!--end table-->

                                <!-- <div class="modal fade bd-example-modal-x3" id="cust_po_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
                                    <div class="modal-dialog modal-x3" role="document">
                                        <div class="modal-content">
	                                    	<div class="modal-header">
	                                            <h4 class="modal-title m-0" id="myLargeModalLabel">Add Customer PO</h4>
	                                            <button type="button" class="close " data-dismiss="modal" aria-label="Close">
	                                            <span aria-hidden="true"><i class="la la-times"></i></span>
	                                            </button>
	                                        </div> 
                                            <div class="col-lg-12">
                                                <div class="card">
                                                    <div class="card-body">
                                                    	<div class="form-row">
	                                                    	<div class="col-lg-12">
	                                                    		<label for="label" class="">P.O Number</label>
	                                                        	<input type="text" maxlength="64" name="po_number" id="cust_po" value="" class="form-control" placeholder="P.O Number">
	                                                        </div>
	                                                        <div class="col-lg-12"><br>
	                                                        	<button type="button" class="btn btn-secondary" onclick="change_label('cust_po_btn','cust_po_modal')">Add</button>
	                                                        </div>
	                                                    </div>
                                                    </div>
                                                </div>
                                            </div> 
                                            
                                        </div>
                                    </div>
                                </div> 

                                <div class="modal fade bd-example-modal-x3" id="paymode_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
                                    <div class="modal-dialog modal-x3" role="document">
                                        <div class="modal-content">
	                                    	<div class="modal-header">
	                                            <h4 class="modal-title m-0" id="myLargeModalLabel">Add Payment Mode</h4>
	                                            <button type="button" class="close " data-dismiss="modal" aria-label="Close">
	                                            <span aria-hidden="true"><i class="la la-times"></i></span>
	                                            </button>
	                                        </div> 
                                            <div class="col-lg-12">
                                                <div class="card">
                                                    <div class="card-body">
                                                    	<div class="form-row">
	                                                    	<div class="col-lg-12 position-relative form-group">
	                                                    		<label>Payment Mode <span class="error">*</span></label>
	                                                        	<?php $payModesData = $commonFunctions->getData('fin_accnt_payment_mode',' WHERE status = 0'); ?>
                                                                <select class="form-control select2" name="payment_modes" id="payment_modes" required="">
                                                                    <option value="" disabled="" selected=""></option>
                                                                    <?php foreach ($payModesData as $rw) { ?>
                                                                        <option value="<?php echo $rw['id'];?>"><?php echo $rw['label'];?></option>
                                                                    <?php } ?>
                                                                </select>
	                                                        </div>
	                                                        <div class="form-row cheque_div" style="margin-bottom: 5px;display: none;">
	                                                            <div class="col-md-1 position-relative form-group" style="margin-bottom: 5px;">
	                                                            </div>
	                                                            <div class="col-md-1 position-relative form-group" style="margin-bottom: 5px;">
	                                                                
	                                                            </div>
	                                                            <div class="col-md-12 position-relative form-group" style="margin-bottom: 5px;">
	                                                                <label>Cheque Name </label>
	                                                                <input type="text" name="cheque_name" id="cheque_name" value="" class="form-control" placeholder='Cheque Name'>
	                                                            </div>
	                                                            <div class="col-md-12 position-relative form-group" style="margin-bottom: 5px;">
	                                                                <label>Cheque Number</label>
	                                                                <input type="text" name="cheque_no" id="cheque_no" value="0" class="form-control" placeholder='Cheque Number'>
	                                                            </div>
	                                                            <div class="col-md-12 position-relative form-group" style="margin-bottom: 5px;">
	                                                                <label>Cheque Date 
                                                                    </label>
	                                                                <input type="text" name="cheque_date" id="cheque_date" value="" class="form-control" placeholder='Cheque Date'>
	                                                            </div>
	                                                            <div class="col-md-12 position-relative form-group" style="margin-bottom: 5px;">
	                                                                <label>Cheque Bank </label>
	                                                                <input type="text" name="cheque_bank" id="cheque_bank" value="" class="form-control" placeholder='Cheque Bank'>
	                                                            </div>

	                                                        </div>
                                                        <div class="form-row bank_transfer_div" style="margin-bottom: 5px;display: none;">
                                                            <div class="col-md-1 position-relative form-group" style="margin-bottom: 5px;">
                                                            </div>
                                                            <div class="col-md-1 position-relative form-group" style="margin-bottom: 5px;">
                                                                
                                                            </div>
                                                            <div class="col-md-12 position-relative form-group" style="margin-bottom: 5px;">
                                                                <label>Holder Name <span class="error">*</span></label>
                                                                <input type="text" name="holder_name" id="holder_name" value="" class="form-control" placeholder='Holder Name'>
                                                            </div>
                                                            <div class="col-md-12 position-relative form-group" style="margin-bottom: 5px;">
                                                                <label>Date <span class="error">*</span></label>
                                                                <input type="text" name="trans_date" id="trans_date" value="" class="form-control" placeholder='Date'>
                                                            </div>
                                                            <div class="col-md-12 position-relative form-group" style="margin-bottom: 5px;">
                                                                <label>Bank <span class="error">*</span></label>
                                                                <input type="text" name="bank" id="bank" value="" class="form-control" placeholder='Bank'>
                                                            </div>
                                                            <div class="col-md-12 position-relative form-group" style="margin-bottom: 5px;">
                                                                <label>Transfer Bank <span class="error">*</span></label>
                                                                <input type="text" name="transfer_bank" id="transfer_bank" value="" class="form-control" placeholder='Transfer Bank'>
                                                            </div>
                                                        </div>
	                                                        <div class="col-lg-12"><br>
	                                                        	<button type="button" class="btn btn-secondary" onclick="change_label('paymode_btn','paymode_modal')">Add</button>
	                                                        </div>
	                                                    </div>
                                                    </div>
                                                </div>
                                            </div>
                                            
                                        </div>
                                    </div>
                                </div> 

                                <div class="modal fade bd-example-modal-x3" id="paytype_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
                                    <div class="modal-dialog modal-x3" role="document">
                                        <div class="modal-content">
	                                    	<div class="modal-header">
	                                            <h4 class="modal-title m-0" id="myLargeModalLabel">Add Payment Type</h4>
	                                            <button type="button" class="close " data-dismiss="modal" aria-label="Close">
	                                            <span aria-hidden="true"><i class="la la-times"></i></span>
	                                            </button>
	                                        </div> 
                                            <div class="col-lg-12">
                                                <div class="card">
                                                    <div class="card-body">
                                                    	<div class="form-row">
	                                                    	<div class="col-lg-12">
	                                                        	<label for="label" class="">Payment Terms <span class="error">*</span></label>
	                                                        </div>
	                                                       	<div class="col-lg-12">
	                                                        	<?php $payTermsData = $commonFunctions->getData('fin_accnt_payment_trems',''); ?>
                                                                <select class="form-control select2" name="payment_terms" id="payment_terms" required="">
                                                                    <option value="">Select</option>
                                                                    <?php foreach ($payTermsData as $rw) { ?>
                                                                        <option value="<?php echo $rw['id'];?>"><?php echo $rw['label'];?></option>
                                                                    <?php } ?>
                                                                </select>
                                                                <label id="payment_terms-error" class="error" for="payment_terms"></label>
	                                                        </div>
	                                                        <div class="col-lg-12"><br>
	                                                        	<button type="button" class="btn btn-secondary" onclick="change_label('paytype_btn','paytype_modal')">Add</button>
	                                                        </div>
	                                                    </div>
                                                    </div>
                                                </div>
                                            </div> 
                                            
                                        </div>
                                    </div>
                                </div> 

                                <div class="modal fade bd-example-modal-x3" id="project_id_label_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
                                    <div class="modal-dialog modal-x3" role="document">
                                        <div class="modal-content">
	                                    	<div class="modal-header">
	                                            <h4 class="modal-title m-0" id="myLargeModalLabel">Add Project</h4>
	                                            <button type="button" class="close " data-dismiss="modal" aria-label="Close">
	                                            <span aria-hidden="true"><i class="la la-times"></i></span>
	                                            </button>
	                                        </div>
                                            <div class="col-lg-12">
                                                <div class="card">
                                                    <div class="card-body">
                                                    	<div class="form-row">
	                                                    	<div class="col-lg-12">
	                                                    		<label for="label" class="">Project</label>
	                                                        	<input type="text" maxlength="64" name="project" value="" id="project" class="form-control" placeholder="Project">
	                                                        </div>
	                                                        <div class="col-lg-12"><br>
	                                                        	<button type="button" class="btn btn-secondary" onclick="change_label('project_id_label_btn','project_id_label_modal')">Add</button>
	                                                        </div>
	                                                    </div>
                                                    </div> 
                                                </div> 
                                            </div> 
                                            
                                        </div> 
                                    </div> 
                                </div>  -->

                            </div>  <!--end /div-->                                          
                        </div>  <!--end col-->                                      
                    </div><!--end row-->

                    <p></p>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="table-responsive2 project-invoice">
                                <table class="table table-bordered mb-0">
                                    <thead class="thead-light">
                                        <tr>
                                            <th style="width: 20%;">Product Ref / ID</th>
                                            <th style="width: 30%;">Product Description</th>
                                            <th style="width: 8%;">Unit Price</th>
                                            <th style="width: 8%;">Quantity</th> 
                                            <th style="width: 11%;">Amount</th>
                                            <th style="width: 8%;">Add / Remove</th>
                                        </tr><!--end tr-->
                                    </thead>
                                    <tbody>
                                       <tr class="after-add-more">
                                          <td>
                                            <select name="product_id[]" class="product_id form-control product_id1 select2" required="">
                                                <option value="">Select</option>
                                            </select>
                                            <span id="product_id[]-error" class="error" for="product_id[]"></span>
                                          </td>
                                          <td>
                                            <input type="text" class="form-control product_desc1" name="product_desc[]" placeholder="Enter Product Description" value="">
                                          	<!-- <textarea class="form-control product_desc1" name="product_desc[]" placeholder="Enter Product Description" rows="3"></textarea> -->
                                          </td>
                                          <td>
                                            <input type="text" name="unit_price[]" class="form-control unit_price1" >
                                          </td>
                                          <td>
                                            <input type="text" name="quantity[]" class="form-control quantity1" required="" onkeyup="check_quantity(1)">
                                          </td>
                                          <td>
                                            <input type="text" name="total_pro_amt[]" class="total_pro_amt form-control total_pro_amt1" readonly="">
                                          </td>
                                          <td class="change">
                                            <button type="button" class="btn btn-soft-success btn-icon-circle btn-icon-circle-sm align-self-center add-more">
                                             	<i class="fas fa-plus font-16"></i>
                                            </button>
                                            <a style="width: 100px;display:none;" class="btn btn-secondary move_stack1" href="javascript:void(0)" onclick="redirect_stock_movement('1')">Move Stock</a>
                                          </td>
                                       </tr>
                                       
                                       <!--end tr-->
                                       <tr>
                                          <td colspan="3" class="border-0"></td>
                                          <td class="border-0 font-14 text-dark"><b>Sub Total</b></td>
                                          <td class="border-0 font-14 text-dark"><b>
                                            <input type="hidden" name="sub_total_amt" class="sub_total_amt" value="0">
                                            <span class="sub_total_amt">0</span></b></td>
                                       </tr>
                                       <!--end tr-->
                                       <tr>
                                          <th colspan="3" class="border-0"></th>
                                          <td class="border-0 font-14 text-dark"><b>Tax Rate</b></td>
                                          <td class="border-0 font-14 text-dark"><b>$0.00%</b></td>
                                       </tr>
                                       <!--end tr-->
                                       <tr>
                                          <th colspan="3" class="border-0"></th>
                                          <td class="border-0 font-14 text-dark"><b>Discount</b></td>
                                          <td colspan="2" class="border-0 font-14 text-dark"><b><input type="text" name="discount" id="discount" value="0" style="width:50px!important"></b></td>
                                       </tr>
                                       <!--end tr-->
                                       <tr class="bg-black text-white">
                                          <th colspan="3" class="border-0"></th>
                                          <td class="border-0 font-14"><b>Total</b></td>
                                          <td colspan="2" class="border-0 font-14"><b><span class="total_amt">0</span></b></td>
                                          
                                       </tr>
                                       <!--end tr-->
                                    </tbody>
                                </table><!--end table-->
                            </div>  <!--end /div-->                                          
                        </div>  <!--end col-->                                      
                    </div><!--end row-->

                    <div class="row justify-content-center">
                        <div class="col-lg-6">
                            <h5 class="mt-4">Terms And Condition :</h5>
                            <ul class="pl-3">
                                <li><small class="font-12">All accounts are to be paid within 7 days from receipt of invoice. </small></li>
                                <li><small class="font-12">To be paid by cheque or credit card or direct payment online.</small ></li>
                                <li><small class="font-12"> If account is not paid within 7 days the credits details supplied as confirmation of work undertaken will be charged the agreed quoted fee noted above.</small></li>                                            
                            </ul>
                        </div> <!--end col-->                                       
                        <div class="col-lg-6 align-self-end">
                            <div class="float-right" style="width: 30%;">
                                <small>Account Manager</small>
                                <img src="assets/images/signature.png" alt="" class="mt-2 mb-1" height="26">
                                <p class="border-top">Signature</p>
                            </div>
                        </div><!--end col-->
                    </div><!--end row-->
                    <hr>
                    <div class="row d-flex justify-content-center">
                        <div class="col-lg-12 col-xl-4 ml-auto align-self-center">
                            <div class="text-center"><small class="font-12">Thank you very much for doing business with us.</small></div>
                        </div><!--end col-->
                        <div class="col-lg-12 col-xl-4">
                            <div class="float-right d-print-none">
                                <button type="button" class="btn btn-primary btn-sm save_form" id="save_form">
                                 	<i class="fa fa-save align-self-center icon-xs"></i> Save Invoice
                                </button>
                                <!-- <a href="sales-invoices-INV-20210623001.html" class="btn btn-soft-success btn-sm">
                                    <i class="fa fa-file-invoice align-self-center icon-xs"></i> Create Invoice
                                </a> -->
                            </div>
                        </div><!--end col-->
                    </div><!--end row-->
                </div><!--end card-body-->
            </div><!--end card-->
        </div><!--end col-->
    </div><!--end row-->

                                                </form>
                                <!--/div>
                            </div-->
                        </div>
                    <?php else: ?>
                        <div class="col-md-12">
                            <!--div class="main-card mb-3 card">
                                <div class="card-body"-->
                                    <style type="text/css">
                                        tr {cursor: pointer;}
                                    </style>
                                    <?php 
                                    $targetpage = "invoice.php?state=list";
                                    $limit1 = 50;
                                    $limit = 50;
                                    $total_pages = $commonFunctions->getData('sys_erp_sales_invoice','');
                                    $total_pages = count($total_pages);
                                    $stages = 1;
                                    $page = @$_GET['page'];
                                    if($page){
                                        $start = ($page - 1) * $limit; 
                                    }else{
                                        $start = 0; 
                                    } 
                                    $search_con = "";
                                    if(!empty($_GET['search'])){
                                        $search_con = " AND invoice_no LIKE '%".$_GET['search']."%' OR invoice_date LIKE '%".$_GET['search']."%' OR invoice_due_date LIKE '%".$_GET['search']."%' OR project_number LIKE '%".$_GET['search']."%' OR total LIKE '%".$_GET['search']."%' ";

                                        $warehArr = $commonFunctions->getIDs('invty_wrhus','id'," WHERE short_name_location LIKE '%".$_GET['search']."%' ");
                                        $whr_ids = $warehArr['ids'];
                                        if(!empty($whr_ids)){ $search_con .= "  OR branch IN(".$whr_ids.") "; }

                                        $warehArr = $commonFunctions->getIDs('crm_cust_details','id'," WHERE address LIKE '%".$_GET['search']."%' ");
                                        $whr_ids = $warehArr['ids'];
                                        if(!empty($whr_ids)){ $search_con .= "  OR bill_to IN(".$whr_ids.") "; }
                                        if(!empty($whr_ids)){ $search_con .= "  OR ship_to IN(".$whr_ids.") "; }
                                    }
                                    $where = " WHERE id ".$search_con." ORDER BY id DESC LIMIT $start, $limit ";
                                    // Initial page num setup
                                    if ($page == 0){ $page = 1; }
                                    $prev = $page - 1;  
                                    $next = $page + 1;  
                                    $lastpage = ceil($total_pages/$limit);  
                                    $LastPagem1 = $lastpage - 1;    
                                    $paginate = '';
                                    if($lastpage > 1)
                                    {       
                                        $paginate .= "<div class='paginate'>";
                                        // Previous

                                        if ($page > 1){
                                            $paginate.= "<a href='$targetpage&page=$prev'>Previous</a>";
                                        }else{
                                            $paginate.= "<span class='disabled'>Previous</span>";   }
                                        // Pages    
                                        if ($lastpage < 2 + ($stages * 2))  // Not enough pages to breaking it up
                                        {   
                                            for ($counter = 1; $counter <= $lastpage; $counter++)
                                            {
                                                if ($counter == $page){
                                                    $paginate.= "<span class='current'>$counter</span>";
                                                }else{
                                                    $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                            }
                                        }
                                        elseif($lastpage > 2 + ($stages * 2))   // Enough pages to hide a few?
                                        {
                                            // Beginning only hide later pages
                                            if($page < 1 + ($stages * 2))   
                                            {
                                                for ($counter = 1; $counter < 4 + ($stages * 2); $counter++)
                                                {
                                                    if ($counter == $page){
                                                        $paginate.= "<span class='current'>$counter</span>";
                                                    }else{
                                                        $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                                }
                                                $paginate.= "...";
                                                $paginate.= "<a href='$targetpage&page=$LastPagem1'>$LastPagem1</a>";
                                                $paginate.= "<a href='$targetpage&page=$lastpage'>$lastpage</a>";
                                            }
                                            // Middle hide some front and some back
                                            elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2))
                                            {
                                                $paginate.= "<a href='$targetpage&page=1'>1</a>";
                                                $paginate.= "<a href='$targetpage&page=2'>2</a>";
                                                $paginate.= "...";
                                                for ($counter = $page - $stages; $counter <= $page + $stages; $counter++)
                                                {
                                                    if ($counter == $page){
                                                        $paginate.= "<span class='current'>$counter</span>";
                                                    }else{
                                                        $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}    
                                                }
                                                $paginate.= "...";
                                                $paginate.= "<a href='$targetpage&page=$LastPagem1'>$LastPagem1</a>";
                                                $paginate.= "<a href='$targetpage&page=$lastpage'>$lastpage</a>";
                                            }
                                            // End only hide early pages
                                            else
                                            {
                                                $paginate.= "<a href='$targetpage&page=1'>1</a>";
                                                $paginate.= "<a href='$targetpage&page=2'>2</a>";
                                                $paginate.= "...";
                                                for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++)
                                                {
                                                    if ($counter == $page){
                                                        $paginate.= "<span class='current'>$counter</span>";
                                                    }else{
                                                        $paginate.= "<a href='$targetpage&page=$counter'>$counter</a>";}
                                                }
                                            }       
                                        }       
                                                // Next
                                        if ($page < $counter - 1){ 
                                            $paginate.= "<a href='$targetpage&page=$next'>Next</a>";
                                        }else{
                                            $paginate.= "<span class='disabled'>Next</span>";
                                            }
                                        $paginate.= "</div>";   
                                    }
                                    $invtData = $commonFunctions->getData('sys_erp_sales_invoice',$where);

                                    $startP = $limit + $start;
                                    if($startP > @count($invtData) ){
                                        $startP = @count($invtData) + $start;
                                    }
                                    echo "<div style='float: right;'>".$paginate."</div>";?>
                                    <table style="margin-top: 10px;width: 100% !important;" class="table datatable_t table-hover table-striped table-bordered">
                                        <thead>
                                            <tr>
                                                <th class="text-center">Invoice No#</th>
                                                <th class="text-center">Customer</th>
                                                <th class="text-center">Invoice Date</th>
                                                <th class="text-center">Amount</th>
                                                <th class="text-center">Status</th>
                                                <th class="text-center">Created By</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php 
                                            foreach ($invtData as $row) { ?>
                                                <tr onclick="redirect_('invoice-view.php?invoice_id=<?php echo $row['id'];?>')">
                                                    <th class="text-center">
                                                        <?php echo $row['invoice_no']; ?>
                                                    </th>
                                                    <th class="text-center">
                                                        <?php echo $commonFunctions->getname($row['bill_to'],"crm_cust_details","name","id");
                                                        ?>
                                                    </th>
                                                    <th class="text-center">
                                                        <?php echo $row['invoice_date']; ?>
                                                    </th>
                                                    <th class="text-center">
                                                        <?php echo $row['total']; ?>
                                                    </th>
                                                    <th class="text-center">
                                                        <?php if($row['invoice_status'] == 0){ echo "<span class='btn btn-soft-danger btn-sm'>Unpaid</span>"; }
                                                        if($row['invoice_status'] == 1){ echo "<span class='btn btn-soft-success btn-sm'>Paid</span>"; }
                                                        if($row['invoice_status'] == 2){ echo "<span class='btn btn-soft-primary btn-sm'>Overdue</span>"; } ?>
                                                    </th>
                                                    <th class="text-center">
                                                        <?php echo $commonFunctions->getname($row['invoice_creator'],"sys_erp_adm_user","erp_sys_user_name_first","id")." ".$commonFunctions->getname($row['invoice_creator'],"sys_erp_adm_user","erp_sys_user_name_last","id");
                                                        ?>
                                                    </th>
                                                </tr>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                <!--/div>
                            </div-->
                        </div>

                    <?php endif; ?>
            <?php if(@$_GET['state'] == "list"): ?>    
                </div>
            </div>

        </div>
    </div> <!-- end col -->
</div> <!-- end row -->
<?php endif; ?>
        

<div class="modal fade" id="exampleModalDefault" tabindex="-1" role="dialog" aria-labelledby="exampleModalDefaultLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form class="form-group save_popup_form" id="save_popup_form">
                <div class="modal-header">
                    <h6 class="modal-title m-0" id="exampleModalDefaultLabel">Do you want to create delivery note ?</h6>
                    <button type="button" class="close " data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true"><i class="la la-times"></i></span>
                    </button>
                </div><!--end modal-header-->
                <div class="modal-body">
                    <div class="row">
                        <div class="col-lg-3"></div>
                        <div class="col-lg-9">
                            <div class="form-check form-check-inline" style="margin-top: 15px;">
                              <input name="delivery_note_flag" class="delivery_note_flag form-check-input" type="radio" id="inlineCheckbox1" value="1" required="">
                              <label class="form-check-label" for="inlineCheckbox1"><b>I want to make delivery note now.</b></label>
                            </div>             
                        </div><!--end col-->
                        <div class="col-lg-3"></div>
                        <div class="col-lg-9">
                            <div class="form-check form-check-inline" style="margin-top: 15px;">
                              <input name="delivery_note_flag" class="delivery_note_flag form-check-input" type="radio" id="inlineCheckbox2" value="2" required="">
                              <label class="form-check-label" for="inlineCheckbox2"><b>I want to make delivery note later.</b></label>
                            </div>             
                        </div><!--end col-->
                        <div class="col-lg-3"></div>
                        <div class="col-lg-9">
                            <div class="form-check form-check-inline" style="margin-top: 15px;">
                              <input name="delivery_note_flag" class="delivery_note_flag form-check-input" type="radio" id="inlineCheckbox3" value="3" required="">
                              <label class="form-check-label" for="inlineCheckbox3"><b>I don`t want to make delivery note.</b></label>
                            </div>             
                        </div><!--end col-->
                        <div class="col-lg-3"></div>
                        <div class="col-lg-9">
                            <br>
                            <label id="delivery_note_flag-error" class="error" for="delivery_note_flag" style=""></label>
                        </div> 
                    </div><!--end row-->                                                      
                </div><!--end modal-body-->
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Close</button>
                    <button type="button" id="save_popup_form_btn" class="btn btn-primary btn-sm">Save changes</button>
                </div><!--end modal-footer-->
            </form>
        </div><!--end modal-content-->
    </div><!--end modal-dialog-->
</div><!--end modal-->
<?php require "../../inc/footer.php"; ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script type="text/javascript">
    $("#invoice_form").validate({
        ignore: [],
    });
    $(".save_form").click(function(){
        if($("#invoice_form").valid()){
            $("#exampleModalDefault").modal("show");
        }else{
        	Swal.fire('Warning', 'Please fill all required fields!', 'error');
        }
    });
    $("#save_popup_form_btn").click(function(){
        if($("#save_popup_form").valid()){
            var delivery_note_flag = $(".delivery_note_flag:checked").val();
            $.ajax({
                type: 'POST',
                url: "",
                data: $('#invoice_form').serialize()+"&action=ajax_call_2&delivery_note_flag="+delivery_note_flag,
                success: function(response) { 
                    window.location.href = response;
                }
            });
        }
    });
    $("#payment_modes").change(function(){
        $("#payment_modes-error").html("");
        var payment_modes = $("#payment_modes option:selected").text();
        $(".paymode").html(payment_modes);
        if(payment_modes == "Cheque"){
            $(".cheque_div").css("display","");
            /*$("#cheque_name").attr("required","");
            $("#cheque_no").attr("required","");
            $("#cheque_date").attr("required","");
            $("#cheque_bank").attr("required","");*/
        }else{
            $(".cheque_div").css("display","none");
            $("#cheque_name").removeAttr("required","");
            $("#cheque_no").removeAttr("required","");
            $("#cheque_date").removeAttr("required","");
            $("#cheque_bank").removeAttr("required","");
        }
        if(payment_modes == "Bank Transfer"){
            $(".bank_transfer_div").css("display","");
            $("#holder_name").attr("required","");
            $("#trans_date").attr("required","");
            $("#bank").attr("required","");
            $("#transfer_bank").attr("required","");
        }else{
            $(".bank_transfer_div").css("display","none");
            $("#holder_name").removeAttr("required","");
            $("#trans_date").removeAttr("required","");
            $("#bank").removeAttr("required","");
            $("#transfer_bank").removeAttr("required","");
        }
    });    
    $("#payment_terms").change(function(){
        var payment_terms = $("#payment_terms option:selected").text();
        $(".paytype").html(payment_terms);
        $("#payment_terms-error").html("");

        days = $("#payment_terms option:selected").attr("data-id");
        $.ajax({
            type: 'POST',
            url: "",
            data: {"days":days,"action":"ajax_call_5"},
            success: function(response) { 
                var obj = JSON.parse(response);
                $(".invoice_due_date").val(obj.invoice_due_date);
                $(".span_invoice_due_date").html(obj.span_invoice_due_date);
            }
        });
    });
    $("#ship_to").change(function(){
        var ship_to = $("#ship_to option:selected").text();
        $(".custAddress").html(ship_to);
        $("#ship_to-error").html("");
    });    
    $("#cust_po").keyup(function(){
        var cust_po = $("#cust_po").val();
        $(".cust_po").val(cust_po);
        $(".cust_po").html(cust_po);
    });
    $("#project").keyup(function(){
        var project = $("#project").val();
        $(".project_id_label").html(project);
    });
    $("#bill_to").change(function(){
        $("#bill_to-error").html("");
    });
    $(".product_id1").change(function(){
        var warehouse_id = $("#warehouse_id option:selected").val();
        var product_id = $(".product_id1 option:selected").val();
        $.ajax({
            type: 'POST',
            url: "",
            data: {"warehouse_id":warehouse_id,"product_id":product_id,"action":"ajax_call_1"},
            success: function(response) { 
                obj = JSON.parse(response);
                $(".quantity1").attr("max",obj.stock_count);
                $(".unit_price1").val(obj.price);
                $(".unit_price1").attr("min",obj.price);
                $(".product_desc1").val(obj.product_desc);
            }
        });
    });
    $("#warehouse_id").change(function(){
        var warehouse_id = $("#warehouse_id option:selected").val();
        var product_id = $(".product_id1 option:selected").val();
        $.ajax({
            type: 'POST',
            url: "",
            data: {"warehouse_id":warehouse_id,"product_id":product_id,"action":"ajax_call_1"},
            success: function(response) { 
                obj = JSON.parse(response);
                $(".product_id1").html("<option value=''>Select</option>"+obj.option);
                $(".quantity1").attr("max",obj.stock_count);
                $(".unit_price1").val(obj.price);
                $(".product_desc1").val(obj.product_desc);
            }
        });
    });
    $(".quantity1").keyup(function(){
        var quantity = parseInt($(".quantity1").val());
        if(quantity != ''){    
            var unit_price = parseInt($(".unit_price1").val());
            $(".total_pro_amt1").val(unit_price * quantity);

            var total_pro_amt = parseInt($(".total_pro_amt1").val());
            var sub_total_amt = parseInt($(".sub_total_amt").val());
            total_pro_amt = 0;
            $(".total_pro_amt").each(function() {
                total_pro_amt = total_pro_amt + parseInt(this.value);
                $(".sub_total_amt").val(total_pro_amt);
                $(".sub_total_amt").html(total_pro_amt);
                $("#discount").attr("max",total_pro_amt);
                var discount = parseInt($("#discount").val());
                if(discount == ""){ discount = 0; }
                $(".total_amt").html(total_pro_amt - discount);
            });
        }
    });
    $("#bill_to").change(function(){
        var bill_to = $("#bill_to option:selected").val();
        $.ajax({
            type: 'POST',
            url: "",
            data: {"bill_to":bill_to,"action":"ajax_call"},
            success: function(response) { 
                obj = JSON.parse(response);

                $("#ship_to").html("<option value=''>Select</option>"+obj.option);
                $(".email").html(obj.email);
                $(".contact").html(obj.contact);

            }
        });
    });
    $(".btn-step-1").click(function(){
        var warehouse_id = $("#warehouse_id option:selected").val();
        var bill_to = $("#bill_to option:selected").val();
        var ship_to = $("#ship_to option:selected").val();
        var payment_modes = $("#payment_modes option:selected").val();
        var payment_terms = $("#payment_terms option:selected").val();
        if(warehouse_id != '' && bill_to != '' && ship_to != '' && payment_modes != '' && payment_terms != '' ){
            $("#warehouse_id-error").html("");
            $("#bill_to-error").html("");
            $("#ship_to-error").html("");
            $("#payment_modes-error").html("");
            $("#payment_terms-error").html("");

            $(".step-1").css("display","none");
            $(".step-2").css("display","block");
        }else{
            if(warehouse_id == ''){ $("#warehouse_id-error").html("Please enter warehouse name."); }
            if(bill_to == ''){ $("#bill_to-error").html("Please enter bill to."); }
            if(ship_to == ''){ $("#ship_to-error").html("Please enter ship to."); }
            if(payment_modes == ''){ $("#payment_modes-error").html("Please enter payment modes."); }
            if(payment_terms == ''){ $("#payment_terms-error").html("Please enter payment terms."); }
        }
    });
    $(".back_to_first").click(function(){
        $(".step-1").css("display","block");
        $(".step-2").css("display","none");
    });
    $("#discount").keyup(function(){
        var discount = parseInt($("#discount").val());
        if(discount == ""){ discount = 0; }
        var sub_total_amt = parseInt($(".sub_total_amt").val());
        $(".total_amt").html(sub_total_amt - discount);
    });
$(document).ready(function() {
    var i = 2;
    $("body").on("click",".add-more",function(){ 
        //var html = $(".after-add-more").first().clone();
        var html = '<tr class="after-add-more">\
          <td>\
            <select name="product_id[]" class="product_id form-control product_id'+i+'">\
                <option value="0">Select</option>\
            </select>\
          </td>\
          <td>\
          <input type="text" class="form-control product_desc'+i+'" name="product_desc[]" placeholder="Enter Product Description" value="">\
          </td>\
          <td>\
            <input type="text" name="unit_price[]" class="form-control unit_price'+i+'" >\
          </td>\
          <td>\
            <input type="text" name="quantity[]" class="form-control quantity'+i+'" onkeyup="check_quantity('+i+')">\
          </td>\
          <td>\
            <input type="text" name="total_pro_amt[]" class="total_pro_amt form-control total_pro_amt'+i+'" readonly="">\
          </td>\
          <td class="change"><button type="button" class="btn btn-soft-danger btn-icon-circle btn-icon-circle-sm align-self-center remove"><i class="fas fa-times font-16"></i></button></td>\
       </tr>';
        $(html).find(".change").html("<button type='button' class='btn btn-soft-danger btn-icon-circle btn-icon-circle-sm align-self-center remove'><i class='fas fa-times font-16'></i></button><a style='width: 100px;display:none;' class='btn btn-secondary move_stack"+i+"' href='javascript:void(0)' onclick='redirect_stock_movement("+i+")' >Move Stock</a>");      
        $(".after-add-more").last().after(html);
        var j = i;
        
        $('.product_id'+i).select2();

        var warehouse_id = $("#warehouse_id option:selected").val();
        var product_id = $(".product_id"+j+" option:selected").val();
        var value = [];
        $(".product_id option:selected").each(function() {
            value.push(this.value);
            //$(".product_id"+j+" option:[value='"+value+"']").prop('disabled', true);
        });
        $.ajax({
            type: 'POST',
            url: "",
            data: {"warehouse_id":warehouse_id,"product_id":product_id,"action":"ajax_call_1","already_selected":value},
            success: function(response) { 
                obj = JSON.parse(response);
                $(".product_id"+j).html("<option value=''>Select</option>"+obj.option);
                $(".quantity"+j).attr("max",obj.stock_count);
                $(".unit_price"+j).val(obj.price);
                $(".unit_price"+j).attr("min",obj.price);
                $(".product_desc"+j).val(obj.product_desc);
            }
        });

        $(".product_id"+j).change(function(){
            var warehouse_id = $("#warehouse_id option:selected").val();
            var product_id = $(".product_id"+j+" option:selected").val();
            $.ajax({
                type: 'POST',
                url: "",
                data: {"warehouse_id":warehouse_id,"product_id":product_id,"action":"ajax_call_1"},
                success: function(response) { 
                    obj = JSON.parse(response);
                    $(".quantity"+j).attr("max",obj.stock_count);
                    $(".unit_price"+j).val(obj.price);
                    $(".unit_price"+j).attr("min",obj.price);
                    $(".product_desc"+j).val(obj.product_desc);
                }
            });
        });
        $(".quantity"+j).keyup(function(){
            var quantity = parseInt($(".quantity"+j).val());
            if(quantity != ''){    
                var unit_price = parseInt($(".unit_price"+j).val());
                $(".total_pro_amt"+j).val(unit_price * quantity);

                var total_pro_amt = parseInt($(".total_pro_amt"+j).val());
                var sub_total_amt = parseInt($(".sub_total_amt").val());
                total_pro_amt = 0;
                $(".total_pro_amt").each(function() {
                    total_pro_amt = total_pro_amt + parseInt(this.value);
                    $(".sub_total_amt").val(total_pro_amt);
                    $(".sub_total_amt").html(total_pro_amt);
                    $("#discount").attr("max",total_pro_amt);
                    var discount = parseInt($("#discount").val());
                    if(discount == ""){ discount = 0; }
                    $(".total_amt").html(total_pro_amt - discount);
                });
                
            }
        });
        i++;
    });

    $("body").on("click",".remove",function(){ 
        $(this).parents(".after-add-more").remove();
    });
});
</script>
<script>
    $( function() {
        $( "#cheque_date,#trans_date" ).datepicker();
    } );
    function redirect_(uri){
        window.location.href = uri;
    }
</script>
<script type="text/javascript">
    //var table = $(".datatableCust").dataTable();
	$(".bill_to_btn").click(function(){
		$.ajax({
            type: 'POST',
            url: "",
            data: {"action":"ajax_call_3"},
            success: function(response) { 
                $("#bill_to_tbody").html(response);
                $(".datatableCust").dataTable();
            }
        });
	});
	function set_bill_to_data(id){
		var bill_to_ = $("#bill_to_"+id).val();
		$(".custAddressBillTo").html(bill_to_);
		$("#bill_to").val(id);
		$("#billToModal").modal("hide");
		$(".bill_to_btn").html("Edit");
	}

	$(".ship_to_btn").click(function(){
		var bill_to = $("#bill_to").val();
		if(bill_to != ''){	
			$.ajax({
	            type: 'POST',
	            url: "",
	            data: {"action":"ajax_call_4","bill_to":bill_to},
	            success: function(response) { 
	                $(".ship_to_tbody").html(response);
	                $(".datatableCust").dataTable();
	            }
	        });
	    }else{
	    	$("#ship_to_modal").modal("hide");
	    	alert("Please select bill to first!");
	    }
	});

	
	function set_ship_to_data(id){
		var ship_to_ = $("#ship_to_"+id).val();
		$(".custAddressShipTo").html(ship_to_);
		$("#ship_to").val(id);
		$("#ship_to_modal").modal("hide");
		$(".ship_to_btn").html("Edit");
	}
	$(".cust_po_btn").click(function(){
		$("#cust_po_modal").modal("show");
	});
	$(".paymode_btn").click(function(){
		$("#paymode_modal").modal("show");
	});
	$(".paytype_btn").click(function(){
		$("#paytype_modal").modal("show");
	});
	$(".project_id_label_btn").click(function(){
		$("#project_id_label_modal").modal("show");
	});
	$(".add_warehose").click(function(){
		var text = $("#warehouse_id option:selected").text();
		$(".branch_name").html("<br>"+text);
		$(".wharehouse_btn").html("Edit");
		$("#wharehouseModal").modal("hide");
	});
	function change_label(class_n,modal_id){
		$("."+class_n).html("Edit");
		$("#"+modal_id).modal("hide");
	}
	function redirect_stock_movement(i){
		var product_id = $(".product_id"+i+" option:selected").val();
		var warehouse_id = $("#warehouse_id option:selected").val();
		if(product_id != "undefined" && product_id != ''){
			var url = "<?php echo DOCUMENT_ROOT_CLASS;?>product-services/inventory/stock-movements.php?state=add&warehouse_id="+warehouse_id+"&product_id="+product_id;
			
			$("<a>").prop({
	            target: "_blank",
	            href: url
	        })[0].click();
			//$('a').attr('target', '_blank').attr('href', "<?php echo DOCUMENT_ROOT_CLASS;?>product-services/inventory/stock-movements.php?state=add&warehouse_id="+warehouse_id+"&product_id="+product_id).trigger('click');
		}else{
			Swal.fire('Warning', 'Please select product!', 'error');			
		}
	}

$("#warehouse_id").change();
function check_quantity(inc){
    var quantity = $(".quantity"+inc).val();
    var maxquantity = $(".quantity"+inc).attr("max");
    if(parseInt(quantity) > parseInt(maxquantity)){
        Swal.fire('Warning', 'Sorry stock not available please request for stock movement by clicking on move stock...', 'error');
        $(".move_stack"+inc).css("display","block");
    }else{
        $(".move_stack"+inc).css("display","none");
    }
}
</script>
