<?php session_start();
//define('SITEURL','http://itscircle.dyndns.org:81/restapp/');
//define('SITEURL','http://localhost:81/restapi/');
//define('SITEURL','http://94.76.193.54/meatshop/');
define('SITEURL','http://localhost/groccery/');
 try {
    $hostname = "local";
    $port = 10060;
    $dbname = "al_qalam_live";
    $username = "sa";
    //$pw = "Dima@123";
    $pw="hamabd";
    //Driver={SQL Server};Server=$hostname;Database=$dbname;
   $connection = odbc_connect("groccery", $username, $pw);
     // $connection1 = odbc_connect("restapp", $username, $pw);
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
  }
//$SalesLedgerID=$_SESSION['SETTING']['SALES'];

 // $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 getCostPrice($ItemID,$GodownID,$InvoiceDate,$connection)
{
 $Balance=0; 
 if($ItemID>0)
 {
 if($GodownID>0)
  $GodownID2="GodownID=$GodownID and ";
else
$GodownID2="";

 if($InvoiceDate!='')
  $InvoiceDate2=" Invoiceid in(select InvoiceID from InvoiceMAster where InvoiceDate<='".$InvoiceDate."' and active=1 and InvoiceType in (0,4)) and ";
else
$InvoiceDate2="";

$searchbox="".$GodownID2.$InvoiceDate2;

  $sql="select top 1 isnull(UnitPrice,0) as Balance from invoiceDetail where $searchbox ItemID=$ItemID  order by InvoiceID desc";

  $result=odbc_exec($connection, $sql);
  while($row=odbc_fetch_array($result))
  {
  $Balance=$row['Balance'];
  }
}
  return $Balance;  
}
function getStockBalance($ItemID,$GodownID,$InvoiceDate,$connection)
{
 $Balance=0; 
 if($ItemID>0)
 {
 if($GodownID>0)
  $GodownID2="GodownID=$GodownID and ";
else
$GodownID2="";

 if($InvoiceDate!='')
  $InvoiceDate2=" convert(date,TransDate)<='".$InvoiceDate."' and ";
else
$InvoiceDate2="";

$searchbox="".$GodownID2.$InvoiceDate2;

  $sql="select isnull(sum(Qty),0) as Balance from StockLedger where $searchbox ItemID=$ItemID and InvoiceTypeID>0";


  $result=odbc_exec($connection, $sql);
  while($row=odbc_fetch_array($result))
  {
  $Balance=$Balance+$row['Balance'];
  }
}
  return $Balance; 
}

  function getBranches($connection)
  {
      $data=array();
$sql="SELECT '['+name+'].dbo.' as DbName,(select top 1 GodownID from Godowns where AdditionalInfo5=dbid) as GodownID,
dbid FROM master.dbo.sysdatabases where dbid in (select  convert(numeric,(case when AdditionalInfo5='' or AdditionalInfo5=null  then 1 else AdditionalInfo5 end),0) from Godowns where degree=1)
and dbid>1";
$result=odbc_exec($connection, $sql) or die(odbc_error().$sql);
   while ($row = odbc_fetch_array($result)) {
  
    $data []=$row;
      }//end while
      //print_r($data);
      return json_encode($data); 
  
  }
  function getRawMaterial($ItemID,$InvoiceID,$connection)
  {
    $data=array();
      if($ItemID!="" && $InvoiceID!="" )
      {
$sql="select *  from ViewStockLedger where InvoiceID=".$InvoiceID." and ReferenceItemID=".$ItemID;
    $result=odbc_exec($connection,$sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
    }
      }
      return json_encode($data);
  }
  function GenerateCostOfGoodSold($connection,$InvoiceID,$Branch)
  {/*
$value=$Branch;
odbc_autocommit($connection, FALSE);
             $fields=array();
            $VoucherID=getmaxId("VoucherMaster","VoucherID",$connection)+1;
$NetAmount=$subtotal;

         $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);  

//code for branch cash and payment 
          
/*$sql="select * from ".$Branch."VoucherDetails where ReferenceInvoiceID=".$InvoiceID." and Debit>0";
$result1=odbc_exec($connection,$sql);
while($row1=odbc_fetch_array($result1))
    {

   odbc_autocommit($connection, FALSE);
$fdetails=array();  
           $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$row1['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']=$row1['Debit'];
           $fdetails['Credit']=$row1['Credit'];
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=0;//$CreditLedgerID;
           $fdetails['CostCenterID']=0;//$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="Copy From Branch"; 
           //print_r($fdetails);
       InsertVoucherDetail2($fdetails,$InvoiceType,$VoucherID,$connection);              
        
      }*/
/*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;
  }
  */}
