<?php session_start();
//error_reporting(0);
//define('SITEURL','http://mutakamela.ddns.net:53557/erp/');
/*define('SITEURL','http://itscircle.dyndns.org:81/taylor2/');*/
//define('SITEURL','http://localhost:81/property/');
define('SITEURL','http://85.234.131.96:81/hotel/');
 try {
    $hostname = "local";
    $port = 10060;
    $dbname = "al_qalam_live";
    //$username = "ali";
    //$pw = "Ali123";
    $username="sa";
    $pw="hamabd@20";
    //Driver={SQL Server};Server=$hostname;Database=$dbname;
   $connection = odbc_connect("hotel", $username, $pw);
  } catch (Exception $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }
// $stmt = odbc_prepare($connection,'select top 5 * from inventory');
  /*$result=odbc_exec($connection,'select top 5 * from inventory');
  while ($row = odbc_fetch_array($result)) {
    print_r($row);
  }*/
  //unset($dbh); unset($stmt);
function TotalSalesChart()
{
  $data=array();
    $data[0]='Q1';
    $data[1]='Q2';
    $data[2]='Q3';
    $data[3]='Q4';
    $data[4]='Q5';
    $data[5]='Q6';
    $data[6]='Q7';
    $data[7]='Q8';
    $data[8]='Q9';
    $data[9]='Q10';
    $data[10]='Q11';
    $data[11]='Q12';
    $data[12]='Q13';
    $data[13]='Q14';
    echo  implode(",",$data);
}
  function GenerateSalesInvoice($connection,$InvoiceID=0,$UserName)
  {

 odbc_autocommit($connection, FALSE);
//$details=array_keys($_POST);
//$d=json_decode(($details[0].$details[1]));
//print_r($d);
//$InvoiceID=$_GET['InvoiceID'];

//remove previous generated invoice
$sqlupdate="update VoucherMaster set active=0,DeleteLog='".$UserName."' where VoucherTypeID=8 and ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);
              $sqlupdate="update VoucherDetails set IsDelete=1 where ReferenceInvoiceID=".$InvoiceID;
              odbc_exec($connection,$sqlupdate);


    $sql="select * from InvoiceMaster where InvoiceID=".$InvoiceID;
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $NetAmount=$row['NetAmount'];//im
      $InvoiceDate=$row['InvoiceDate'];
      $Narration="";
      $ReferenceInvoiceID=$InvoiceID;
      $AmountDebit=0;
      $AmountCredit=0;
      $GodownID=$row['GodownID'];
      $TotalTaxAmount=$row['TotalTaxAmount'];//im
      $TotalAmount=$row['TotalAmount'];//im
      $InvoiceType=$row['InvoiceType'];
      $KeyField=$row['KeyField'];
      $SupplierID=$row['SupplierID'];//im


    }
              $fields=array();
            $VoucherID=getmaxId("VoucherMaster","VoucherID",$connection)+1;
         $fields['VoucherID']=$VoucherID;
           $fields['VoucherNo']=$KeyField;//isset($VoucherNo)?$VoucherNo:0;
           $fields['TotalAmount']=isset($NetAmount)?$NetAmount:0;
           $fields['Active']=1;//isset($Active)?$Active:0;
           $fields['VoucherDate']=isset($InvoiceDate)?$InvoiceDate:null;
           $fields['Narration']=isset($Narration)?$Narration:0;
           $fields['Posted']=1;//isset($Posted)?$Posted:0;
           $fields['IsPostDated']=0;//isset($IsPostDated)?$IsPostDated:0;
           $fields['VoucherTypeID']=8;//isset($VoucherTypeID)?$VoucherTypeID:0;
           $fields['PeriodID']=1;//isset($PeriodID)?$PeriodID:0;
           $fields['ReferenceInvoiceID']=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $fields['SupplierID']=0;//isset($SupplierID)?$SupplierID:0;
           $fields['LedgerID']=isset($SupplierID)?$SupplierID:0;
           $fields['AmountDebit']=isset($AmountDebit)?$AmountDebit:0;
           $fields['AmountCredit']=isset($AmountCredit)?$AmountCredit:0;
           $fields['IsAuto']=1;//isset($IsAuto)?$IsAuto:0;
           $fields['LocationID']=isset($GodownID)?$GodownID:0;
           $fields['ReferenceVoucherID']=isset($ReferenceVoucherID)?$ReferenceVoucherID:0;
           $fields['GroupID']=isset($GroupID)?$GroupID:0;
           $fields['MultiVoucher']=0;//isset($MultiVoucher)?$MultiVoucher:0;
           $fields['VoucherToBePosted']=1;//isset($VoucherToBePosted)?$VoucherToBePosted:0;
           $fields['Cash']=0;//isset($Cash)?$Cash:0;
           $fields['ContractID']=0;//isset($ContractID)?$ContractID:0;
           $fields['UserID']=isset($UserID)?$UserID:0;
           $fields['VoucherDateTime']=isset($VoucherDateTime)?$VoucherDateTime:date("Y-m-d H:i:s");
           $fields['PaymentType']=isset($PaymentType)?$PaymentType:'';
         //  print_r($fields);
          InsertVoucherMaster2($fields,$InvoiceType,$InvoiceID,$connection);  

        $fdetails=array();  
        for($a=0;$a<2;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$SupplierID;//$d->CustomerLedgerID; DEbit side entry
           if($a==0)
           {
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            $CreditLedgerID=106;//$d->VATLedgerID;
           }
          else
          {
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
              $CreditLedgerID=170;//$d->SalesLedgerID;
          }
           $fdetails['Debit']=$Debit;
           $fdetails['Credit']=$Credit;
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="JOB CARD INVOICE"; 
           //print_r($fdetails);
       InsertVoucherDetail($fdetails,$InvoiceType,$VoucherID,$connection);              
        }//end for 
        //update master invoice 
         $updateinvoice="update InvoiceMaster set AutoVoucherID=$VoucherID,InvoiceStatus=4,editLog='".$UserName."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$updateinvoice);
        $ReferenceInvoiceID=getnamesingle("InvoiceMaster","ReferenceInvoiceID","InvoiceID",$InvoiceID,$connection);
        if($ReferenceInvoiceID>0)
        {
        $sql="update InvoiceMaster set InvoiceStatus=4 where InvoiceID=".$ReferenceInvoiceID;
odbc_exec($connection,$sql);
        }
        $sqlupdate="update VoucherMaster set CreateLog='".$UserName."' where VoucherTypeID=8 and ReferenceInvoiceID=".$InvoiceID;
        odbc_exec($connection,$sqlupdate);
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Invoice Generated Sucessfully');
           date_default_timezone_set("Asia/Muscat");

          $details='{"details":"Invoice Generated, NetAmount='.$NetAmount.'","Query":"","file":"'.$_SERVER['SCRIPT_FILENAME'].'"}';
  ActivityLog($connection,'Invoice Generated',$details,$_SESSION['UserName'], $InvoiceID,$VoucherID,$NetAmount,$KeyField,1,4,$_SERVER['REMOTE_ADDR']);  
  $ret=1;
  }
  else
  {
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Invoice Can Not BE Generated');
      $ret=0;
  }
  //  echo json_encode($res);
