<?php
include_once('database_connection.php');

$date=Date("Y-m-d");
if(isset($_GET['action']))
{
  if($_GET['action']=="ButtonGenerateSalesInvoice")
  {
       if((isset($_GET['startdate']) &&  $_GET['startdate']!="undefined" && $_GET['startdate']!="")  && (isset($_GET['enddate']) && $_GET['enddate']!="undefined" && $_GET['enddate']!=""))
            {
                $start=$_GET['startdate'];
                $end=$_GET['enddate'];
                $date=" convert(date,InvoiceDate) Between '$start' and '$end' and ";
                $tdate="convert(date,today) Between '$start' and '$end'  and ";
            }
            else
            {
              $date=Date("Y-m-d");
                $tdate="convert(date,today)='$date' and ";
                $date="invoicedate='".$date."' and ";
            }
    $UserName=$_GET['UserName'];
  $sql="select distinct EditLog as UserName,InvoiceDate from invoicemaster where invoicetype=5 and invoicestatus in(2,4) and paid>0 and $date (EditLog='$UserName' or CreateLog='$UserName') ";
$result=odbc_exec($connection, $sql);
    while($row=odbc_fetch_array($result))
    {
/* query */
$UserName=$row['UserName'];
$date=$row['InvoiceDate'];
  $sql1="SELECT * FROM InvoiceMaster WHERE InvoiceDate='$date' and EditLog='$UserName' and paid>0 and invoicetype=5 and invoicestatus in(2,4) and invoiceid not in 
(select invoiceid from dailyreport where symCashier='$UserName' and $tdate 1=1)";
$result1=odbc_exec($connection, $sql1);
     while($row1=odbc_fetch_array($result1))
     {
      $InvoiceID=$row1['InvoiceID'];
      //print_r($row1);
      $ret=GenerateSalesInvoice($connection,$InvoiceID);
      if($ret==1)
      {
       $sql2="update InvoiceMaster set EditLog='$UserName' where InvoiceID=$InvoiceID";
      odbc_exec($connection, $sql2);
       $sql2="update vouchermaster set CreateLog='$UserName' where ReferenceInvoiceID=$InvoiceID";
      odbc_exec($connection, $sql2);
      $res=array('status'=>"ok",'description'=>'Invoice Generated Sucessfully');
      echo json_encode($res);
  		}
     }
   }
  }
}
//-- check if invoice generated or not 
  //-- select * from vouchermaster where vouchertypeid=8 and referenceinvoiceid=21271 
  //-- if invoice not generated , generate invoice 
  //-- if already generated then update the autovoucherid
 /*$result=odbc_exec($connection, $sql);
    while($row=odbc_fetch_array($result))
    {
      $data[]=$row;
      //check if the invoice is generate of not 
      $InvoiceID=$row['InvoiceID'];
      $sql1="select * from vouchermaster where vouchertypeid=8 and referenceinvoiceid=$InvoiceID";
      $result1=odbc_exec($connection, $sql1);
      if(odbc_num_rows($result1)>0)
      {

      }

    }*/

?>