function GenerateSalesVoucherPayment($connection,$InvoiceID,$UserName,$Branch,$subtotal,$GodownID)
{
$LocationID=$GodownID;
$value=$Branch;
 //odbc_autocommit($connection, FALSE);
//$details=array_keys($_POST);
//$d=json_decode(($details[0].$details[1]));
//print_r($d);
//$InvoiceID=$_GET['InvoiceID'];
 $sql="select * from SalesInvoiceMaster where active=0 and InvoiceID=".$InvoiceID;
$result2=odbc_exec($connection,$sql) or die(odbc_error().$sql);
if(odbc_num_rows($result2)>0)
{
$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);

}
else
{
//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 SalesInvoiceMaster where active=1 and InvoiceID=".$InvoiceID;
    //$r=$sql;
    $result2=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    while($row2=odbc_fetch_array($result2))
    {
      $NetAmount=$row2['NetAmount'];//im
      $InvoiceDate=$row2['InvoiceDate'];
      $Narration="";
      $ReferenceInvoiceID=$InvoiceID;
      $AmountDebit=0;
      $AmountCredit=$NetAmount;
      $GodownID=$row2['GodownID'];
      $TotalTaxAmount=$row2['TotalTaxAmount'];//im
      $TotalAmount=$row2['TotalAmount'];//im
      $InvoiceType=$row2['InvoiceType'];
      $KeyField=$row2['KeyField'];
      $SupplierID=$row2['CustomerID'];//im
$sql="select * from ".$value."vouchermaster where ReferenceInvoiceID=$ReferenceInvoiceID and active=1";
//return $sql;
      $result3=odbc_exec($connection,$sql);
      /*if(odbc_num_rows($result3)>0)
      {*/
      while($row3=odbc_fetch_array($result3)) 
      {

        $VoucherID=getmaxId("VoucherMaster","VoucherID",$connection)+1;
        $VoucherIDOLD=$row3['VoucherID'];
        $VoucherTypeID=$row3['VoucherTypeID'];
        $VoucherNo=$row3['VoucherNo'];
        $ReferenceInvoiceID=$row3['ReferenceInvoiceID'];
        $LocationID=$row3['LocationID'];//>1)?$row3['LocationID']:0;
        $Active=$row3['Active'];

$deletesql="delete VoucherMaster where VoucherID=".$VoucherIDOLD;       
odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

$deletesql="delete voucherdetails where VoucherID=".$VoucherIDOLD;;       
odbc_exec($connection,$deletesql) or die(odbc_error().$deletesql);

if($Active==1)
{
      if($VoucherTypeID==1)$VoucherTypeID=5;
      if($VoucherTypeID==2)$VoucherTypeID=5;
      
      if($VoucherTypeID==3)$VoucherTypeID=6;
      if($VoucherTypeID==4)$VoucherTypeID=6;

        if($VoucherTypeID==5)$VoucherTypeID=7;
        elseif($VoucherTypeID==6)$VoucherTypeID=71;
        elseif($VoucherTypeID==7)$VoucherTypeID=8;
if($LocationID==1)
{
if($VoucherTypeID==5)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=5 and LocationID=1",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
          $VoucherNo="RV-".$VoucherNo;
        }
        if($VoucherTypeID==6)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=6 and LocationID=1",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
          $VoucherNo="PV-".$VoucherNo;
        }
        if($VoucherTypeID==8)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=8 and LocationID=1",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
          $VoucherNo="SV-".$VoucherNo;
        }
        if($VoucherTypeID==7)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=7  and LocationID=1",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
          $VoucherNo="JV-".$VoucherNo;
        }
        if($VoucherTypeID==10)
        {
          $VoucherNo=generateCode("vouchermaster","VoucherNo","VoucherTypeID=10  and LocationID=1",$connection)+1;
          $VoucherNo=str_pad($VoucherNo,7,"0",STR_PAD_LEFT);
          $VoucherNo="PTC-".$VoucherNo;
        }
}

$sqlinsert="insert into vouchermaster (VoucherID,[VoucherNo]
      ,[TotalAmount]
      ,[Active]
      ,[VoucherDate]
      ,[Narration]
      ,[Posted]
      ,[IsPostDated]
      ,[PostDate]
      ,[VoucherTypeID]
      ,[ChequeNo]
      ,[PONO]
      ,[DD]
      ,[TC]
      ,[PeriodID]
      ,[ReferenceInvoiceID]
      ,[ClientBankAccountName]
      ,[LedgerID]
      ,[AmountDebit]
      ,[AmountCredit]
      ,[IsAuto]
      ,[WorkOrderID]
      ,[LocationID]
      ,[VoucherPostDateTime]
      ,[CreateLog]
      ,[EditLog]
      ,[DeleteLog]
      ,[EmployeeID]
      ,[CostCenterID]
      ,[Received]
      ,[Balance]
      ,[ReferenceVoucherID]
      ,[GroupID]
      ,[ClientPayeeName]
      ,[AmountInWords]
      ,[PostDatedCh]
      ,[MultiVoucher]
      ,[VoucherToBePosted]
      ,[Cash]
      ,[PDCDayshold]
      ,[ChequeStatus]
      ,[SelectionID]
      ,[PDCPostDate]
      ,[PDCPostHoldDate]
      ,[IsVoucherReturnCheque]
      ,[ContractID]
      ,[UserID]
      ,[ApprovalDate]
      ,[ApprovalDescription]
      ,[ApprovalDescriptionReturn]
      ,[ApprovalToBePosted]
      ,[ApprovalToBeReturn]
      ,[CounterID]
      ,[ShiftNo]
      ,[NatureID]
      ,[InvoiceTypeID]
      ,[BankBranchName]
      ,[BankLedgerID]
      ,[PDCVoucherReferenceID]
      ,[ChequeStatusID]
      ,[BankDate]
      ,[NewLedgerID]
      ,[NewChequeStatusID]
      ,[PaymentID]
      ,[VoucherReferenceInvoiceID]
      ,[IsAutoPettyCashVoucher])
SELECT VoucherID
      ,'".$VoucherNo."'
      ,[TotalAmount]
      ,[Active]
      ,[VoucherDate]
      ,[Narration]
      ,[Posted]
      ,[IsPostDated]
      ,[PostDate]
      ,".$VoucherTypeID."
      ,[ChequeNo]
      ,[PONO]
      ,[DD]
      ,[TC]
      ,[PeriodID]
      ,[ReferenceInvoiceID]
      ,[ClientBankAccountName]
      ,[LedgerID]
      ,[AmountDebit]
      ,[AmountCredit]
      ,[IsAuto]
      ,[WorkOrderID]
      ,".$LocationID."
      ,[VoucherPostDateTime]
      ,[CreateLog]
      ,[EditLog]
      ,[DeleteLog]
      ,[EmployeeID]
      ,[CostCenterID]
      ,[Received]
      ,[Balance]
      ,[ReferenceVoucherID]
      ,[GroupID]
      ,[ClientPayeeName]
      ,[AmountInWords]
      ,[PostDatedCh]
      ,[MultiVoucher]
      ,[VoucherToBePosted]
      ,[Cash]
      ,[PDCDayshold]
      ,[ChequeStatus]
      ,[SelectionID]
      ,[PDCPostDate]
      ,[PDCPostHoldDate]
      ,[IsVoucherReturnCheque]
      ,[ContractID]
      ,[UserID]
      ,[ApprovalDate]
      ,[ApprovalDescription]
      ,[ApprovalDescriptionReturn]
      ,[ApprovalToBePosted]
      ,[ApprovalToBeReturn]
      ,[CounterID]
      ,[ShiftNo]
      ,[NatureID]
      ,[InvoiceTypeID]
      ,[BankBranchName]
      ,[BankLedgerID]
      ,[PDCVoucherReferenceID]
      ,[ChequeStatusID]
      ,[BankDate]
      ,[NewLedgerID]
      ,[NewChequeStatusID]
      ,[PaymentID]
      ,[VoucherReferenceInvoiceID]
      ,[IsAutoPettyCashVoucher]
  FROM ".$value."[VoucherMaster] where VoucherID=".$VoucherIDOLD;