return $ret;

  }
  function getCardBalance($connection,$COAID)
  {
    $data=0;
          $sql="select (sum(Debit)-sum(Credit)) as Balance from CardTransaction where COAID=$COAID";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $data=$row['Balance'];
    }
  //echo json_encode($data);  
    return $data;
  }
 function getAccountBalance($connection,$COAID=0)
 {
  $data=0;
$sql="select isnull(sum(isnull(debit,0))-sum(isnull(credit,0)),0) as balance  from GeneralLedger where COAID=$COAID";
$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
while($row=odbc_fetch_array($result))
{
$data=$row['balance'];
}
return $data;
 } 

function ActivityLog($connection,$title='',$details='',$username='',$invoiceid=0,$voucherid=0,$amount=0,$reference='',$godownid=0,$status=0,$ip='')
  {
    $userTimezone = new DateTimeZone('Asia/Muscat');

 date_default_timezone_set("Asia/Muscat");

    $ID=getMaxId("ActivityLog","ID",$connection)+1;
    if($ID<1)$ID=1;
       odbc_autocommit($connection, FALSE);
  $time=date("Y-m-d H:i:s");
  if($amount=="" || $amount==null) $amount=0;
   //   $time=$userTimezone->format('Y-m-d H:i:s'); 
    $sql="insert into ActivityLog (ID,actiontitle,actiontime,godownid,actiondetails,username,invoiceid,voucherid,amount,reference,status,ip) values($ID,'$title','$time',$godownid,'$details','$username',$invoiceid,$voucherid,$amount,'$reference',$status,'$ip')";
odbc_exec($connection, $sql) or die(odbc_error().$sql);

if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}
  }

function getCardCodeDecode($a)
{
$str="";
  if($a=="")return "";
	if($a!="")
	{
		$arr=str_split($a, 2);

//print_r($arr);
$arr1=array();
$count=3;
foreach($arr as $k)
{
$ka=str_split($k, 1);
$temp=$ka[0];
$k[0]=$ka[1];
$k[1]=$temp;
$arr1[$count]=$ka;  
$count--;
}
//print_r($arr1);
//$str=implode($arr1);
//print_r($arr1);

for($i=0;$i<count($arr1);$i++)
{
$str =$str.$arr1[$i][0];
$str =$str.$arr1[$i][1];
}
	}
return $str;
}
function getCardCode($a)
{
$arr=str_split($a, 2);

//print_r($arr);
$arr1=array();
$count=3;
foreach($arr as $k)
{
$ka=str_split($k, 1);
$temp=$ka[0];
$k[0]=$ka[1];
$k[1]=$temp;
$arr1[$count]=$ka;  
$count--;
}
//print_r($arr1);
//$str=implode($arr1);
//print_r($arr1);
$str="";
for($i=0;$i<count($arr1);$i++)
{
$str =$str.$arr1[$i][0];
$str =$str.$arr1[$i][1];
}
return $str;
}


  function getMaxId($table,$field,$connection)
  {
    $data="";
    $sql="select max($field) as id from $table";
    $result=odbc_exec($connection, $sql);
    while($row=odbc_fetch_array($result))
    {
      $data=$row['id'];
    }
    return $data;
  }

  function getnamewhere($table,$fields,$where="1=1",$connection)
  {
 $data=array();
    $sql="select $fields from $table where $where";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $data=$row;
    }
    return json_encode($data);
  }
  
  function getnamesingle($table,$field,$exp=1,$value=1,$connection)
  {
    $data="";
    if($value!="")
    {
  $sql="select $field from $table where $exp=$value";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $data=utf8_encode($row[$field]);
    }
    }
return $data;
  }
function getSum($table,$field,$exp=1,$value=1,$connection)
  {
    $data="";
    if($value!="")
    {
  $sql="select $field from $table where $exp=$value";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
      $data=utf8_encode($row['sum']);
    }
    }
return $data;
  }
  function generateCode2($table,$field,$where,$rep,$connection)
  {
    $data="";//array();//"";
    if($where!="")
    {
    $sql="select replace(max(VoucherNo),'$rep','')+1 as total from $table where $where";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    $row=odbc_num_rows($result);
   // print_r($row);
      $data=$row;
    
    }
return $data;
  }

  function generateCode($table,$field,$where,$connection)
  {
    $data="";//array();//"";
    if($where!="")
    {
    $sql="select @@ROWCOUNT as total from $table where $where";
    $result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
    $row=odbc_num_rows($result);
   // print_r($row);
      $data=$row;
    
    }
return $data;
  }
  function generateGLCode($under,$NatureID,$connection)
{
    $total=1;
    $sql="select count(COAID) as total from accounts where under=$under and NatureID=$NatureID";
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row=odbc_fetch_array($result))
    {
            $total=$row['total'];
            $total=$total+1;
    }
