<?php 
//33AADCG4992P1Z0 dummy for tgest
// "SellerDtls" => [
//    "Gstin" => "33AACFY7179C1Z3", 
//    "LglNm" => "YOGA SAND AND STONES COMPANY", 
//    "Addr1" => "520-9-3, 1ST FLOOR, PORIYALAR NAGAR 8TH STREET,THIRUMALPURAM POST", 
//    "Loc" => "Madurai", 
//    "Pin" => 625014, 
//    "Stcd" => "33" 
// ], 
include "config.php";
error_reporting(0);
$salescodee=$_GET['print'];
$table = $_GET['table'];
 $go=mysqli_query($connect,"select * from $table where salescode ='$salescodee' && status !='deleted'");
 $i = 0;
  while($dis=mysqli_fetch_array($go))
  {
  $date=date_create($dis['date']);
   $customer_code= $dis['customer'];
$customer=mysqli_query($connect,"select * from customerdetails where code = '$customer_code' && status!='deleted'");
while($customershow = mysqli_fetch_array($customer))
{
    
   $product = $dis['product'];
$cus=mysqli_query($connect,"select * from productdetail where status !='deleted' && productcode ='$product'");
while($cusshow = mysqli_fetch_array($cus))
{
  $price = $dis['price'];
  $qty = $dis['netqty'];
  $gst = $cusshow['tax'];
  
   if($cusshow['unit']=="TONN")
  {
  $unit_type="TON";
  }
  
  if($cusshow['unit']=="KG")
  {
  $unit_type="KGS";
  }
  
  if($cusshow['unit']=="UNIT")
  {
  $unit_type="UNT";
  }
  
  $inclu = $price * 100 /( 100 + $gst);
  $sub = $inclu * $qty;
  $tax = (0.01*$gst*$sub);
    $count +=1;
    $state_name = $customershow['state'];
    $state_lower_case=strtolower(preg_replace("/ /i","",$state_name));
   if($state_lower_case=="tamilnadu"){
    $prodata[]=(object)[
                             "ItemNo" => 1, 
                             "SlNo" => 1, 
                             "IsServc" => "N", 
                             "PrdDesc" =>$dis['productname'], 
                             "HsnCd" => $cusshow['hsn'], 
                             "Qty" => (float)Number_format($qty,2,'.',''),
                             "FreeQty" => 0, 
                             "Unit" => $unit_type, 
                             "UnitPrice" => (float)Number_format($inclu,2,'.',''), 
                             "TotAmt" => (float)Number_format($sub,2,'.',''), 
                             "Discount" => 0, 
                             "PreTaxVal" => 0, 
                             "AssAmt" => (float)Number_format($sub,2,'.',''), 
                             "GstRt" => (float)Number_format($gst,2,'.',''), 
                             "IgstAmt" => 0, 
                             "CgstAmt" =>(float)Number_format(($tax/2),2,'.',''), 
                             "SgstAmt" => (float)Number_format(($tax/2),2,'.',''), 
                             "CesRt" => 0, 
                             "CesAmt" => 0, 
                             "CesNonAdvlAmt" => 0, 
                             "StateCesRt" => 0, 
                             "StateCesAmt" => 0, 
                             "StateCesNonAdvlAmt" => 0, 
                             "OthChrg" => 0, 
                             "TotItemVal" => (float)round(Number_format($sub + $tax,2,'.',''))
                          ];
                          $Val_Dtls = (object)[
                             "AssVal" => (float)Number_format($sub,2,'.',''),
                             "CgstVal" => (float)Number_format(($tax/2),2,'.',''),
                             "SgstVal" => (float)Number_format(($tax/2),2,'.',''),
                             "IgstVal" => 0, 
                             "CesVal" => 0, 
                             "StCesVal" => 0, 
                             "Discount" => 0, 
                             "OthChrg" => 0, 
                             "RndOffAmt" => 0, 
                             "TotInvVal" => (float)round(Number_format($sub + $tax,2,'.',''))
                          ];
}
else{
   $prodata[]=(object)[
      "ItemNo" => 1, 
      "SlNo" => 1, 
      "IsServc" => "N", 
      "PrdDesc" =>$dis['productname'], 
      "HsnCd" => $cusshow['hsn'], 
      "Qty" => (float)Number_format($qty,2,'.',''), 
      "FreeQty" => 0, 
      "Unit" => $unit_type, 
      "UnitPrice" => (float)Number_format($inclu,2,'.',''), 
      "TotAmt" => (float)Number_format($sub,2,'.',''), 
      "Discount" => 0, 
      "PreTaxVal" => 0, 
      "AssAmt" => (float)Number_format($sub,2,'.',''), 
      "GstRt" => (float)Number_format($gst,2,'.',''), 
      "IgstAmt" => (float)Number_format($tax,2,'.',''), 
      "CgstAmt" => 0, 
      "SgstAmt" => 0, 
      "CesRt" => 0, 
      "CesAmt" => 0, 
      "CesNonAdvlAmt" => 0, 
      "StateCesRt" => 0, 
      "StateCesAmt" => 0, 
      "StateCesNonAdvlAmt" => 0, 
      "OthChrg" => 0, 
      "TotItemVal" => (float)round(Number_format($sub + $tax,2,'.',''))
   ];
   $Val_Dtls = (object)[
      "AssVal" => (float)Number_format($sub,2,'.',''),
      "CgstVal" => 0,
      "SgstVal" => 0,
      "IgstVal" => (float)Number_format($tax,2,'.',''), 
      "CesVal" => 0, 
      "StCesVal" => 0, 
      "Discount" => 0, 
      "OthChrg" => 0, 
      "RndOffAmt" => 0, 
      "TotInvVal" => (float)round(Number_format($sub + $tax,2,'.',''))
   ];
}
$data_fetch =  (object)[ 
    "Version" => "1.1", 
    "TranDtls" =>  (object)[
          "TaxSch" => "GST", 
          "SupTyp" => "B2B", 
          "RegRev" => "N", 
          "IgstOnIntra" => "N" 
       ], 
    "DocDtls" =>  (object)[
             "Typ" => "INV", 
             "No" => $salescodee, 
             "Dt" => date_format($date,"d/m/Y")
          ], 
         "SellerDtls" => (object)[
   "Gstin" => "33AACFY7179C1Z3", 
   "LglNm" => "YOGA SAND AND STONES COMPANY", 
   "Addr1" => "520-9-3, 1ST FLOOR, PORIYALAR NAGAR 8TH STREET,THIRUMALPURAM POST", 
   "Loc" => "MADURAI", 
   "Pin" => 625014, 
   "Stcd" => "33" 
], 
    "BuyerDtls" =>  (object)[
                   "Gstin" => $customershow['gst'], //
                   "LglNm" => $customershow['name'], 
                   "Pos" => substr($customershow['gst'], 0, 2), 
                   "Addr1" => $customershow['address'], 
                   "Loc" => $customershow['district'], 
                   "Pin" => (int)$customershow['pincode'], 
                   "Stcd" => substr($customershow['gst'], 0, 2) 
                ], 
    "DispDtls" =>  (object)[
                      "Nm" => "YOGA SAND AND STONES COMPANY", 
                      "Addr1" => "No 4/5.1 Vadipatti,Kachakatti Main Road", 
                      "Loc" => "Madurai", 
                      "Pin" => 625218, 
                      "Stcd" => "33"
                   ], 
    "ShipDtls" =>  (object)[
                         "Gstin" => $customershow['gst'], 
                         "LglNm" => $customershow['name'], 
                         "Addr1" => $dis['delivery'], 
                         "Loc" => $dis['dispatch_district'], 
                         "Pin" => (int)$dis['dispatch_pincode'], 
                         "Stcd" => $dis['dispatch_state_code']
                      ], 
    "ItemList" => $prodata,
     "ValDtls" =>$Val_Dtls,
    "EwbDtls" =>  (object)[
                                     "TransId" => $dis['eway_trans_id'], 
                                     "TransName" => $dis['eway_trans_name'], 
                                     "TransMode" => "1", 
                                     "Distance" => (int)$dis['eway_distance'], 
                                     "VehNo" => $dis['vehicleno'], 
                                     "VehType" => 'R' 
									 
									 /*"TransId"=> "21ADAPP6261D1Z1",
   									 "TransName"=> "Just in time Shippers Pvt Limited",
    								"TransMode"=> "1",
									"Distance"=> 0,
									"VehNo"=> "KA33A1234",
									"VehType"=> "R"*/
									 
                                  ] 
 ];
 $data_result = json_encode($data_fetch);
}
}
}
   
 //echo $state_lower_case;
 ?>
                        


                        <!DOCTYPE html>
