<?php
error_reporting(E_ERROR | E_PARSE);
session_start();
include '../../class/ClassForm.php';
require '../../Classes/PHPExcel.php';
include '../state_master.php';
define('_File_Loc', dirname(__FILE__));
$valid_ext = array('zip');
$folderName = date('d-m-y');
$zip_directory = "../../uploads/zip/".$folderName."/";
$zip_directory_scan = "../../uploads/zip/".$folderName;



function getIndianCurrency(float $number)
{
    $decimal = round($number - ($no = floor($number)), 2) * 100;
    $hundred = null;
    $digits_length = strlen($no);
    $i = 0;
    $str = array();
    $words = array(0 => '', 1 => 'one', 2 => 'two',
        3 => 'three', 4 => 'four', 5 => 'five', 6 => 'six',
        7 => 'seven', 8 => 'eight', 9 => 'nine',
        10 => 'ten', 11 => 'eleven', 12 => 'twelve',
        13 => 'thirteen', 14 => 'fourteen', 15 => 'fifteen',
        16 => 'sixteen', 17 => 'seventeen', 18 => 'eighteen',
        19 => 'nineteen', 20 => 'twenty', 30 => 'thirty',
        40 => 'forty', 50 => 'fifty', 60 => 'sixty',
        70 => 'seventy', 80 => 'eighty', 90 => 'ninety');
    $digits = array('', 'hundred','thousand','lakh', 'crore');
    while( $i < $digits_length ) {
        $divider = ($i == 2) ? 10 : 100;
        $number = floor($no % $divider);
        $no = floor($no / $divider);
        $i += $divider == 10 ? 1 : 2;
        if ($number) {
            $plural = (($counter = count($str)) && $number > 9) ? 's' : null;
            $hundred = ($counter == 1 && $str[0]) ? ' and ' : null;
            $str [] = ($number < 21) ? $words[$number].' '. $digits[$counter]. $plural.' '.$hundred:$words[floor($number / 10) * 10].' '.$words[$number % 10]. ' '.$digits[$counter].$plural.' '.$hundred;
        } else $str[] = null;
    }
    $Rupees = implode('', array_reverse($str));
    $paise = ($decimal > 0) ? "." . ($words[$decimal / 10] . " " . $words[$decimal % 10]) . ' Paise' : '';
    return ($Rupees ? $Rupees . 'Rupees ' : '') . $paise;
}