return $total;
}
function getDataType2($conn,$table,$field)
{
  $data=array();
   $sql="select data_type from information_schema.columns where table_name='$table' and column_name='$field'";
$result=odbc_exec($conn,$sql);
if(odbc_num_rows($result)>0)
{
  $data=odbc_fetch_array($result);

//print_r($data);
if($data['data_type']=="varchar" || $data['data_type']=="nvarchar" || $data['data_type']=="time" || $data['data_type']=="datetime" || $data['data_type']=="date" || $data['data_type']=="smalldatetime" || $data['data_type']=="time")
{
    return true;
} 
else 
  {
    return false;
  }
}
else
{
  return false;
} //echo json_encode($data);// print_r($data); 

}
function insertStock($InvoiceID,$main,$mrdetail,$InvoiceType,$connection)
{
            $Reference =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  
      $ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
            $GodownID =isset($main->GodownID)?$main->GodownID:0;
            $SupplierID =isset($main->SupplierID)?$main->SupplierID:0;
            $SupplierName =isset($main->SupplierName)?$main->SupplierName:'';
            $Location =isset($main->Location)?$main->Location:0;
                      $InvoiceDate =isset($main->BillDate)?$main->BillDate:'';
            $Narration =isset($main->Narration)?$main->Narration:'';
            $Narration=htmlspecialchars($Narration);
$ReferenceInvoiceID =isset($main->ReferenceInvoiceID)?$main->ReferenceInvoiceID:0;

            $InvoiceType =isset($main->InvoiceType)?$main->InvoiceType:0;
            $QuoteReference =isset($main->QuoteReference)?$main->QuoteReference:null;
            $Notes =isset($main->Notes)?$main->Notes:'';
            $DueDate =isset($main->DeliveryDate)?$main->DeliveryDate:'';
    odbc_autocommit($connection, FALSE);
                $sql="delete from stockledger where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);
       //     print_r($_REQUEST);
            for($a=0;$a<count($mrdetail);$a++)
            {
            $Flag =isset($mrdetail[$a]->Flag)?$mrdetail[$a]->Flag:'';
            if($Flag!="D")
            {
//
            $ItemID =isset($mrdetail[$a]->Item_ItemID)?$mrdetail[$a]->Item_ItemID:'';
            $JobCardItem=isset($mrdetail[$a]->JobCardItem)?$mrdetail[$a]->JobCardItem:'';
            if($JobCardItem!="")$ItemID=getnamesingle("Inventory","ID","Name","'".$JobCardItem."'",$connection);
            
            $ItemName =isset($mrdetail[$a]->Item_ItemName)?$mrdetail[$a]->Item_ItemName:'';
            $Color =isset($mrdetail[$a]->Item_Color)?$mrdetail[$a]->Item_Color:'';
            $Size =isset($mrdetail[$a]->Item_Size)?$mrdetail[$a]->Item_Size:'';
            $Barcode =isset($mrdetail[$a]->Item_Barcode)?$mrdetail[$a]->Item_Barcode:'';
            $Category =isset($mrdetail[$a]->Item_Category)?$mrdetail[$a]->Item_Category:'';
            $Brand =isset($mrdetail[$a]->Item_Brand)?$mrdetail[$a]->Item_Brand:'';
            $Item_KeyField =isset($mrdetail[$a]->Item_KeyField)?$mrdetail[$a]->Item_KeyField:'';
            
            $UnitPrice =(isset($mrdetail[$a]->Rate) && $mrdetail[$a]->Rate!="")?$mrdetail[$a]->Rate:0;
            $StockQty =isset($mrdetail[$a]->StockQty)?$mrdetail[$a]->StockQty:0;
            $ItemTable =isset($mrdetail[$a]->ItemTable)?$mrdetail[$a]->ItemTable:'';
            $Qty =isset($mrdetail[$a]->Qty)?$mrdetail[$a]->Qty:0;
            //}
   $ReceivedQty=(isset($mrdetail[$a]->ReceivedQty) && $mrdetail[$a]->ReceivedQty!="")?(double)$mrdetail[$a]->ReceivedQty:0;
    $Amount =(isset($mrdetail[$a]->Amount) && $mrdetail[$a]->Amount>0)?$mrdetail[$a]->Amount:($ReceivedQty*$UnitPrice);
            $Discount =(isset($mrdetail[$a]->Discount) && $mrdetail[$a]->Discount>=0)?(double)$mrdetail[$a]->Discount:0;
            $TaxPercent =(isset($mrdetail[$a]->VAT) && $mrdetail[$a]->VAT>0)?(double)$mrdetail[$a]->VAT:0;
            $NetAmount =(isset($mrdetail[$a]->NetAmount) && $mrdetail[$a]->NetAmount>0)?$mrdetail[$a]->NetAmount:0;
            $TaxAmount =(isset($mrdetail[$a]->VATAmount) && $mrdetail[$a]->VATAmount>0)?$mrdetail[$a]->VATAmount:0;
            $DiscountAmount =(isset($mrdetail[$a]->DiscountAmount) && $mrdetail[$a]->DiscountAmount>0)?$mrdetail[$a]->DiscountAmount:0;
            $Attr2 =isset($mrdetail[$a]->PartNumber)?$mrdetail[$a]->PartNumber:'';
            $Attr1 =isset($mrdetail[$a]->Specification)?$mrdetail[$a]->Specification:'';
            $Narration =isset($mrdetail[$a]->Narration)?$mrdetail[$a]->Narration:'';
            $ReferenceTransactionID =isset($mrdetail[$a]->ReferenceTransactionID)?$mrdetail[$a]->ReferenceTransactionID:'';
            $JobCardItem =isset($mrdetail[$a]->JobCardItem)?$mrdetail[$a]->JobCardItem:'';
            $TransactionID =isset($mrdetail[$a]->TransactionID)?$mrdetail[$a]->TransactionID:'';
         $VehicleBrandID=isset($mrdetail[$a]->VehicleBrandID)?$mrdetail[$a]->VehicleBrandID:'';
         $Attr3=isset($mrdetail[$a]->VehicleBrandName)?$mrdetail[$a]->VehicleBrandName:'';
         $VehicleModelID=isset($mrdetail[$a]->VehicleModelID)?$mrdetail[$a]->VehicleModelID:'';
         $VehicleTypeID=isset($mrdetail[$a]->VehicleTypeID)?$mrdetail[$a]->VehicleTypeID:'';

         $Attr4=isset($mrdetail[$a]->VehicleModelName)?$mrdetail[$a]->VehicleModelName:'';
            $Cost =isset($mrdetail[$a]->Cost)?$mrdetail[$a]->Cost:0;

            $UnitID=1;
            $TotalNetAmount=0;
              if($InvoiceType==8)
              {
/*                [{"Company_ID":"2","Company_Value":"","BaseType_ID":"SERVICE","BaseType_Value":"SERVICE","MainCategory_ID":"41","MainCategory_Value":"41","SubCategory_ID":"Mechanical works for Japanese","SubCategory_Value":"Mechanical works for Japanese","Brand_ID":"ACTIVE","Brand_Value":"ACTIVE","Level_ID":"2.00","Level_Value":"2.00","Item_ItemID":"296","Item_ItemName":"Mechanical works for Japanese","Item_Barcode":"I-0000181","Qty":"3.0000","Rate":"200.0000","Amount":"600.0000","Discount":".0000","VAT":"5.00","VATAmount":"30.00","NetAmount":"630.0000","TransactionID":"7385","Flag":"R","SNo":"2","Narration":"hdud ouo yioy  "},{"Company_ID":"2","Company_Value":"","BaseType_ID":"SERVICE","BaseType_Value":"SERVICE","MainCategory_ID":"30","MainCategory_Value":"30","SubCategory_ID":"Engine oil change ( with out  Filter )","SubCategory_Value":"Engine oil change ( with out  Filter )","Brand_ID":"ACTIVE","Brand_Value":"ACTIVE","Level_ID":"1.00","Level_Value":"1.00","Item_ItemID":"31","Item_ItemName":"Engine oil change ( with out  Filter )","Item_Barcode":"I-0000003","Qty":"1.0000","Rate":"20.0000","Amount":"20.0000","Discount":".0000","VAT":"5.00","VATAmount":"1.00","NetAmount":"21.0000","TransactionID":"7377","Flag":"R","SNo":"1","Narration":"test test"}]*/
      /*  $ItemID=isset($mrdetail[$a]->ItemID)?$mrdetail[$a]->ItemID:0;
        $ItemName =isset($mrdetail[$a]->ItemName)?$mrdetail[$a]->ItemName:'';
            $Color =isset($mrdetail[$a]->Color)?$mrdetail[$a]->Color:'';
            $Size =isset($mrdetail[$a]->Size)?$mrdetail[$a]->Size:'';
            $Barcode =isset($mrdetail[$a]->Barcode)?$mrdetail[$a]->Barcode:'';
            $Category =isset($mrdetail[$a]->Category)?$mrdetail[$a]->Category:'';
            $Brand =isset($mrdetail[$a]->Brand)?$mrdetail[$a]->Brand:'';
            $Item_KeyField =isset($mrdetail[$a]->KeyField)?$mrdetail[$a]->KeyField:'';*/
            $Cost =isset($mrdetail[$a]->Cost)?$mrdetail[$a]->Cost:0;
                $Category =isset($mrdetail[$a]->MainCategory_ID)?$mrdetail[$a]->MainCategory_ID:0;
                $Level_ID =isset($mrdetail[$a]->Level_ID)?$mrdetail[$a]->Level_ID:0;
                $VATPercent= (isset($mrdetail[$a]->VAT) && $mrdetail[$a]->VAT>0)?(double)$mrdetail[$a]->VAT:0;
                $VATAmount =(isset($mrdetail[$a]->VATAmount) && $mrdetail[$a]->VATAmount>0)?$mrdetail[$a]->VATAmount:0;
              }
            else
            {
                 $VATPercent=$TaxPercent;
            $VATAmount=$TaxAmount;
            }
              
              $ID=getmaxId("stockledger","ID",$connection)+1;
              $ItemID=isset($ItemID)?$ItemID:0;
           $ReferenceItemID=isset($ItemID)?$ItemID:0;
           $Qty=isset($Qty)?$Qty:0;
           $InvoiceTypeID=isset($InvoiceType)?$InvoiceType:0;
           $InvoiceID=isset($InvoiceID)?$InvoiceID:0;
           $ReferenceInvoiceID=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $Reference=isset($Reference)?$Reference:'';
           $Remarks=isset($Narration)?$Narration:'';
           $GodownID=isset($GodownID)?$GodownID:0;
           $ProjectID=isset($ProjectID)?$ProjectID:0;
           $BranchID=isset($BranchID)?$BranchID:$_SESSION['BRANCHID'];
           $COAID=isset($SupplierID)?$SupplierID:0;
           $Active=1;//isset($Active)?$Active:0;
           $ContainerNo=isset($Attr2)?$Attr2:$Attr1;
           $UserID=isset($UserID)?$UserID:0;
           $Rate=isset($UnitPrice)?$UnitPrice:0;
           $CounterID=isset($CounterID)?$CounterID:0;
           $VoucherID=isset($VoucherID)?$VoucherID:0;
           $TransDate=isset($InvoiceDate)?$InvoiceDate:'';
           $ExpiryDate=isset($DueDate)?$DueDate:'';
           $SupplierID=isset($SupplierID)?$SupplierID:0;
           $DepartmentID=isset($DepartmentID)?$DepartmentID:0;
// update the main item in the stock ledger 
$sql="INSERT INTO [taylor].[dbo].[StockLedger]
           ([ID]
           ,[ItemID]
           ,[ReferenceItemID]
           ,[Qty]
           ,[InvoiceTypeID]
           ,[InvoiceID]
           ,[ReferenceInvoiceID]
           ,[Reference]
           ,[Remarks]
           ,[GodownID]
           ,[ProjectID]
           ,[BranchID]
           ,[COAID]
           ,[Active]
           ,[ContainerNo]
           ,[UserID]
           ,[Rate]
           ,[CounterID]
           ,[VoucherID]
           ,[TransDate]
           ,[ExpiryDate]
           ,[SupplierID]
           ,[DepartmentID]
           ,[ItemJson])
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           $Qty,
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $DepartmentID,'$ItemJson')"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);

//end code here            
           $sqlmaterial="select * from inventory_ingredients where ItemID=$ItemID";
           $resultmaterial=odbc_exec($connection,$sqlmaterial);
           while($rowmaterial=odbc_fetch_array($resultmaterial))
           {
                          $ID=getmaxId("stockledger","ID",$connection)+1;

            $ItemID=$rowmaterial['MaterialID'];
            $Qty2=$rowmaterial['Qty'];
            $Qt=$Qty*$Qty2;
                      //code for stock ledger 
  $sql="INSERT INTO [taylor].[dbo].[StockLedger]
           ([ID]
           ,[ItemID]
           ,[ReferenceItemID]
           ,[Qty]
           ,[InvoiceTypeID]
           ,[InvoiceID]
           ,[ReferenceInvoiceID]
           ,[Reference]
           ,[Remarks]
           ,[GodownID]
           ,[ProjectID]
           ,[BranchID]
           ,[COAID]
           ,[Active]
           ,[ContainerNo]
           ,[UserID]
           ,[Rate]
           ,[CounterID]
           ,[VoucherID]
           ,[TransDate]
           ,[ExpiryDate]
           ,[SupplierID]
           ,[DepartmentID])
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qt).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $DepartmentID)"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);

         }
                 /*$sql="insert into invoicedetail (
InvoiceID
           ,ItemID
           ,UnitPrice
           ,QTY
           ,Amount
           ,UnitID
           ,NetAmount
           ,TaxPercent
           ,TaxAmount
           ,Narration
           ,TotalNetAmount
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,itemBrand
           ,itemCode
           ,itemSize           
           ,VATPercent
           ,VATAmount
           ,ReceivedQty
           ,StockQty
           ,isDelete
           ,DiscountAmount
           ,DiscountPercent
        ) values("
       .$InvoiceID."
           ,".$ItemID."
           ,".$UnitPrice."
           ,".$Qty."
           ,".$Amount."
           ,".$UnitID."
           ,".$NetAmount."
           ,".$TaxPercent."
           ,".$TaxAmount."
           ,'".$Narration."'
           ,".$TotalNetAmount."
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Cost."'
           ,'".$VehicleBrandID."'
           ,'".$VehicleModelID."'                      
           ,'".$VehicleTypeID."'  
           ,".$VATPercent."
           ,".$VATAmount."
           ,".$ReceivedQty.
          ",".$StockQty.",0,".$DiscountAmount.",".$Discount.")";*/
       //   odbc_exec($connection, $sql) or die(odbc_error().$sql);
          }//end if flag
          }//end for loop
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}

}
function insertInvoiceDetail($InvoiceID,$mrdetail,$InvoiceType,$connection)
{
    odbc_autocommit($connection, FALSE);
                $sql="delete from invoiceDetail where InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);
       //     print_r($_REQUEST);
            for($a=0;$a<count($mrdetail);$a++)
            {
            $Flag =isset($mrdetail[$a]->Flag)?$mrdetail[$a]->Flag:'';
            if($Flag!="D")
            {
//
            $ItemID =isset($mrdetail[$a]->Item_ItemID)?$mrdetail[$a]->Item_ItemID:'';
            $JobCardItem=isset($mrdetail[$a]->JobCardItem)?$mrdetail[$a]->JobCardItem:'';
            if($JobCardItem!="")$ItemID=getnamesingle("Inventory","ID","Name","'".$JobCardItem."'",$connection);
            
            $ItemName =isset($mrdetail[$a]->Item_ItemName)?$mrdetail[$a]->Item_ItemName:'';
            $Color =isset($mrdetail[$a]->Item_Color)?$mrdetail[$a]->Item_Color:'';
      $Size =isset($mrdetail[$a]->Item_Size)?$mrdetail[$a]->Item_Size:'';
      $DueDate =isset($mrdetail[$a]->DueDate)?$mrdetail[$a]->DueDate:'';
$InvoiceDate =isset($mrdetail[$a]->InvoiceDate)?$mrdetail[$a]->InvoiceDate:'';
            $Barcode =isset($mrdetail[$a]->Item_Barcode)?$mrdetail[$a]->Item_Barcode:'';
            $Category =isset($mrdetail[$a]->Item_Category)?$mrdetail[$a]->Item_Category:'';
            $Brand =isset($mrdetail[$a]->Item_Brand)?$mrdetail[$a]->Item_Brand:'';
            $Item_KeyField =isset($mrdetail[$a]->Item_KeyField)?$mrdetail[$a]->Item_KeyField:'';
            
            $UnitPrice =(isset($mrdetail[$a]->Rate) && $mrdetail[$a]->Rate!="")?$mrdetail[$a]->Rate:0;
            $StockQty =isset($mrdetail[$a]->StockQty)?$mrdetail[$a]->StockQty:0;
            $ItemTable =isset($mrdetail[$a]->CategorySize)?$mrdetail[$a]->CategorySize:'';
            $Qty =isset($mrdetail[$a]->Qty)?$mrdetail[$a]->Qty:0;
         //    $CategorySize=json_decode($mrdetail[$a]->CategorySize);
          $Picture1 =isset($mrdetail[$a]->Picture1)?$mrdetail[$a]->Picture1:'';
          $Picture2 =isset($mrdetail[$a]->Picture2)?$mrdetail[$a]->Picture2:'';

            //}
   $ReceivedQty=(isset($mrdetail[$a]->ReceivedQty) && $mrdetail[$a]->ReceivedQty!="")?(double)$mrdetail[$a]->ReceivedQty:0;
    $Amount =(isset($mrdetail[$a]->Amount) && $mrdetail[$a]->Amount>0)?$mrdetail[$a]->Amount:($ReceivedQty*$UnitPrice);
            $Discount =(isset($mrdetail[$a]->Discount) && $mrdetail[$a]->Discount>=0)?(double)$mrdetail[$a]->Discount:0;
            $TaxPercent =(isset($mrdetail[$a]->VAT) && $mrdetail[$a]->VAT>0)?(double)$mrdetail[$a]->VAT:0;
            $NetAmount =(isset($mrdetail[$a]->NetAmount) && $mrdetail[$a]->NetAmount>0)?$mrdetail[$a]->NetAmount:0;
            $TaxAmount =(isset($mrdetail[$a]->VATAmount) && $mrdetail[$a]->VATAmount>0)?$mrdetail[$a]->VATAmount:0;
            $DiscountAmount =(isset($mrdetail[$a]->DiscountAmount) && $mrdetail[$a]->DiscountAmount>0)?$mrdetail[$a]->DiscountAmount:0;
            $Attr2 =isset($mrdetail[$a]->PartNumber)?$mrdetail[$a]->PartNumber:'';
            $Attr1 =isset($mrdetail[$a]->Specification)?$mrdetail[$a]->Specification:'';
            $Narration =isset($mrdetail[$a]->Narration)?$mrdetail[$a]->Narration:'';
            $ReferenceTransactionID =isset($mrdetail[$a]->ReferenceTransactionID)?$mrdetail[$a]->ReferenceTransactionID:'';
            $JobCardItem =isset($mrdetail[$a]->JobCardItem)?$mrdetail[$a]->JobCardItem:'';
            $TransactionID =isset($mrdetail[$a]->TransactionID)?$mrdetail[$a]->TransactionID:'';
         $VehicleBrandID=isset($mrdetail[$a]->VehicleBrandID)?$mrdetail[$a]->VehicleBrandID:'';
         $Attr3=isset($mrdetail[$a]->VehicleBrandName)?$mrdetail[$a]->VehicleBrandName:'';
         $VehicleModelID=isset($mrdetail[$a]->VehicleModelID)?$mrdetail[$a]->VehicleModelID:'';
         $VehicleTypeID=isset($mrdetail[$a]->VehicleTypeID)?$mrdetail[$a]->VehicleTypeID:'';
         $CategorySize=isset($mrdetail[$a]->CategorySize)?$mrdetail[$a]->CategorySize:'';

         $Attr4=isset($mrdetail[$a]->VehicleModelName)?$mrdetail[$a]->VehicleModelName:'';
            $Cost =(isset($mrdetail[$a]->Cost) && $mrdetail[$a]->Cost!="")?$mrdetail[$a]->Cost:0;
            $CompanyID =(isset($mrdetail[$a]->CompanyID) && $mrdetail[$a]->CompanyID!="")?$mrdetail[$a]->CompanyID:0;

            $UnitID=1;
            $TotalNetAmount=0;
              if($InvoiceType==8)
              {
/*                [{"Company_ID":"2","Company_Value":"","BaseType_ID":"SERVICE","BaseType_Value":"SERVICE","MainCategory_ID":"41","MainCategory_Value":"41","SubCategory_ID":"Mechanical works for Japanese","SubCategory_Value":"Mechanical works for Japanese","Brand_ID":"ACTIVE","Brand_Value":"ACTIVE","Level_ID":"2.00","Level_Value":"2.00","Item_ItemID":"296","Item_ItemName":"Mechanical works for Japanese","Item_Barcode":"I-0000181","Qty":"3.0000","Rate":"200.0000","Amount":"600.0000","Discount":".0000","VAT":"5.00","VATAmount":"30.00","NetAmount":"630.0000","TransactionID":"7385","Flag":"R","SNo":"2","Narration":"hdud ouo yioy  "},{"Company_ID":"2","Company_Value":"","BaseType_ID":"SERVICE","BaseType_Value":"SERVICE","MainCategory_ID":"30","MainCategory_Value":"30","SubCategory_ID":"Engine oil change ( with out  Filter )","SubCategory_Value":"Engine oil change ( with out  Filter )","Brand_ID":"ACTIVE","Brand_Value":"ACTIVE","Level_ID":"1.00","Level_Value":"1.00","Item_ItemID":"31","Item_ItemName":"Engine oil change ( with out  Filter )","Item_Barcode":"I-0000003","Qty":"1.0000","Rate":"20.0000","Amount":"20.0000","Discount":".0000","VAT":"5.00","VATAmount":"1.00","NetAmount":"21.0000","TransactionID":"7377","Flag":"R","SNo":"1","Narration":"test test"}]*/
      /*  $ItemID=isset($mrdetail[$a]->ItemID)?$mrdetail[$a]->ItemID:0;
        $ItemName =isset($mrdetail[$a]->ItemName)?$mrdetail[$a]->ItemName:'';
            $Color =isset($mrdetail[$a]->Color)?$mrdetail[$a]->Color:'';
            $Size =isset($mrdetail[$a]->Size)?$mrdetail[$a]->Size:'';
            $Barcode =isset($mrdetail[$a]->Barcode)?$mrdetail[$a]->Barcode:'';
            $Category =isset($mrdetail[$a]->Category)?$mrdetail[$a]->Category:'';
            $Brand =isset($mrdetail[$a]->Brand)?$mrdetail[$a]->Brand:'';
            $Item_KeyField =isset($mrdetail[$a]->KeyField)?$mrdetail[$a]->KeyField:'';*/
            $Cost =isset($mrdetail[$a]->Cost)?$mrdetail[$a]->Cost:0;
                $Category =isset($mrdetail[$a]->MainCategory_ID)?$mrdetail[$a]->MainCategory_ID:0;
                $Level_ID =isset($mrdetail[$a]->Level_ID)?$mrdetail[$a]->Level_ID:0;
                $VATPercent= (isset($mrdetail[$a]->VAT) && $mrdetail[$a]->VAT>0)?(double)$mrdetail[$a]->VAT:0;
                $VATAmount =(isset($mrdetail[$a]->VATAmount) && $mrdetail[$a]->VATAmount>0)?$mrdetail[$a]->VATAmount:0;
              }
            else
            {
                 $VATPercent=$TaxPercent;
            $VATAmount=$TaxAmount;
            }
              
              $TransactionID=getmaxId("invoiceDetail","TransactionID",$connection)+1;
                 $sql="insert into invoicedetail (
InvoiceID
           ,ItemID
           ,UnitPrice
           ,QTY
           ,Amount
           ,UnitID
           ,NetAmount
           ,TaxPercent
           ,TaxAmount
           ,Narration
           ,TotalNetAmount
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,itemBrand
           ,itemCode
           ,itemSize           
           ,VATPercent
           ,VATAmount
           ,ReceivedQty
           ,StockQty
           ,isDelete
           ,DiscountAmount
           ,DiscountPercent,InvoiceDate,DueDate,BranchID
        ) values("
       .$InvoiceID."
           ,".$ItemID."
           ,".$UnitPrice."
           ,".$Qty."
           ,".$Amount."
           ,".$UnitID."
           ,".$NetAmount."
           ,".$TaxPercent."
           ,".$TaxAmount."
           ,'".$Narration."'
           ,".$TotalNetAmount."
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Cost."'
           ,'".$VehicleBrandID."'
           ,'".$VehicleModelID."'                      
           ,'".$VehicleTypeID."'  
           ,".$VATPercent."
           ,".$VATAmount."
           ,".$ReceivedQty.
          ",".$StockQty.",0,".$DiscountAmount.",".$Discount.",'".$InvoiceDate."','".$DueDate."',".$CompanyID.")";
          odbc_exec($connection, $sql) or die(odbc_error().$sql);
          }//end if flag
          //insert Category size 
            $c=0;
          /*  $sql="delete from InvoiceMaster_JobDetail where TextBoxName='CategorySize' and invoiceid=$InvoiceID";
            odbc_exec($connection, $sql) or die(odbc_error().$sql);

//isset($mrdetail[$a]->CategorySize)?$mrdetail[$a]->CategorySize:0;    
       $CategorySize=json_decode($mrdetail[$a]->CategorySize);
       $CS=json_encode($CategorySize);
       //print_r($CategorySize[0]);
       for($c=0;$c<count($CategorySize);$c++)
       {
       $MasterValueID=$CategorySize[$c]->MasterValueID;
       $Description=$CategorySize[$c]->MasterValue;
       $TextBoxName='CategorySize';
       $Particular=$CategorySize[$c]->MasterValue;
       //$ItemID=$mrdetail[$a]->Item_ItemID;
$sqlupdate="update invoiceDetail set ItemJson='$CS',AttrPictureLocation1='$Picture1',AttrPictureLocation2='$Picture2' where InvoiceID=$InvoiceID and ItemID=$ItemID";
   odbc_exec($connection, $sqlupdate) or die(odbc_error().$sqlupdate);
  $sql ="insert into InvoiceMaster_JobDetail (InvoiceID,MasterValueID,Description,TextBoxName,Particulars,ItemID) values(".$InvoiceID.",".$MasterValueID.",'".$Description."','".$TextBoxName."','".$Particular."',".$ItemID.")";
   odbc_exec($connection, $sql) or die(odbc_error().$sql);*/
      //}
 //$mrdetails->ItemTable=$value->CategorySize;
              //InsertJList($InvoiceID,$CategorySize,'CategorySize',$connection);

 /*foreach($mrdetails as $value )
    {
       $CategorySize=json_decode($value->CategorySize);
//$mrdetails->ItemTable=$value->CategorySize;
              //InsertJList($InvoiceID,$CategorySize,'CategorySize',$connection);
       }*/
          //insert category size
          }//end for loop
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}
}