<html>
   <head>
   <script src="datatable/data.js" type="text/javascript"></script>
<script src="datatable/table.js" type="text/javascript"></script>
<script src="datatable/datatable.js"></script>
   <style>
.loader {
  border: 16px solid #f3f3f3;
  border-radius: 50%;
  border-top: 16px solid #3498db;
  width: 80px;
  height: 80px;
  -webkit-animation: spin 2s linear infinite; /* Safari */
  animation: spin 2s linear infinite;
}

/* Safari */
@-webkit-keyframes spin {
  0% { -webkit-transform: rotate(0deg); }
  100% { -webkit-transform: rotate(360deg); }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
.loader-div{
   display: flex;
    align-items: center;
    justify-content: center;
    /* position: fixed; */
    position: relative;
    top: calc(50vh - 80px);;
}
</style>
   </head>
   <body>
      <div class="loader-div">
      <div class="loader"></div>
      </div>
   
<div id="jsonString" style="display:none" ><?php echo $data_result;?></div>
<a href="" id="redirectUrl"></a>
<input type="text" id="salescode" value="<?php echo $salescodee?>">
<script>
   setTimeout(() => {
   let stringContent = document.getElementById('jsonString').innerHTML;
   console.log('doc',JSON.parse(stringContent)); 
   handleJsonResponse(JSON.parse(stringContent));
   }, 2000);
    function handleJsonResponse(jsonBody){
      console.log(JSON.stringify(jsonBody));
// fetch('https://my.gstzen.in/~gstzen/a/post-einvoice-data/einvoice-json/', {
//     method: 'POST',
//     headers: {
//         'Content-Type': 'application/json',
//         'Token': 'de3a3a01-273a-4a81-8b75-13fe37f14dc6'
// 'Token': 'eb3c83ae-dc9a-47ed-badf-ce994460e1c5'//live
//     },
//     body: JSON.stringify(jsonBody)
// }).then((response) => {
//  console.log('res',response);
// })
// .then((responseJson) => {
//    console.log('res',responseJson);
// })
// .catch((error) => {
//   console.log('eroor',error)
// });
$.ajax({  
                    // url:"https://my.gstzen.in/~gstzen/a/post-einvoice-data/einvoice-json/",  
                     method:"POST",  
                     headers: {
        'Content-Type': 'application/json',
        //'Token': 'eb3c83ae-dc9a-47ed-badf-ce994460e1c5'
        //'TOKEN':'de3a3a01-273a-4a81-8b75-13fe37f14dc6'
    },
    data: JSON.stringify(jsonBody),
                     success:function(data)  
                     {  
                        console.log('einvoiceJson',data);
                     if(data.status != 0){
                        updateSalesCode(data);
                     }else{
                        alert(data.message);
                     }
                     },
                     error: function (error) {
                        console.log(error);
                        alert(error.responseJSON.message);
                     }
                });  
    }
    function updateSalesCode(dataInvoice){
      let salesCodeData = document.getElementById('salescode').value;
      $.ajax({  
                     url:"ajaxpath/update_einvoice_sales.php",  
                     method:"POST",  
                       data: {salescode : salesCodeData,einvoiceCode : dataInvoice.InvoicePdfUrl},
                     success:function(data)  
                     {  
                        document.getElementById('redirectUrl').href = "https://my.gstzen.in"+dataInvoice.InvoicePdfUrl;

setTimeout(() => {
   document.getElementById('redirectUrl').click();
}, 100);
                     },
                     error: function (error) {
                        console.log(error);
                        alert(error.responseJSON.message);
                     }
                });  
    }
</script>
</body>
</html>