odbc_exec($connection,$sqlinsert) or die(odbc_error().$sqlinsert);



$sqlupdate="update ".$value."[VoucherMaster] set datamode=1 where VoucherID=".$VoucherIDOLD;
odbc_exec($connection,$sqlupdate);
//code for Voucher Details 
$sqldelete ="delete from VoucherDetails where VoucherID=".$VoucherIDOLD;
odbc_exec($connection,$sqldelete);

if($LocationID>1)
$GStart=getnamesingle("Godowns","AdditionalInfo3","GodownID",$LocationID,$connection);


 $sqldetail="insert into voucherdetails (VoucherID,[LedgerID],[Debit],[Credit],[Narration],[ReferenceInvoiceID],DetailLocationID,[EmployeeID],[ChequeNo],[InstrumentDate],[ChequeAmount],[CostCenterID],[CreditLedgerID],[dInvoiceTypeID])
SELECT VoucherID
      ,case when [LedgerID]>100000 then ([LedgerID]-(select convert(numeric(14),AdditionalInfo3) from Godowns where GodownID= ".$LocationID.")) else isnull(LedgerID,0) end as LedgerID
      ,[Debit]
      ,[Credit]
      ,[Narration]
      ,isnull([ReferenceInvoiceID],0)
      ,$LocationID
      ,[EmployeeID]
      ,[ChequeNoD]
      ,[InstrumentDate]
      ,case when [ChequeAmount] is null then 0 else [ChequeAmount] end as [ChequeAmount]
      ,[CostCenterID]
      ,case when [CreditLedgerID]>100000 then ([CreditLedgerID]-(select convert(numeric(14),AdditionalInfo3) from Godowns where GodownID= ".$LocationID.")) else CreditLedgerID end as [CreditLedgerID]
      ,[dInvoiceTypeID]
  FROM ".$value."[vw_VoucherDetails_Online] where VoucherID=".$VoucherIDOLD;
odbc_exec($connection,$sqldetail) or die(odbc_error().$sqldetail);
//end code for voucher details 
//cost of gold sold entry 
if($subtotal>0)
{
  $SidebarID=44;
  $degree=1;
  $Userid="";
  $Code='COGS_POST';
  if(CheckPolicy($Userid,$SidebarID,$Code,$degree,$connection)==1)
  {
$InventoryLedgerID=$_SESSION['SETTING']['INVENTORY'];
$COGSLedgerID=$_SESSION['SETTING']['COGS'];
$fdetails=array();  
           $fdetails['VoucherID']=$VoucherIDOLD;
           $fdetails['LedgerID']=$COGSLedgerID;//$SupplierID;//$d->CustomerLedgerID; 
        
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
            $CreditLedgerID=$InventoryLedgerID;//$d->SalesLedgerID;

           $fdetails['Debit']=$subtotal;
           $fdetails['Credit']=$subtotal;
           $fdetails['Narration']="Cost of Good Sold Entry :".$VoucherIDOLD;
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$LocationID;//$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$LocationID;//company
           $fdetails['TransactionType']="Cost of Good Sold Entry"; 
           //print_r($fdetails);
       InsertVoucherDetail2($fdetails,$InvoiceType,$VoucherIDOLD,$connection);
     }//end check policy
}             
else
{
  $SidebarID=44;
  $degree=1;
  $Userid="";
  $Code='COGS_POST';
  if(CheckPolicy($Userid,$SidebarID,$Code,$degree,$connection)==1)
  {
  $InventoryLedgerID=$_SESSION['SETTING']['INVENTORY'];
$COGSLedgerID=$_SESSION['SETTING']['COGS'];
$fdetails=array();  
           $fdetails['VoucherID']=$VoucherIDOLD;
           $fdetails['LedgerID']=$InventoryLedgerID;//$SupplierID;//$d->CustomerLedgerID; 
        
            $Debit=$TotalAmount;
            $Credit=$TotalAmount;
            $CreditLedgerID=$COGSLedgerID;//$d->SalesLedgerID;

           $fdetails['Debit']=($subtotal*-1);
           $fdetails['Credit']=($subtotal*-1);
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=$CreditLedgerID;
           $fdetails['CostCenterID']=$LocationID;//$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$LocationID;//company
           $fdetails['TransactionType']="Cost of Good Sold Entry"; 
           //print_r($fdetails);
       InsertVoucherDetail2($fdetails,$InvoiceType,$VoucherIDOLD,$connection);
        }//end COGS Policy
}
//update syntable 
/*$sqlupdate="insert into ".$value."SyncTableStatus(ID,TableName,PrimaryKeyID,PrimaryFieldName,datamode,GodownID) values($syntableid,'VoucherMaster',$VoucherIDOLD,'VoucherID',0,$LocationID) ";
      odbc_exec($connection,$sqlupdate) or die(odbc_error().$sqlupdate);
*/
      $sqlupdate="update  ".$value."SalesInvoiceMaster set datamode=1 where InvoiceID=".$InvoiceID;
         //  odbc_exec($connection,$sqlupdate) or die(odbc_error().'here error'.$sqlupdate);
           
}//end Active if 
      }//end voucher while
    //}//end if record exists 


    }//end main while
 /*             $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);  

//code for branch cash and payment 
          
/*$sql="select * from ".$Branch."VoucherDetails where ReferenceInvoiceID=".$InvoiceID." and Debit>0";
$result1=odbc_exec($connection,$sql);
while($row1=odbc_fetch_array($result1))
    {

   odbc_autocommit($connection, FALSE);
$fdetails=array();  
           $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$row1['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']=$row1['Debit'];
           $fdetails['Credit']=$row1['Credit'];
           $fdetails['Narration']="JOB CARD";
           $fdetails['ReferenceInvoiceID']=$InvoiceID;
           $fdetails['CreditLedgerID']=0;//$CreditLedgerID;
           $fdetails['CostCenterID']=0;//$GodownID;//company
           $fdetails['IsDelete']=0;
           $fdetails['DebitCostCenterID']=$GodownID;//company
           $fdetails['TransactionType']="Copy From Branch"; 
           //print_r($fdetails);
       InsertVoucherDetail2($fdetails,$InvoiceType,$VoucherID,$connection);              
        
      }*/