if(isset($_FILES['file'])){
    $filename = $_FILES['file']['name'];
    $ext = pathinfo($filename, PATHINFO_EXTENSION);
    if(in_array(strtolower($ext),$valid_ext)){
        $tmp_name = $_FILES['file']['tmp_name'];
        if(!is_dir($zip_directory)){
            mkdir($zip_directory, 7555, true);
        }

        $zip = new ZipArchive;
        if ($zip->open($tmp_name) === TRUE){            
            $zip->extractTo($zip_directory);
            $zip->close();

            $files = array_diff( scandir($zip_directory), array(".", "..") );    
            if(count($files) > 0){
                foreach($files as $json){
                    $target_loc = str_replace('tmp','json',tempnam("../../uploads/json/","invson00"));
                    $source_Loc = $zip_directory.$json;
                    if(copy($source_Loc,$target_loc)){
                        $string = file_get_contents($target_loc);
                        $data = json_decode($string, true);
    
                        $AckNo = $data['AckNo'];
                        $AckDt = $data['AckDt'];
                        $Irn = $data['Irn'];
                        $SignedInvoice = $data['SignedInvoice'];
                        $SignedQRCode = $data['SignedQRCode'];
    
                        // Decrypt Invoice Details
                        $deUrul = 'http://elearn.stvat.com/E-Invoice1/tools/decrypt_QR.php?data='.$SignedInvoice;
                        // $deUrul = 'http://192.168.1.120:94/lms-gstqrcode/tools/decrypt_QR.php?data='.$SignedInvoice;
                        $cURLConnection = curl_init();
                        curl_setopt($cURLConnection, CURLOPT_URL, $deUrul);
                        curl_setopt($cURLConnection, CURLOPT_RETURNTRANSFER, true);
                        $result_Inv = curl_exec($cURLConnection);
                        curl_close($cURLConnection);
                        $Invoice_Details = json_decode($result_Inv,true);
                        $data_inv = json_decode($Invoice_Details['data'],true);        
    
                        $itemLists = $data_inv['ItemList'];
                        $SellerGstin = $data_inv['SellerDtls']['Gstin'];
    
    
                        //B2B Finding
                        $b2b = $data_inv['TranDtls']['SupTyp'];
    
                        // Biller Details
                        $buy_name = $data_inv['BuyerDtls']['TrdNm'];
                        $buy_addr1 = $data_inv['BuyerDtls']['Addr1'];
                        $buy_addr2 = $data_inv['BuyerDtls']['Addr2'];
                        $buy_addr3 = $data_inv['BuyerDtls']['Loc']." - ".$data_inv['BuyerDtls']['Pin'];
                        $buy_addr4 = $data_inv['BuyerDtls']['TrdNm'];
                        $buy_state = ($state_list[$data_inv['BuyerDtls']['Stcd']]);
                        $buy_gstin = $data_inv['BuyerDtls']['Gstin'];
                        $buy_pan = substr($data_inv['BuyerDtls']['Gstin'],2,-3);
    
                         // Invoice Details
                        $inv_no = $data_inv['DocDtls']['No'];
                        $inv_date = $data_inv['DocDtls']['Dt'];
                        $inv_pos = $state_list[$data_inv['BuyerDtls']['Pos']];
                        $inv_sc = $data_inv['BuyerDtls']['Pos'];
                        $inv_poRef = '';
    
                        // tax Details
                        $inv_amt = $data_inv['ValDtls']['AssVal'];
                        $inv_cgst = $data_inv['ValDtls']['CgstVal'];
                        $inv_sgst = $data_inv['ValDtls']['SgstVal'];
                        $inv_Igst = $data_inv['ValDtls']['IgstVal'];
                        $inv_discnt = $data_inv['ValDtls']['Discount'];
                        $inv_oth = $data_inv['ValDtls']['OthChrg'];
                        $inv_rndOff = $data_inv['ValDtls']['RndOffAmt'];
                        $inv_total = $data_inv['ValDtls']['TotInvVal'];
                        $cgst_rate = $data_inv['ItemList'][0]['GstRt'] / 2;
                        $sgst_rate = $data_inv['ItemList'][0]['GstRt'] / 2;
                        $igst_rate = $data_inv['ItemList'][0]['IgstAmt'] != 0 ? $data_inv['ItemList'][0]['GstRt'] : 0 ;
    
                        //Qrcode Image get        
                        $QrUrul = 'http://elearn.stvat.com/E-Invoice1/qr/prqr.php?data='.$SignedQRCode;        
                        // $QrUrul = 'http://192.168.1.120:94/lms-gstqrcode/qr/prqr.php?data='.$SignedQRCode;
                        $cURLConnection1 = curl_init();
                        curl_setopt($cURLConnection1, CURLOPT_URL, $QrUrul);
                        curl_setopt($cURLConnection1, CURLOPT_RETURNTRANSFER, true);
                        $result_Qr = curl_exec($cURLConnection1);
                        curl_close($cURLConnection1);
                        $qr_Details = json_decode($result_Qr,true);        
                        $qr_inv = $qr_Details['Qr_url'];
    
                        if($b2b == "B2B"){
                            // Create Excel File        
                            $BaseAccess = 'Base Copy.xlsx';
                            $temp = '../../uploads/teps/test.xlsx';
                            $mod_invNo = str_replace('/','-',$inv_no);
                            $filNameExcel = '../../uploads/Excel/'.$buy_gstin.'-'.$mod_invNo.'_247.xlsx';
                            if(copy($BaseAccess,$temp)){                        
                            }                    
                            $excel = PHPExcel_IOFactory::load($temp);
                            $excel ->setActiveSheetIndex(0);
        
                            // Biller Details
                            $excel->getActiveSheet()->setCellValue('B14',$buy_name);
                            $excel->getActiveSheet()->setCellValue('B15',$buy_addr1);
                            $excel->getActiveSheet()->setCellValue('B16',$buy_addr2);
                            $excel->getActiveSheet()->setCellValue('B17',$buy_addr3);
                            $excel->getActiveSheet()->setCellValue('B18',$buy_state);
                            $excel->getActiveSheet()->setCellValue('D19',$buy_gstin);
                            $excel->getActiveSheet()->setCellValue('D20',$buy_pan);
    
                            // Invoice Details
                            $excel->getActiveSheet()->setCellValue('H15',$inv_no);
                            $excel->getActiveSheet()->setCellValue('J15',$inv_date);
                            $excel->getActiveSheet()->setCellValue('J17',$inv_pos);
                            $excel->getActiveSheet()->setCellValue('J18',$inv_sc);
                            $excel->getActiveSheet()->setCellValue('J19',$inv_poRef);
    
                            //  QR Details
                            $gdImage = imagecreatefrompng('../../'.$qr_inv);
                            $objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
                            $objDrawing->setName('QR image');
                            $objDrawing->setDescription('QR Details');
                            $objDrawing->setImageResource($gdImage);
                            $objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG);
                            $objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
                            $objDrawing->setHeight(200);
                            $objDrawing->setCoordinates('I3');
                            $objDrawing->setWorksheet($excel->getActiveSheet());
    
                            // IRN Details
                            $AckDetails = 'Ack.No : '.$AckNo.'         Ack.Date : '.$AckDt;
                            $excel->getActiveSheet()->setCellValue('B22','IRN');
                            $excel->getActiveSheet()->setCellValue('C22',$Irn);
                            $excel->getActiveSheet()->setCellValue('B23',$AckDetails);
    
                            // Product Details
                            $pr_ROW = 25;
    
                            foreach($itemLists as $key =>$value){
                                $sl_row = 'B'.$pr_ROW;
                                $produt_row = 'C'.$pr_ROW;
                                $hsn_row = 'I'.$pr_ROW;
                                $amount_row = 'K'.$pr_ROW;
    
                                $excel->getActiveSheet()->setCellValue($sl_row,$value['SlNo']);
                                $excel->getActiveSheet()->setCellValue($produt_row,$value['PrdDesc']);
                                $excel->getActiveSheet()->setCellValue($hsn_row,$value['HsnCd']);
                                $excel->getActiveSheet()->setCellValue($amount_row,$value['TotAmt']);
                                $pr_ROW++;            
                            }
    
    
                            // Tax Details
                            $excel->getActiveSheet()->setCellValue('K39',$inv_amt);
                            $excel->getActiveSheet()->setCellValue('K40',$inv_cgst);
                            $excel->getActiveSheet()->setCellValue('K41',$inv_sgst);
                            $excel->getActiveSheet()->setCellValue('K42',$inv_Igst);
                            $excel->getActiveSheet()->setCellValue('K43',$inv_rndOff);
                            $excel->getActiveSheet()->setCellValue('K44',$inv_total);
                            $inv_t2w = floatval($inv_total);
                            $amtInwords = 'Amount In Words:  ' ;//.getIndianCurrency(floatval($inv_t2w));
                            $excel->getActiveSheet()->setCellValue('B44',$amtInwords);
    
                            $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
                            $xyz = str_replace('.php', '.xlsx', __FILE__);
                            $objWriter->save($xyz);        
                            rename($xyz,$filNameExcel);
                            $Excel_Url = str_replace('../../','',$filNameExcel); //Excel Download Url
                            unlink($temp);
    
                            $ItemCnt = 0;
                            $jsonFile = '../../uploads/json/'.$mod_invNo.'.json';
                            rename($target_loc,$jsonFile);
                            $jsonurl = str_replace('../../','',$jsonFile);
                            //$target_loc = str_replace('/home/sridhara/elearn.stvat.com/E-Invoice/','',$target_loc);
                            $target_loc .='.json';
                            $entry = array(
                                'id'=> 0,
                                'inv_no'=> $inv_no,
                                'inv_date'=> $inv_date,
                                'qr_data'=> $SignedQRCode,
                                'irn' => $Irn,
                                'sel_gstin'=> $SellerGstin,
                                'buy_gstin'=> $buy_gstin,
                                'tot_amount'=> $inv_total,
                                'itm_count'=> $ItemCnt,
                                'qr_url'=> $qr_inv,
                                'json_url'=> $jsonurl,
                                'excel_url'=> $Excel_Url,
                                'remarks'=> $_SESSION['user_id'],
                                'extra1'=> $zip_directory,
                                'status_'=> 5                    
                            );                        
                            $status = $ClassForm->f_mysql_insert_array('qr_invdetails', $entry);
                        }
                        else{
                            // Create Excel File    For Export Invoice    
                            $BaseAccess = 'Export Copy.xlsx';
                            $temp = '../../uploads/teps/test.xlsx';
                            $mod_invNo = str_replace('/','-',$inv_no);
                            $filNameExcel = '../../uploads/Excel/'.$buy_gstin.'-'.$mod_invNo.'_247.xlsx';
                            if(copy($BaseAccess,$temp)){                        
                            }                    
                            $excel = PHPExcel_IOFactory::load($temp);
                            $excel ->setActiveSheetIndex(0);
        
                            // Biller Details
                            $excel->getActiveSheet()->setCellValue('B14',$buy_name);
                            $excel->getActiveSheet()->setCellValue('B15',$buy_addr1);
                            $excel->getActiveSheet()->setCellValue('B16',$buy_addr2);
                            $excel->getActiveSheet()->setCellValue('B17',$buy_addr3);
                            // $excel->getActiveSheet()->setCellValue('B18',$buy_state);
                            // $excel->getActiveSheet()->setCellValue('D19',$buy_gstin);
                            // $excel->getActiveSheet()->setCellValue('D20',$buy_pan);
    
                            // Invoice Details
                            $excel->getActiveSheet()->setCellValue('I13',$inv_no);
                            $excel->getActiveSheet()->setCellValue('I14',$inv_date);
                            $excel->getActiveSheet()->setCellValue('I16',$inv_pos);
                            $excel->getActiveSheet()->setCellValue('I17','N.A');
                            $excel->getActiveSheet()->setCellValue('I18','USA');
    
                            //  QR Details
                            $gdImage = imagecreatefrompng('../../'.$qr_inv);
                            $objDrawing = new PHPExcel_Worksheet_MemoryDrawing();
                            $objDrawing->setName('QR image');
                            $objDrawing->setDescription('QR Details');
                            $objDrawing->setImageResource($gdImage);
                            $objDrawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG);
                            $objDrawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
                            $objDrawing->setHeight(200);
                            $objDrawing->setCoordinates('I3');
                            $objDrawing->setWorksheet($excel->getActiveSheet());
    
                            // IRN Details
                            $AckDetails = 'Ack.No : '.$AckNo.'         Ack.Date : '.$AckDt;
                            $excel->getActiveSheet()->setCellValue('B22','IRN');
                            $excel->getActiveSheet()->setCellValue('C22',$Irn);
                            $excel->getActiveSheet()->setCellValue('B23',$AckDetails);
    
                            // Product Details
                            $pr_ROW = 25;
    
                            foreach($itemLists as $key =>$value){
                                $sl_row = 'B'.$pr_ROW;
                                $produt_row = 'C'.$pr_ROW;
                                $hsn_row = 'I'.$pr_ROW;
                                $amount_row = 'K'.$pr_ROW;
                                $total_cost = 'H'.$pr_ROW;
    
                                $excel->getActiveSheet()->setCellValue($sl_row,$value['SlNo']);
                                $excel->getActiveSheet()->setCellValue($produt_row,$value['PrdDesc']);
                                // $excel->getActiveSheet()->setCellValue($hsn_row,$value['HsnCd']);
                                $excel->getActiveSheet()->setCellValue($total_cost,$value['TotAmt']);
                                $excel->getActiveSheet()->setCellValue($amount_row,$value['TotAmt']);
                                $pr_ROW++;            
                            }
    
    
                            // Tax Details
                            // $excel->getActiveSheet()->setCellValue('K39',$inv_amt);
                            // $excel->getActiveSheet()->setCellValue('K40',$inv_cgst);
                            // $excel->getActiveSheet()->setCellValue('K41',$inv_sgst);
                            // $excel->getActiveSheet()->setCellValue('K42',$inv_Igst);
                            // $excel->getActiveSheet()->setCellValue('K43',$inv_rndOff);
                            // $excel->getActiveSheet()->setCellValue('K35',$inv_total);
                            $excel->getActiveSheet()->setCellValue('K37',$inv_total);
                            $inv_t2w = floatval($inv_total);
                            $amtInwords = 'Amount In Words:  '; //.getIndianCurrency(floatval($inv_t2w));
                            $excel->getActiveSheet()->setCellValue('B44',$amtInwords);
    
                            $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
                            $xyz = str_replace('.php', '.xlsx', __FILE__);
                            $objWriter->save($xyz);        
                            rename($xyz,$filNameExcel);
                            $Excel_Url = str_replace('../../','',$filNameExcel); //Excel Download Url
                            unlink($temp);
    
                            $ItemCnt = 0;
                            $jsonFile = '../../uploads/json/'.$mod_invNo.'.json';
                            rename($target_loc,$jsonFile);
                            $jsonurl = str_replace('../../','',$jsonFile);
                            //$target_loc = str_replace('/home/sridhara/elearn.stvat.com/E-Invoice/','',$target_loc);
                            $target_loc .='.json';
                            $entry = array(
                                'id'=> 0,
                                'inv_no'=> $inv_no,
                                'inv_date'=> $inv_date,
                                'qr_data'=> $SignedQRCode,
                                'irn' => $Irn,
                                'sel_gstin'=> $SellerGstin,
                                'buy_gstin'=> $buy_gstin,
                                'tot_amount'=> $inv_total,
                                'itm_count'=> $ItemCnt,
                                'qr_url'=> $qr_inv,
                                'json_url'=> $jsonurl,
                                'excel_url'=> $Excel_Url,
                                'remarks'=> $_SESSION['user_id'],
                                'extra1'=> $target_loc,
                                'status_'=> 5
                        
                            );                        
                            $status = $ClassForm->f_mysql_insert_array('qr_invdetails', $entry);
                        }
                        
                        // if(!$status['mysqli_error']){
                        //     $return_array = array(
                        //         'status' => '1',
                        //         'status_info' => 'details uploaded successfully..',
                        //         'download' =>$Excel_Url,
                        //     );
                        //     echo $jsonformat = json_encode($return_array);    
                        //     exit;
                        // }
    
                    }
                    else{
    
                    }
    
                }
                $return_array = array(
                    'status' => '1',
                    'status_info' => 'details uploaded successfully..',
                    // 'download' =>$Excel_Url,
                    'download' => 'bilapi'
                );
                echo $jsonformat = json_encode($return_array);    
                exit;
            }
            else{
                $return_array = array(
                    'status' => '2',
                    'status_info' => 'Not able to open zip files',
                    // 'download' =>$Excel_Url,
                    'download' => 'bilapi'
                );
                echo $jsonformat = json_encode($return_array);    
                exit;
            }        
            
        }
        else{
            $return_array = array(
                'status' => '2',
                'status_info' => 'Not able to open zip files',
                // 'download' =>$Excel_Url,
                'download' => 'bilapi'
            );
            echo $jsonformat = json_encode($return_array);    
            exit;
        }
    }
    else{
        $return_array = array(
            'status' => '2',
            'status_info' => 'File Format Not Supported',
            // 'download' =>$Excel_Url,
            'download' => 'bilapi'
        );
        echo $jsonformat = json_encode($return_array);    
        exit;
    }

    
}
?>