function InsertJList($InvoiceID,$listdata,$TextBoxName,$connection)
{
    odbc_autocommit($connection, FALSE);
  //delete previsou record 
  $sql="delete from InvoiceMaster_JobDetail where InvoiceID=".$InvoiceID." and TextBoxName='".$TextBoxName."'";
  odbc_exec($connection, $sql);
$data=json_decode($listdata);
//print_r($data);

  for($f=0;$f<count($data);$f++)
  {
    $MasterValueID=isset($data[$f]->MasterValueID)?$data[$f]->MasterValueID:0;
    $Description=isset($data[$f]->Value)?$data[$f]->Value:0;
    $Particular=isset($data[$f]->Particular)?$data[$f]->Particular:'';
    if($Particular=='')
    $Particular=isset($data[$f]->MasterValue)?$data[$f]->MasterValue:'';
  /*  echo $Particular;
    print_r($_SESSION);
 */
    if(isset($_SESSION[$Particular]))
    {
    $pl=$_SESSION[$Particular];
    $PictureLocation=$pl[$Particular];
    }
    else
    {
      $PictureLocation='';  
    } 
/*    if($PictureLocation!="")
    {*/
      $sql ="insert into InvoiceMaster_JobDetail (InvoiceID,MasterValueID,Description,TextBoxName,Particulars,PictureLocation) values(".$InvoiceID.",".$MasterValueID.",'".$Description."','".$TextBoxName."','".$Particular."','".$PictureLocation."')";
     /* }
     else
     {
      $sql ="insert into InvoiceMaster_JobDetail (InvoiceID,MasterValueID,Description,TextBoxName,Particulars) values(".$InvoiceID.",".$MasterValueID.",'".$Description."','".$TextBoxName."','".$Particular."')";
     }*/ 
     odbc_exec($connection, $sql) or die(odbc_error().$sql);

  }
  //echo $sql."<Br>";
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}
}//end insertJLIST 