//end code for branch 

/*        $fdetails=array();  
        for($a=0;$a<3;$a++)
        {
           $fdetails['VoucherID']=$VoucherID;
           $fdetails['LedgerID']=$SupplierID;//$d->CustomerLedgerID; DEbit side entry
           if($a==3)
           {
           $fdetails['LedgerID']=$SupplierID;//$d->CustomerLedgerID; DEbit side entry 
            $Debit=$TotalTaxAmount;
            $Credit=$TotalTaxAmount;
            $CreditLedgerID=106;//$d->VATLedgerID;
           }
           else if($a==0)
          {
            //debit entry for sales Customer

            $Debit=$TotalAmount;
            $Credit=0;//$TotalAmount;
            $CreditLedgerID=0;//$d->SalesLedgerID;
          }
          else if($a==1)
          {
            //Credit entry for sales Head
            $fdetails['LedgerID']=0;//$SupplierID;
            $Debit=0;
            $Credit=$TotalAmount;//$TotalAmount;
            $CreditLedgerID=170;//$d->SalesLedgerID;
          }
          else if($a==2)
          {
            //entry for cash collection Credit Side
            $fdetails['LedgerID']=0;//$d->CustomerLedgerID; DEbit side entry
            $Debit=0;//$TotalAmount;
            $Credit=$TotalAmount;
            $CreditLedgerID=$SupplierID;//$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 SalesInvoiceMaster set AutoVoucherID=$VoucherID,InvoiceStatus=4,editLog='".$UserName."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$updateinvoice);
        $ReferenceInvoiceID=getnamesingle("SalesInvoiceMaster","ReferenceInvoiceID","InvoiceID",$InvoiceID,$connection);
        if($ReferenceInvoiceID>0)
        {
        $sql="update SalesInvoiceMaster set InvoiceStatus=4,datamode=1 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;
}//end else 

  
}

function GenerateSalesInvoice($connection,$InvoiceID,$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 SalesInvoiceMaster 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['CustomerID'];//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 SalesInvoiceMaster set AutoVoucherID=$VoucherID,InvoiceStatus=4,editLog='".$UserName."' where InvoiceID=".$InvoiceID;
        odbc_exec($connection,$updateinvoice);
        $ReferenceInvoiceID=getnamesingle("SalesInvoiceMaster","ReferenceInvoiceID","InvoiceID",$InvoiceID,$connection);
        if($ReferenceInvoiceID>0)
        {
        $sql="update SalesInvoiceMaster set InvoiceStatus=4,datamode=1 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 $res;

  }  
  function checkDuplicate($table,$field,$value,$connection)
  {
      $sql="select * from $table where $field='$value'";
      $result=odbc_exec($connection,$sql);
      if(odbc_num_rows($result)>0)
      {
        return true;
      }
      else
      {
        return false;
      }
  }
function getCardCodeDecode($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 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 getMaxLocationID($table,$field,$where,$connection)
  {
    $data="";
    $sql="select max($field) as id from $table where $where";
    $result=odbc_exec($connection, $sql);
    while($row=odbc_fetch_array($result))
    {
      $data=$row['id'];
    }
    return $data;
  }

  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,$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,$value,$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,$value,$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 insertSalesInvoiceDetail($InvoiceID,$mrdetail,$InvoiceType,$connection)
{

    odbc_autocommit($connection, FALSE);
                $sql="delete from SalesinvoiceDetail 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:'';
            $CostPrice =isset($mrdetail[$a]->CostPrice)?$mrdetail[$a]->CostPrice:0;
            
            $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:'';

            $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:'';*/
                $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("SalesinvoiceDetail","TransactionID",$connection)+1;
                 $sql="insert into SalesinvoiceDetail (TransactionID,
InvoiceID
           ,ItemID
           ,UnitPrice
           ,QTY
           ,Amount
           ,UnitID
           ,NetAmount
           ,TaxPercent
           ,TaxAmount
           ,Narration
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,itemBrand
           ,itemCode
           ,itemSize           
           ,DiscountAmount
           ,DiscountPercent
          ,Standardprice3
        ) values("
       .$TransactionID."
           ,".$InvoiceID."
           ,".$ItemID."
           ,".$UnitPrice."
           ,".$Qty."
           ,".$Amount."
           ,".$UnitID."
           ,".$NetAmount."
           ,".$TaxPercent."
           ,".$TaxAmount."
           ,'".$Narration."'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$VehicleBrandID."'
           ,'".$VehicleModelID."'                      
           ,'".$VehicleTypeID."'  
           ,".$DiscountAmount.",".$Discount.",".$CostPrice.")";
          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_print($InvoiceID,$mrdetail,$InvoiceType,$connection)
{

   // odbc_autocommit($connection, FALSE);
                $sql="delete from invoiceDetail_print 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:'';
       $CategorySize=isset($mrdetail[$a]->CategorySize)?$mrdetail[$a]->CategorySize:'';

         $Attr4=isset($mrdetail[$a]->VehicleModelName)?$mrdetail[$a]->VehicleModelName:'';
         $Standardprice3=isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
         if($Standardprice3=="" || $Standardprice3=="undefined")$Standardprice3=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:'';*/
                $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;
            }
              $CategorySize11= (array)$CategorySize;
              $CategorySize11=json_encode($CategorySize11);
              $TransactionID=getmaxId("invoiceDetail_print","TransactionID",$connection)+1;
                 $sql="insert into invoicedetail_print (
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
           ,ItemJson,Standardprice3
        ) values("
       .$InvoiceID."
           ,".$ItemID."
           ,".$UnitPrice."
           ,".$Qty."
           ,".$Amount."
           ,".$UnitID."
           ,".$NetAmount."
           ,".$TaxPercent."
           ,".$TaxAmount."
           ,'".$Narration."'
           ,".$TotalNetAmount."
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$VehicleBrandID."'
           ,'".$VehicleModelID."'                      
           ,'".$VehicleTypeID."'  
           ,".$VATPercent."
           ,".$VATAmount."
           ,".$ReceivedQty.
          ",".$StockQty.",0,".$DiscountAmount.",".$Discount.",'".($CategorySize11)."',$Standardprice3)";
          odbc_exec($connection, $sql) or die(odbc_error().$sql);

            //code for CategorySize 
/*for($a=0;$a<count($mrdetails);$a++)
{*/
//  $CategorySize=(json_decode($mrdetail[$a]->CategorySize));
  //$CategorySize=$CategorySize;//->detailitems; 
 // print_r($CategorySize);


          }//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:'';
            $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:'';
       $CategorySize=isset($mrdetail[$a]->CategorySize)?$mrdetail[$a]->CategorySize:'';

         $Attr4=isset($mrdetail[$a]->VehicleModelName)?$mrdetail[$a]->VehicleModelName:'';
         $Standardprice3=isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
         if($Standardprice3=="" || $Standardprice3=="undefined")$Standardprice3=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:'';*/
                $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;
            }
              $CategorySize11= (array)$CategorySize;
              $CategorySize11=json_encode($CategorySize11);
              $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
           ,ItemJson,Standardprice3
        ) values("
       .$InvoiceID."
           ,".$ItemID."
           ,".$UnitPrice."
           ,".$Qty."
           ,".$Amount."
           ,".$UnitID."
           ,".$NetAmount."
           ,".$TaxPercent."
           ,".$TaxAmount."
           ,'".$Narration."'
           ,".$TotalNetAmount."
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$VehicleBrandID."'
           ,'".$VehicleModelID."'                      
           ,'".$VehicleTypeID."'  
           ,".$VATPercent."
           ,".$VATAmount."
           ,".$ReceivedQty.
          ",".$StockQty.",0,".$DiscountAmount.",".$Discount.",'".($CategorySize11)."',$Standardprice3)";
          odbc_exec($connection, $sql) or die(odbc_error().$sql);

            //code for CategorySize 
/*for($a=0;$a<count($mrdetails);$a++)
{*/
//  $CategorySize=(json_decode($mrdetail[$a]->CategorySize));
  //$CategorySize=$CategorySize;//->detailitems; 
 // print_r($CategorySize);
  if($CategorySize!="")
  {/*
   for($b=0;$b<count($CategorySize);$b++)
   {
    $ReferenceItemID=$ItemID;//$CategorySize[$b]->ItemID;//Master Item
    $ItemID= isset($CategorySize[$b]->MaterialID)?$CategorySize[$b]->MaterialID:$CategorySize[$b]->Item_ItemID;//."<br>";
    $Qty=$CategorySize[$b]->Qty;
    $Rate=isset($CategorySize[$b]->RetailPrice)?$CategorySize[$b]->RetailPrice:$CategorySize[$b]->Rate;
    $Remarks= $CategorySize[$b]->Narration;
    $ExpiryDate=Date("Y-m-d");
    //$InvoiceID=21;
    //$InvoiceType=5;
    $Active=1;
    $ContainerNo="";
    $COAID=0;
    $BranchID=0;
    $UserID=0;
    $TransDate=Date("Y-m-d");
    $CounterID=0;
    $VoucherID=0;
    $SupplierID=0;
    $CurrentDepartmentID=2000;
    $GodownID=1;
    $Reference="";
    $ReferenceInvoiceID=0;
    $ProjectID=0;
    $ItemJson="";
    $Attr1="";
    $Attr2="";
    $Attr3="";
    $Attr4="";
    $Attr5="";
    $Attr6="";
    $Attr7="";
    $Attr8="";
    $Attr9="";
    $Attr10="";
    
               $ID=getmaxId("stockledger","ID",$connection)+1;
              $sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
                    odbc_exec($connection, $sql) or die(odbc_error().$sql);
   }
*/}
          //end code for categorysize 

          }//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 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)
     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']."
     )";
   
            
            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=1 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 InsertVoucherMasterNew($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']:'';
  $VoucherTypeID=0;
  if($InvoiceType==5)
$VoucherTypeID=8;
  else if($InvoiceType==4)
$VoucherTypeID=71;
else if($InvoiceType==3)
$VoucherTypeID=66;

            /*$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
            if($InvoiceType==3 || $InvoiceType==4 || $InvoiceType==5)
            $sql="select * from VoucherMaster where active=1 and VoucherTypeID=$VoucherTypeID and ReferenceInvoiceID=".$InvoiceID;
          else
          $sql="select * from VoucherMaster where VoucherTypeID=$VoucherTypeID and 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 VoucherTypeID=$VoucherTypeID and ReferenceInvoiceID=".$InvoiceID;
     //       odbc_exec($connection,$sql) or die(odbc_error().$sql);  
             $fields['VoucherID']=$VoucherID;
            }
            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 VoucherID='.$sql);
  }
else
{
      odbc_rollback($connection);
      $res=array('status'=>"Error",'description'=>'Record  Not Updated');

}            
return $res;
}
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
            if($InvoiceType==3)
            {
            $sql="select * from VoucherMaster where active=1 and VoucherTypeID=8 and ReferenceInvoiceID=".$InvoiceID;  
            }
            else
            {
            $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 InsertVoucherDetail2($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); 

}
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 CheckPolicy($Userid,$Sidebar,$Code,$degree,$connection)
{
  //$degree=json_decode(getnamewhere("policybank","max(degree) as deg","Code='$Code' and active=1",$connection));
  //$degree=implode(",", $degree);
  // $degree=$degree->deg;


  if($Userid!="" && $degree==3)
    {
  $sql="select Active from policybank where UserID=$Userid and SidebarID=$Sidebar and Code='$Code'";
  }
  elseif ($Sidebar!="" && $degree==2) {
      # code...
  $sql="select Active from policybank where SidebarID=$Sidebar and Code='$Code'";
    }  
    else{
        # code...
       $sql="select Active from policybank where Code='$Code' and degree=1";
      }  
    $result=odbc_exec($connection,$sql) or die(odbc_error().$sql);
    if(odbc_num_rows($result)>0)
    {
      $row=odbc_fetch_array($result);
      /*$permit=str_replace("[","", $permit);
      $permit=str_replace("]","", $permit);*/
      $ans=$row['Active'];
      
        return $ans;
    }
    else
    {
        return 0;
    }
}
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");
          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>"; 
                   
              }
              
}
function insertStockQC($InvoiceID,$main,$mrdetail,$InvoiceType,$connection)
{

$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID:0;
            $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 InvoiceTypeID=".$InvoiceType." and  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;
            $Status =isset($mrdetail[$a]->Status)?$mrdetail[$a]->Status:0;
            $StatusID =isset($mrdetail[$a]->StatusID)?$mrdetail[$a]->StatusID: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;

                 $Attr5 =isset($mrdetail[$a]->Length)?$mrdetail[$a]->Length:'';
            $Attr6 =isset($mrdetail[$a]->Width)?$mrdetail[$a]->Width:'';
            $Attr7 =isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
            $UnitID=isset($mrdetail[$a]->Unit)?$mrdetail[$a]->Unit:1;
            $Attr8=$UnitID;
            $Attr9="";
            $Attr10="";
            $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:0;
           $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($ShipperID)?$ShipperID:0;
           $ItemJson=isset($ItemJson)?$ItemJson:0;
           if($Status=="APPROVED")
             $DepartmentID=$ShipperID;
             else 
             $DepartmentID=11; 
           
// update the main item in the stock ledger 
$sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     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'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);

//end code 
//stock out 
                     $ID=getmaxId("stockledger","ID",$connection)+1;
$sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
         )"; 
                     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');

}



}//end stock qc
function StockINOnly($InvoiceID,$main,$mrdetail,$InvoiceType,$connection)
{



$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID:2000;
            $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);
                
       //     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:'';
            $ItemJson =isset($mrdetail[$a]->ItemJson)?$mrdetail[$a]->ItemJson:'';
            $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;

       $Attr5 =isset($mrdetail[$a]->Length)?$mrdetail[$a]->Length:'';
            $Attr6 =isset($mrdetail[$a]->Width)?$mrdetail[$a]->Width:'';
            $Attr7 =isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
            $UnitID=isset($mrdetail[$a]->Unit)?$mrdetail[$a]->Unit:1;
            $Attr8=$UnitID;
            $Attr9="";
            $Attr10="";
            $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;
            }
            