function InsertVoucherMasterJob($fields,$InvoiceType,$InvoiceID,$connection)
{
   odbc_autocommit($connection, FALSE);

            $NetAmount=$fields['TotalAmount'];
            /*$Posted=1;
            $IsPostDated=1;
      $LedgerID=0;
            $AmountDebit=0;
            $AmountCredit=0;
            $Active=1;
            $PeriodID=1;
            $IsAuto=1;
            $Cash=0;
            $ContractID=0;
            $VoucherDateTime=date("Y-m-d m:i:s");
            $PaymentType="Credit";
            $ReferenceInvoiceID=$InvoiceID;
            $ReferenceVoucherID=0;
            $VoucherPostDateTime=0;
            $VoucherToBePosted=1;
            $MultiVoucher=0;
            $UserID=0;
            $GroupID=1;
            $LocationID=$GodownID;
            $VoucherTypeID=71;
            $VoucherDate=$InvoiceDate;
            *///$TotalAmount=$TotalAmount
            //insert into voucher 
              $sql="INSERT INTO [dbo].[VoucherMaster]
           ([VoucherID]
           ,[VoucherNo]
           ,[TotalAmount]
           ,[Active]
           ,[VoucherDate]
           ,[Narration]
           ,[Posted]
           ,[IsPostDated]
           ,[VoucherTypeID]
           ,[PeriodID]
           ,[ReferenceInvoiceID]
           ,[LedgerID]
           ,[AmountDebit]
           ,[AmountCredit]
           ,[IsAuto]
           ,[LocationID]
           ,[ReferenceVoucherID]
           ,[GroupID]
           ,[MultiVoucher]
           ,[VoucherToBePosted]
           ,[Cash]
           ,[ContractID]
           ,[UserID]
           ,[VoucherDateTime]
           ,[PaymentType],SelectionID,CreateLog)
     VALUES(".$fields['VoucherID']."
           ,'".$fields['VoucherNo']."'
           ,".$fields['TotalAmount']."
           ,".$fields['Active']."
           ,'".$fields['VoucherDate']."'
           ,'".$fields['Narration']."'
           ,".$fields['Posted']."
           ,".$fields['IsPostDated']."
           ,".$fields['VoucherTypeID']."
           ,".$fields['PeriodID']."
           ,".$fields['ReferenceInvoiceID']."
           ,".$fields['SupplierID']."
           ,".$fields['AmountDebit']."
           ,".$fields['AmountCredit']."
           ,".$fields['IsAuto']."
           ,".$fields['LocationID']."
           ,".$fields['ReferenceVoucherID']."
           ,".$fields['GroupID']."
           ,".$fields['MultiVoucher']."
           ,".$fields['VoucherToBePosted']."
           ,".$fields['Cash']."
           ,".$fields['ContractID']."
           ,".$fields['UserID']."
           ,'".$fields['VoucherDateTime']."'
           ,'".$fields['PaymentType']."',".$fields['SelectionID'].",'".$_SESSION['UserName']."'
     )";
   
            
            odbc_exec($connection,$sql) or die(odbc_error().$sql);  
 if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}           

}
function InsertVoucherMaster2($fields,$InvoiceType,$InvoiceID,$connection)
{
   odbc_autocommit($connection, FALSE);
            $NetAmount=$fields['TotalAmount'];
            $ChequeNo=isset($fields['ChequeNo'])?$fields['ChequeNo']:'';
  $ClientBankAccountName=isset($fields['ClientBankAccountName'])?$fields['ClientBankAccountName']:'';
  $ChequeStatus=isset($fields['ChequeStatus'])?$fields['ChequeStatus']:'0';
 $isVoucherReturnCheque=isset($fields['isVoucherReturnCheque'])?$fields['isVoucherReturnCheque']:'0';
  $ChequeDate=isset($fields['ChequeDate'])?$fields['ChequeDate']:'';
            /*$Posted=1;
            $IsPostDated=1;
      $LedgerID=0;
            $AmountDebit=0;
            $AmountCredit=0;
            $Active=1;
            $PeriodID=1;
            $IsAuto=1;
            $Cash=0;
            $ContractID=0;
            $VoucherDateTime=date("Y-m-d m:i:s");
            $PaymentType="Credit";
            $ReferenceInvoiceID=$InvoiceID;
            $ReferenceVoucherID=0;
            $VoucherPostDateTime=0;
            $VoucherToBePosted=1;
            $MultiVoucher=0;
            $UserID=0;
            $GroupID=1;
            $LocationID=$GodownID;
            $VoucherTypeID=71;
            $VoucherDate=$InvoiceDate;
            *///$TotalAmount=$TotalAmount
            $sql="select * from VoucherMaster where active=0 and VoucherTypeID=8 and  ReferenceInvoiceID=".$InvoiceID;
            $result=odbc_exec($connection,$sql);
            $VoucherID=0;
            if(odbc_num_rows($result)>0)
            {
              $row=odbc_fetch_array($result);
              $VoucherID=$row['VoucherID'];
             $sql="update VoucherMaster set TotalAmount=".$NetAmount.",editlog='".$_SESSION['UserName']."' where ReferenceInvoiceID=".$InvoiceID;
     //       odbc_exec($connection,$sql) or die(odbc_error().$sql);  
            }
            else
            {

            //insert into voucher 
             $sql="INSERT INTO [dbo].[VoucherMaster]
           ([VoucherID]
           ,[VoucherNo]
           ,[TotalAmount]
           ,[Active]
           ,[VoucherDate]
           ,[Narration]
           ,[Posted]
           ,[IsPostDated]
           ,[VoucherTypeID]
           ,[PeriodID]
           ,[ReferenceInvoiceID]
           ,[LedgerID]
           ,[AmountDebit]
           ,[AmountCredit]
           ,[IsAuto]
           ,[LocationID]
           ,[ReferenceVoucherID]
           ,[GroupID]
           ,[MultiVoucher]
           ,[VoucherToBePosted]
           ,[Cash]
           ,[ContractID]
           ,[UserID]
           ,[VoucherDateTime]
           ,[PaymentType],CreateLog,ChequeNo,ClientBankAccountName,ChequeTypeStatus,isVoucherReturnCheque,ChequeDate)
     VALUES(".$fields['VoucherID']."
           ,'".$fields['VoucherNo']."'
           ,".$fields['TotalAmount']."
           ,".$fields['Active']."
           ,'".$fields['VoucherDate']."'
           ,'".$fields['Narration']."'
           ,".$fields['Posted']."
           ,".$fields['IsPostDated']."
           ,".$fields['VoucherTypeID']."
           ,".$fields['PeriodID']."
           ,".$fields['ReferenceInvoiceID']."
           ,".$fields['SupplierID']."
           ,".$fields['AmountDebit']."
           ,".$fields['AmountCredit']."
           ,".$fields['IsAuto']."
           ,".$fields['LocationID']."
           ,".$fields['ReferenceVoucherID']."
           ,".$fields['GroupID']."
           ,".$fields['MultiVoucher']."
           ,".$fields['VoucherToBePosted']."
           ,".$fields['Cash']."
           ,".$fields['ContractID']."
           ,".$fields['UserID']."
           ,'".$fields['VoucherDateTime']."'
           ,'".$fields['PaymentType']."','".$_SESSION['UserName']."',
           '$ChequeNo','$ClientBankAccountName',$ChequeStatus,$isVoucherReturnCheque,'$ChequeDate'
     )";
            odbc_exec($connection,$sql) or die(odbc_error().$sql);  
            
   }
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}            
}
function InsertVoucherMaster($fields,$InvoiceType,$InvoiceID,$connection)
{
   odbc_autocommit($connection, FALSE);
            $NetAmount=$fields['TotalAmount'];
            $ChequeNo=isset($fields['ChequeNo'])?$fields['ChequeNo']:'';
  $ClientBankAccountName=isset($fields['ClientBankAccountName'])?$fields['ClientBankAccountName']:'';
  $ChequeStatus=isset($fields['ChequeStatus'])?$fields['ChequeStatus']:'0';
 $isVoucherReturnCheque=isset($fields['isVoucherReturnCheque'])?$fields['isVoucherReturnCheque']:'0';
  $ChequeDate=isset($fields['ChequeDate'])?$fields['ChequeDate']:'';
            /*$Posted=1;
            $IsPostDated=1;
      $LedgerID=0;
            $AmountDebit=0;
            $AmountCredit=0;
            $Active=1;
            $PeriodID=1;
            $IsAuto=1;
            $Cash=0;
            $ContractID=0;
            $VoucherDateTime=date("Y-m-d m:i:s");
            $PaymentType="Credit";
            $ReferenceInvoiceID=$InvoiceID;
            $ReferenceVoucherID=0;
            $VoucherPostDateTime=0;
            $VoucherToBePosted=1;
            $MultiVoucher=0;
            $UserID=0;
            $GroupID=1;
            $LocationID=$GodownID;
            $VoucherTypeID=71;
            $VoucherDate=$InvoiceDate;
            *///$TotalAmount=$TotalAmount
            $sql="select * from VoucherMaster where active=1 and ReferenceInvoiceID=".$InvoiceID;
            $result=odbc_exec($connection,$sql);
            $VoucherID=0;
            if(odbc_num_rows($result)>0)
            {
              $row=odbc_fetch_array($result);
              $VoucherID=$row['VoucherID'];
             $sql="update VoucherMaster set TotalAmount=".$NetAmount.",editlog='".$_SESSION['UserName']."' where ReferenceInvoiceID=".$InvoiceID;
     //       odbc_exec($connection,$sql) or die(odbc_error().$sql);  
            }
            else
            {

            //insert into voucher 
             $sql="INSERT INTO [dbo].[VoucherMaster]
           ([VoucherID]
           ,[VoucherNo]
           ,[TotalAmount]
           ,[Active]
           ,[VoucherDate]
           ,[Narration]
           ,[Posted]
           ,[IsPostDated]
           ,[VoucherTypeID]
           ,[PeriodID]
           ,[ReferenceInvoiceID]
           ,[LedgerID]
           ,[AmountDebit]
           ,[AmountCredit]
           ,[IsAuto]
           ,[LocationID]
           ,[ReferenceVoucherID]
           ,[GroupID]
           ,[MultiVoucher]
           ,[VoucherToBePosted]
           ,[Cash]
           ,[ContractID]
           ,[UserID]
           ,[VoucherDateTime]
           ,[PaymentType],CreateLog,ChequeNo,ClientBankAccountName,ChequeTypeStatus,isVoucherReturnCheque,ChequeDate)
     VALUES(".$fields['VoucherID']."
           ,'".$fields['VoucherNo']."'
           ,".$fields['TotalAmount']."
           ,".$fields['Active']."
           ,'".$fields['VoucherDate']."'
           ,'".$fields['Narration']."'
           ,".$fields['Posted']."
           ,".$fields['IsPostDated']."
           ,".$fields['VoucherTypeID']."
           ,".$fields['PeriodID']."
           ,".$fields['ReferenceInvoiceID']."
           ,".$fields['SupplierID']."
           ,".$fields['AmountDebit']."
           ,".$fields['AmountCredit']."
           ,".$fields['IsAuto']."
           ,".$fields['LocationID']."
           ,".$fields['ReferenceVoucherID']."
           ,".$fields['GroupID']."
           ,".$fields['MultiVoucher']."
           ,".$fields['VoucherToBePosted']."
           ,".$fields['Cash']."
           ,".$fields['ContractID']."
           ,".$fields['UserID']."
           ,'".$fields['VoucherDateTime']."'
           ,'".$fields['PaymentType']."','".$_SESSION['UserName']."',
           '$ChequeNo','$ClientBankAccountName',$ChequeStatus,$isVoucherReturnCheque,'$ChequeDate'
     )";
            odbc_exec($connection,$sql) or die(odbc_error().$sql);  
            
   }
if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}            
}
function InsertVoucherDetail($fields,$InvoiceType,$InvoiceID,$connection)
{
    odbc_autocommit($connection, FALSE);
    if(isset($fields['TransactionType']))
                $TransactionType=$fields['TransactionType'];
    else  
              $TransactionType="PURCHASE A/C";
            /*$Debit=$TotalAmount;
            $Credit=$TotalAmount;
            $CreditLedgerID=$SupplierID;*/
            $CostCenterID=1;
            $IsDelete=0;
            $DebitCostCenterID=1;
            $fields['ChequeNo']=isset($fields['ChequeNo'])?$fields['ChequeNo']:'';
            $Narrationdetail="Narration details here";
          //  $LedgerID=$PurchaseLedgerID;
            $sqldetail="INSERT INTO [dbo].[VoucherDetails]
           ([VoucherID]
           ,[LedgerID]
           ,[Debit]
           ,[Credit]
           ,[Narration]
           ,[ReferenceInvoiceID]
           ,[CreditLedgerID]
           ,[CostCenterID]
           ,[IsDelete]
           ,[DebitCostCenterID]
           ,[TransactionType],ChequeNo)
     VALUES(".$fields['VoucherID']
           .",".$fields['LedgerID']
           .",".$fields['Debit']
           .",".$fields['Credit']
           .",'".$fields['Narration']
           ."',".$fields['ReferenceInvoiceID']
           .",".$fields['CreditLedgerID']
           .",".$fields['CostCenterID']
           .",".$fields['IsDelete']
           .",".$fields['DebitCostCenterID']
           .",'".$fields['TransactionType']."','".$fields['ChequeNo']."')";
 odbc_exec($connection,$sqldetail) or die(odbc_error().$sqldetail); 
   if (!odbc_error())
   {
      odbc_commit($connection);
      $res=array('status'=>"ok",'description'=>'Data Saved Sucessfully');
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}
}
function userrights($Userid,$Sidebar,$permit,$connection)
{
      $sql="select $permit from Web_Privileges where Userid=$Userid and SidebarID=$Sidebar";
    $result=odbc_exec($connection,$sql);
    if(odbc_num_rows($result)>0)
    {
      $row=odbc_fetch_array($result);
      $permit=str_replace("[","", $permit);
      $permit=str_replace("]","", $permit);
      $ans=$row[$permit];
      
        return $ans;
    }
    else
    {
        return 0;
    }
}
function save($pic,$oldfile,$path)
{
$upload_dir =$path;            
$size_bytes = 9388608;

$extlimit = "yes";
$limitedext = array(".gif",".jpg",".GIF",".JPG",".png",".jpeg",".swf",".png",".Png",".PNG",".txt",".doc",".docx",".xls",".pdf");
          if (!is_dir("$upload_dir")) { 
         die ("<center>The directory <b>($upload_dir)</b> doesn't exist"); 
          } 
          if (!is_writeable("$upload_dir")){ 
             die ("<center>The directory <b>($upload_dir)</b> is NOT writable, Please CHMOD (777)"); 
          }
                $file =  $oldfile; 
              if(file_exists($upload_dir.$file)){ 
        @unlink($upload_dir."/$file");//delete the previous file
              }
              $size = $pic['size']; 
              if ($size > $size_bytes) 
              { 
                    $kb = $size_bytes / 1024; 
                    echo "<center>File Too Large. File must be <b>$kb</b> KB. <br>»<a href=\"$_SERVER[PHP_SELF]\">back</a>"; 
                    exit(); 
              } 
              $ext = strrchr($pic['name'],'.'); 
              if (($extlimit == "yes") && (!in_array($ext,$limitedext))) { 
                    echo("<center>Wrong file extension. ");
                    echo "<br><a href='javascript:history.go(-1)'>Click here to go back</a>"; 
                    exit(); 
              } 
              $filename =  $pic['name']; 
              if(file_exists($upload_dir.$filename)){ 
                    echo "<center>A image with the name <b>$filename </b>already exists change the name of your Image. <br>»<a href=\"$_SERVER[PHP_SELF]\">back</a>"; 
                    exit(); 
              }  
              if (move_uploaded_file($pic['tmp_name'],$upload_dir.$filename)) {
          chmod($upload_dir.$filename, 0644);
              } 
                  else 
              { 
                  echo "<center>There was a problem saving your file.<br>please try again later <br>»<a href=\"$_SERVER[PHP_SELF]\">back</a>"; 
                   
              }
              
}
?>