$sql="delete from stockledger where InvoiceTypeID=$InvoiceType and ItemID=$ItemID and  InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);

              $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:0;
           $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:Date("Y-m-d");
           $ExpiryDate=isset($DueDate)?$DueDate:Date("Y-m-d");
           $SupplierID=isset($SupplierID)?$SupplierID:0;
           $DepartmentID=isset($ShipperID)?$ShipperID:0;
           $ItemJson=isset($ItemJson)?$ItemJson:0;
           
// update the main item in the stock ledger 
 $sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".($Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
          //check stock before STOCK IN 
        /*  if(checkStock($ItemID,$Qty,$connection))
          {

          }
          else
              {*/
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);   
              //}
//stock out 
                     $ID=getmaxId("stockledger","ID",$connection)+1;
               $sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
                   //  odbc_exec($connection, $sql) or die(odbc_error().$sql);      
//end code here            
           
           //code for Raw Material
           $CategorySize=json_decode($ItemJson);

           //end code for Raw Material       
          }//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');

}





}//end Stock in only

function StockIN($InvoiceID,$main,$mrdetail,$InvoiceType,$connection)
{


$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID:2000;
            $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);
                
       //     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:'';
            $ItemJson =isset($mrdetail[$a]->ItemJson)?$mrdetail[$a]->ItemJson:'';
            $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;

       $Attr5 =isset($mrdetail[$a]->Length)?$mrdetail[$a]->Length:'';
            $Attr6 =isset($mrdetail[$a]->Width)?$mrdetail[$a]->Width:'';
            $Attr7 =isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
            $UnitID=isset($mrdetail[$a]->Unit)?$mrdetail[$a]->Unit:1;
            $Attr8=$UnitID;
            $Attr9="";
            $Attr10="";
            $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;
            }
            
$sql="delete from stockledger where InvoiceTypeID=$InvoiceType and ItemID=$ItemID and  InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);

              $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:0;
           $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:Date("Y-m-d");
           $ExpiryDate=isset($DueDate)?$DueDate:Date("Y-m-d");
           $SupplierID=isset($SupplierID)?$SupplierID:0;
           $DepartmentID=isset($ShipperID)?$ShipperID:0;
           $ItemJson=isset($ItemJson)?$ItemJson:0;
           
// update the main item in the stock ledger 
 $sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".($Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
          //check stock before STOCK IN 
        /*  if(checkStock($ItemID,$Qty,$connection))
          {

          }
          else
              {*/
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);   
              //}
//stock out 
                     $ID=getmaxId("stockledger","ID",$connection)+1;
               $sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);      
//end code here            
           
           //code for Raw Material
           $CategorySize=json_decode($ItemJson);

           //end code for Raw Material       
          }//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');

}




}//end StockIN
function StockINOut($InvoiceID,$main,$mrdetail,$InvoiceType,$connection)
{

$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID:2000;
            $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 InvoiceTypeID=$InvoiceType and  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;

       $Attr5 =isset($mrdetail[$a]->Length)?$mrdetail[$a]->Length:'';
            $Attr6 =isset($mrdetail[$a]->Width)?$mrdetail[$a]->Width:'';
            $Attr7 =isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
            $UnitID=isset($mrdetail[$a]->Unit)?$mrdetail[$a]->Unit:1;
            $Attr8=$UnitID;
            $Attr9="";
            $Attr10="";
            $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:0;
           $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($ShipperID)?$ShipperID:0;
           $ItemJson=isset($ItemJson)?$ItemJson:0;
           
// update the main item in the stock ledger 
 $sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".($Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
          //check stock before STOCK IN 
          if(checkStock($ItemID,$Qty,$connection))
          {

          }
          else
              {
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);   
              }
//stock out 
                     $ID=getmaxId("stockledger","ID",$connection)+1;
               $sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);      
//end code here            
           
                 
          }//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');

}



}//stock IN/Out 
function checkStockShopOpening($Item,$GodownID,$date,$connection)
{
 $Balance=0; 
  $sql="select sum(Qty) as Balance from StockLedger where TransDate<'$date' and ItemID=$Item and GodownID=$GodownID";
  $result=odbc_exec($connection, $sql);
  while($row=odbc_fetch_array($result))
  {
  $Balance=$row['Balance'];
  }
  
    return floatval($Balance);
  
}
function checkStockShop($Item,$GodownID,$connection)
{
 $Balance=0; 
  $sql="select sum(Qty) as Balance from StockLedger where ItemID=$Item and GodownID=$GodownID";
  $result=odbc_exec($connection, $sql);
  while($row=odbc_fetch_array($result))
  {
  $Balance=$row['Balance'];
  }
  
    return floatval($Balance);
  
}
function checkStock($Item,$Qty,$connection)
{
 $Balance=0; 
  $sql="select sum(Qty) as Balance from StockLedger where ItemID=$Item";
  $result=odbc_exec($connection, $sql);
  while($row=odbc_fetch_array($result))
  {
  $Balance=$row['Balance'];
  }
  if($Balance>=$Qty)
  {
    return true;
  }
  else
  {
    return false;
  }
}

function StockOut($InvoiceID,$main,$mrdetail,$InvoiceType,$connection)
{


   // odbc_autocommit($connection, FALSE);
$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID:0;
$Reference =(isset($main->KeyField) && $main->KeyField!="") ?$main->KeyField:0;  

      $ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
            $GodownID =(isset($main->GodownID) && $main->GodownID!="")?$main->GodownID:1;
            $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:Date("Y-m-d");

                $sql="delete from stockledger where Invoicetypeid=$InvoiceType and  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:'';
            $ReferenceItemID=0;
            if($JobCardItem!="")$ReferenceItemID=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;

       $Attr5 =isset($mrdetail[$a]->Length)?$mrdetail[$a]->Length:'';
            $Attr6 =isset($mrdetail[$a]->Width)?$mrdetail[$a]->Width:'';
            $Attr7 =isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
            $UnitID=isset($mrdetail[$a]->Unit)?$mrdetail[$a]->Unit:1;
            $Attr8=$UnitID;
            $Attr9="";
            $Attr10="";
            $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($ReferenceItemID)?$ReferenceItemID: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:0;//0;
           $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:Date('Y-m-d');
           $ExpiryDate=isset($DueDate)?$DueDate:Date('Y-m-d');
           $SupplierID=isset($SupplierID)?$SupplierID:0;
           $DepartmentID=isset($ShipperID)?$ShipperID:0;
           $ItemJson=isset($ItemJson)?$ItemJson:0;
           
// update the main item in the stock ledger 

//stock out 
//                     $ID=getmaxId("stockledger","ID",$connection)+1;
               $sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);      
//end code here            
//code for MAterial 
  $sqlmaterial="select * from inventory_ingredients where ItemID=$ItemID";
           $resultmaterial=odbc_exec($connection,$sqlmaterial);
           $ReferenceItemID=$ItemID;
           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 [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qt).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID
           ,'".$ItemJson."'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
            )"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);

         }
//end code for material            
           
                 
          }//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');

}

return $res;

}//stock out 
function insertGoodTransfer($InvoiceID,$main,$mrdetail,$InvoiceType,$connection)
{

$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID:2000;
    $Reference =(isset($main->KeyField) && $main->KeyField!="") ?$main->KeyField:0;  
            if($CurrentDepartmentID==7 || $CurrentDepartmentID=="")
                {
      $CurrentDepartmentID =isset($main->ShippingMethodID)?$main->ShippingMethodID:2000;            
                }
      $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 InvoiceTypeid=6 and  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:0;
            if($JobCardItem!="")$JobCardItem=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;

             $Attr5 =isset($mrdetail[$a]->Length)?$mrdetail[$a]->Length:'';
            $Attr6 =isset($mrdetail[$a]->Width)?$mrdetail[$a]->Width:'';
            $Attr7 =isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
            $UnitID=isset($mrdetail[$a]->Unit)?$mrdetail[$a]->Unit:1;
            $Attr8=$UnitID;
            $Attr9="";
            $Attr10="";
            $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!="")?$ItemID:0;
           $ReferenceItemID=(isset($JobCardItem) && $JobCardItem!="")?$JobCardItem: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:22;//0;
           $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($ShipperID)?$ShipperID:0;
           $ItemJson=isset($ItemJson)?$ItemJson:0;
           
// update the main item in the stock ledger 
$sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           $Qty,
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $DepartmentID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $DepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
         )"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);
//stock out 
                     $ID=getmaxId("stockledger","ID",$connection)+1;
               $sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $CurrentDepartmentID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);      
//end code here            
           
                 
          }//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');

}



}//end good transfer
function insertStockTransfer($InvoiceID,$main,$mrdetail,$InvoiceType,$connection)
{
$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID:2000;
            $Reference =(isset($main->ParkingNo) && $main->ParkingNo!="") ?$main->ParkingNo:0;  if($CurrentDepartmentID==7 || $CurrentDepartmentID=="")
                {
      $CurrentDepartmentID =isset($main->ShippingMethodID)?$main->ShippingMethodID:2000;            
                }
      $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 InvoiceTypeid=$InvoiceType and 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:0;
            if($JobCardItem!="")$JobCardItem=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;

             $Attr5 =isset($mrdetail[$a]->Length)?$mrdetail[$a]->Length:'';
            $Attr6 =isset($mrdetail[$a]->Width)?$mrdetail[$a]->Width:'';
            $Attr7 =isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
            $UnitID=isset($mrdetail[$a]->Unit)?$mrdetail[$a]->Unit:1;
            $Attr8=$UnitID;
            $Attr9="";
            $Attr10="";
            $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!="")?$ItemID:0;
           $ReferenceItemID=(isset($JobCardItem) && $JobCardItem!="")?$JobCardItem: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:0;
           $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($ShipperID)?$ShipperID:0;
           $ItemJson=isset($ItemJson)?$ItemJson:0;
           
// update the main item in the stock ledger 
$sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     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'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
         )"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);
//stock out 
                     $ID=getmaxId("stockledger","ID",$connection)+1;
               $sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qty).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID,'$ItemJson'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
          )"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);      
//end code here            
           
                 
          }//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');

}


}//insertStockTransfer
function insertStock2($InvoiceID,$main,$mrdetail,$InvoiceType,$connection)
{

            $Reference =(isset($main->KeyField) && $main->KeyField!="") ?$main->KeyField:$main->ParkingNo;  
      $ShipperID =isset($main->ShipperID)?$main->ShipperID:0;
$CurrentDepartmentID =isset($main->CurrentDepartmentID)?$main->CurrentDepartmentID:2000;
            $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!='' )?$main->BillDate:Date('Y-m-d');
            $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!='' )?$main->DeliveryDate:Date('Y-m-d');
    //odbc_autocommit($connection, FALSE);
                
       //     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:0;
            $JobCardItem=isset($mrdetail[$a]->JobCardItem)?$mrdetail[$a]->JobCardItem:0;
            if($JobCardItem!="" && $JobCardItem!="0")$JobCardItem=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;
   $Attr5 =isset($mrdetail[$a]->Length)?$mrdetail[$a]->Length:'';
            $Attr6 =isset($mrdetail[$a]->Width)?$mrdetail[$a]->Width:'';
            $Attr7 =isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
            $UnitID=isset($mrdetail[$a]->Unit)?$mrdetail[$a]->Unit:1;
            $Attr8=$UnitID;
            $Attr9="";
            $Attr10="";
            $TotalNetAmount=0;


  $sql="delete from stockledger where ItemID=$ItemID and InvoiceTypeID=$InvoiceType and  InvoiceID=".$InvoiceID;
            odbc_exec($connection,$sql);
            

              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($JobCardItem) && $JobCardItem!="")?$JobCardItem: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:22;//0;
           $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($ShipperID)?$ShipperID:0;
           $ItemJson=isset($ItemJson)?$ItemJson:0;
           
// update the main item in the stock ledger 
$sql="INSERT INTO [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     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'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
         )"; 
                     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);
           $ReferenceItemID=$ItemID;
           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 [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]
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     VALUES ($ID,
           $ItemID,
           $ReferenceItemID,
           ".(-1*$Qt).",
           $InvoiceType,
           $InvoiceID,
           $ReferenceInvoiceID,
           '$Reference',
           '$Remarks',
           $GodownID,
           $ProjectID,
           $BranchID,
           $COAID,
           $Active,
           '$ContainerNo',
           $UserID,
           $Rate,
           $CounterID,
           $VoucherID,
           '$TransDate',
           '$ExpiryDate',
           $SupplierID,
           $CurrentDepartmentID
           ,'".$ItemJson."'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
            )"; 
                     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');

}

return $res;

}
function insertOpeningStock($InvoiceID,$main,$mrdetail,$InvoiceType,$connection)
{
  $sql="delete from StockLedger where ItemID=$InvoiceID and InvoiceTypeID=0";
           odbc_exec($connection, $sql);
    for($a=0;$a<count($mrdetail);$a++)
            {
            $Flag =isset($mrdetail[$a]->Flag)?$mrdetail[$a]->Flag:'';
            if($Flag!="D")
            {
//
            $ItemID =$InvoiceID;//isset($mrdetail[$a]->Item_ItemID)?$mrdetail[$a]->Item_ItemID:'';
            $JobCardItem=isset($mrdetail[$a]->JobCardItem)?$mrdetail[$a]->JobCardItem:0;
            if($JobCardItem!="")$JobCardItem=getnamesingle("Inventory","ID","Name","'".$JobCardItem."'",$connection);
            $JobCardItem=0;
            $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:'';
            $Item_Brand=isset($mrdetail[$a]->Item_Brand)?$mrdetail[$a]->Item_Brand:'';
            $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;
   $Attr5 =isset($mrdetail[$a]->Length)?$mrdetail[$a]->Length:1;

             $Attr6 =isset($mrdetail[$a]->Width)?$mrdetail[$a]->Width:1;
            $Attr7 =isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
            $UnitID=isset($mrdetail[$a]->Unit)?$mrdetail[$a]->Unit:1;
            $Attr8=$UnitID;
            $Attr9="";
            $Attr10="";
            $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=0;//isset($JobCardItem)?$JobCardItem:0;
           $Qty=isset($Qty)?$Qty:0;
           $InvoiceTypeID=isset($InvoiceType)?$InvoiceType:0;
           $InvoiceID=isset($InvoiceID)?$InvoiceID:0;
           $ReferenceInvoiceID=isset($ReferenceInvoiceID)?$ReferenceInvoiceID:0;
           $Reference=isset($Item_Brand)?$Item_Brand:'Opening';
           $Remarks=isset($Narration)?$Narration:'';
           $GodownID=isset($GodownID)?$GodownID:1;
           $ProjectID=isset($ProjectID)?$ProjectID:0;
           $BranchID=isset($BranchID)?$BranchID:0;
           $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($ShipperID)?$ShipperID:0;
           $ItemJson=isset($ItemJson)?$ItemJson:0;
           
           

// update the main item in the stock ledger 
 $sql="INSERT INTO [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]
            ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     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'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
            )"; 
                     odbc_exec($connection, $sql) or die(odbc_error().$sql);
}//end if
}//end for 
}//end function insertopeningstock
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 InvoiceTypeid=$InvoiceType and 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:0;
            if($JobCardItem!="")$JobCardItem=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;
   $Attr5 =isset($mrdetail[$a]->Length)?$mrdetail[$a]->Length:'';

             $Attr6 =isset($mrdetail[$a]->Width)?$mrdetail[$a]->Width:'';
            $Attr7 =isset($mrdetail[$a]->PCS)?$mrdetail[$a]->PCS:0;
            $UnitID=isset($mrdetail[$a]->Unit)?$mrdetail[$a]->Unit:1;
            $Attr8=$UnitID;
            $Attr9="";
            $Attr10="";
            $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($JobCardItem)?$JobCardItem: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:0;
           $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($ShipperID)?$ShipperID:0;
           $ItemJson=isset($ItemJson)?$ItemJson:0;
           
// update the main item in the stock ledger 
$sql="INSERT INTO [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]
            ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     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'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
            )"; 
                     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 [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
           ,Attr1
           ,Attr2
           ,Attr3
           ,Attr4
           ,Attr5
           ,Attr6
           ,Attr7
           ,Attr8
           ,Attr9
           ,Attr10
           )
     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
           ,'".$ItemJson."'
           ,'".$Attr1."'
           ,'".$Attr2."'
           ,'".$Attr3."'
           ,'".$Attr4."'
           ,'".$Attr5."'
           ,'".$Attr6."'
           ,'".$Attr7."'
           ,'".$Attr8."'
           ,'".$Attr9."'
           ,'".$Attr10."'
         )"; 
                     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');

}

}
?>