<?php
session_start();
error_reporting(E_ERROR | E_PARSE);
date_default_timezone_set('asia/kolkata');
include '../../class/ClassForm.php';
include '../../pages/state_master.php';
include '../../qr/qrlib.php';
require '../../Classes/PHPExcel.php';
require '../../Firebase/JWT/JWT.php';
$dt = new DateTime();
$dt = $dt->format('d-m-Y_h-i');
$key = "-----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArxd93uLDs8HTPqcSPpxZrf0
    Dc29r3iPp0a8filjAyeX4RAH6lWm9qFt26CcE8ESYtmo1sVtswvs7VH4Bjg/FDlRpd+MnAlX
    uxChij8/vjyAwE71ucMrmZhxM8rOSfPML8fniZ8trr3I4R2o4xWh6no/xTUtZ02/yUEXbphw3
    DEuefzHEQnEF+quGji9pvGnPO6Krmnri9H4WPY0ysPQQQd82bUZCk9XdhSZcW/am8w
    BulYokITRMVHlbRXqu1pOFmQMO5oSpyZU3pXbsx+OxIOc4EDX0WMa9aH4+snt18WA
    XVGwF2B4fmBk7AtmkFzrTmbpmyVqA3KO2IjzMZPw0hQIDAQAB
-----END PUBLIC KEY-----";
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'../Qr_Files'.DIRECTORY_SEPARATOR;
$PNG_WEB_DIR = 'Qr_Files/temp/';
$errorCorrectionLevel = 'L';
$matrixPointSize = 4;
function getIndianCurrency(float $number){
    $dround = round($number - ($no = floor($number)), 2);
    $decimal =  $dround * 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));
    $decimal = ($decimal < 10) ? $decimal+10 : $decimal;
    $paise = ($decimal > 0) ? "." . ($words[$decimal / 10] . " " . $words[$decimal % 10]) . ' Paise' : '';
    return ($Rupees ? $Rupees . 'Rupees ' : '') . $paise;
}
function filename($unsafeFilename){
    $dangerousCharacters = array(" ", '"', "'", "&", "/", "\\", "?", "#");
    $safe_filename = str_replace($dangerousCharacters, '_', $unsafeFilename);  
    return $safe_filename;
}
if(isset($_SESSION['user']) && $_SESSION['user'] == "Rane"){
    if(isset($_FILES['file'])){
        //$target_loc = str_replace('tmp','json',tempnam("ImportFiles/","inv_".$dt."_"));
        $target_loc = "../ImportFiles/json_".$dt.".json";
        $filename = $_FILES['file']['name'];
        $filesize = $_FILES['file']['size'];
        $return_arr = array();
        
        if(move_uploaded_file($_FILES['file']['tmp_name'],$target_loc)){
            $jsonurl = 'rane/'.str_replace('../','',$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']; 
            $EwbNo = $data['EwbNo'] ? $data['EwbNo'] : '' ; 
            $EwbDt = $data['EwbDt'] ? $data['EwbDt'] : '' ;
            $EwbValidTill = $data['EwbValidTill'] ? $data['EwbValidTill'] : '';
            if(trim($SignedInvoice) != ''){                                               
                $result_Inv = json_encode(JWT::decode($SignedInvoice,$key, array('RS256')));            
                $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 = $data_inv['TranDtls']['SupTyp'];
                $SellerDtls = $data_inv['SellerDtls'];
                $EwbDtls = $data_inv['EwbDtls'];
                $ValDtls = $data_inv['ValDtls'];
                // Biller Details
                $buy_name = $data_inv['BuyerDtls']['LglNm'];
                $buy_addr1 = $data_inv['BuyerDtls']['Addr1'];
                $buy_addr2 = $data_inv['BuyerDtls']['Loc'];
                $buy_addr3 = $state_list[$data_inv['BuyerDtls']['Stcd']]." - ".$data_inv['BuyerDtls']['Pin'];
                $buy_addr4 = $data_inv['BuyerDtls']['LglNm'];
                $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 ;

                if (!file_exists($PNG_TEMP_DIR)){
                    mkdir($PNG_TEMP_DIR);
                }
                $Qr_filename = $PNG_TEMP_DIR.filename($inv_no)."_".$dt.".png";
                $qr_inv = 'rane/Qr_Files/'.filename($inv_no)."_".$dt.".png";
                QRcode::png($SignedQRCode, $Qr_filename, $errorCorrectionLevel, $matrixPointSize, 2);                    
                if($b2b == "B2B"){
                    $BaseAccess = 'RaneInvoice.xlsx';
                    $temp = dirname(__FILE__).DIRECTORY_SEPARATOR."../Output".DIRECTORY_SEPARATOR.substr($dt,0,10);
                    $filNameExcel = dirname(__FILE__).DIRECTORY_SEPARATOR.'../Output'.DIRECTORY_SEPARATOR.$buy_gstin.DIRECTORY_SEPARATOR;
                    if (!file_exists($temp)){
                        mkdir($temp);
                    }
                    if (!file_exists($filNameExcel)){
                        mkdir($filNameExcel);
                    }
                    $filNameExcel = $filNameExcel.DIRECTORY_SEPARATOR.filename($inv_no).'_'.$dt.'_.xlsx';
                    $temp = $temp.DIRECTORY_SEPARATOR.filename($inv_no)."_".$dt.".xlsx";
                    $Excel_Url = 'rane/Output'.DIRECTORY_SEPARATOR.$buy_gstin.DIRECTORY_SEPARATOR.filename($inv_no).'_'.$dt.'_.xlsx';

                    if(copy($BaseAccess,$temp)){
                        $excel = PHPExcel_IOFactory::load($temp);
                        $excel ->setActiveSheetIndex(0);

                        //SELLER iNFO     
                        if($SellerDtls['Gstin'] == '06AACCR9772M1ZP'){
                            $excel->getActiveSheet()->setCellValue('D2',strtoupper($SellerDtls['TrdNm']));
                            $excel->getActiveSheet()->setCellValue('D3','KHARSA NO: 2916,KATARIA COMPLEX ,');
                            $excel->getActiveSheet()->setCellValue('D4','DAULTABAD, GURGAON');
                            $excel->getActiveSheet()->setCellValue('D5','HARYANA (06) - 122001');
                            $excel->getActiveSheet()->setCellValue('H7',$SellerDtls['Gstin']);
                        }
                        else{
                            $excel->getActiveSheet()->setCellValue('D2',strtoupper($SellerDtls['TrdNm']));
                            $excel->getActiveSheet()->setCellValue('D3',strtoupper($SellerDtls['Addr1']));
                            $excel->getActiveSheet()->setCellValue('D4',strtoupper($SellerDtls['Addr2']));
                            //$excel->getActiveSheet()->setCellValue('D5',strtoupper(($state_list[$SellerDtls['Stcd']]).' - '.($SellerDtls['Pin'])));
                            $excel->getActiveSheet()->setCellValue('D5',strtoupper(($state_list[$SellerDtls['Stcd']]).'('.$SellerDtls['Stcd'].') - '.($SellerDtls['Pin'])));
                            $excel->getActiveSheet()->setCellValue('H7',$SellerDtls['Gstin']);
                        }        

                        // E-way Bill
                        $excel->getActiveSheet()->setCellValue('H24',$EwbNo);
                        $excel->getActiveSheet()->setCellValue('h25',$EwbDt);

                        // Billed to Details
                        $excel->getActiveSheet()->setCellValue('A7',$buy_name);
                        $excel->getActiveSheet()->setCellValue('A8',$buy_addr1);
                        $excel->getActiveSheet()->setCellValue('A9',$buy_addr2);
                        $excel->getActiveSheet()->setCellValue('A10',$buy_addr3);
                        
                        $excel->getActiveSheet()->setCellValue('F12',$buy_name);
                        $excel->getActiveSheet()->setCellValue('F13',$buy_addr1);
                        $excel->getActiveSheet()->setCellValue('F14',$buy_addr2);
                        $excel->getActiveSheet()->setCellValue('F15',$buy_addr3);

                        //$excel->getActiveSheet()->setCellValue('H16',$buy_state);
                        $excel->getActiveSheet()->setCellValue('H18',$buy_gstin);
                        $excel->getActiveSheet()->setCellValue('H19',$buy_pan);
                        //$excel->getActiveSheet()->setCellValue('C11',$buy_state);
                        $excel->getActiveSheet()->setCellValue('C12',$buy_gstin);
                        $excel->getActiveSheet()->setCellValue('C13',$buy_pan);

                        // E-way Bill Details
                        $excel->getActiveSheet()->setCellValue('C21',$EwbDtls['TransName']);
                        //$excel->getActiveSheet()->setCellValue('C22',$EwbDtls['VehNo']);
                        $excel->getActiveSheet()->setCellValue('C23',$Eway_mot[$EwbDtls['TransMode']]);
                        
                        // Invoice Details
                        $excel->getActiveSheet()->setCellValue('H8',$inv_no);
                        $excel->getActiveSheet()->setCellValue('H16',$inv_no);
                        $excel->getActiveSheet()->setCellValue('H9',$inv_date);
                        $excel->getActiveSheet()->setCellValue('C11',$inv_pos);
                        $excel->getActiveSheet()->setCellValue('H17',$state_list[$inv_sc].'('.$inv_sc.')');
                        $excel->getActiveSheet()->setCellValue('F21',$inv_poRef);

                        //  QR Details
                        $gdImage = imagecreatefrompng($Qr_filename);
                        $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('J8');
                        $objDrawing->setWorksheet($excel->getActiveSheet());

                        // IRN Details
                        $AckDetails = 'Ack.No : '.$AckNo.'         Ack.Date : '.$AckDt;
                        $excel->getActiveSheet()->setCellValue('F6','IRN : '.$Irn);
                        //$excel->getActiveSheet()->setCellValue('C22',$Irn);
                        //$excel->getActiveSheet()->setCellValue('B23',$AckDetails);

                        $pr_ROW = 29;
                        $total_qty =0;
                        foreach($itemLists as $key =>$value){
                          
                            $sl_row = 'A'.$pr_ROW;
                            $part_row = 'B'.$pr_ROW;
                            $hsn_row = 'C'.$pr_ROW;
                            $qty_row = 'D'.$pr_ROW;
                            $unit_row = 'E'.$pr_ROW;
                            $rate_row = 'F'.$pr_ROW;
                            $toal_row = 'G'.$pr_ROW;
                            $dicnt_row = 'H'.$pr_ROW;
                            $taxable_row = 'I'.$pr_ROW;
                            $sgst_row = 'J'.$pr_ROW;
                            $cgst_row = 'K'.$pr_ROW;
                            $igst_row = 'L'.$pr_ROW;                           
                             $total_qty += $value['Qty'];
                            $excel->getActiveSheet()->setCellValue($sl_row,$value['SlNo']);
                            $excel->getActiveSheet()->setCellValue($part_row,'');
                            $excel->getActiveSheet()->setCellValue($hsn_row,$value['HsnCd']);
                            $excel->getActiveSheet()->setCellValue($qty_row,$value['Qty']);
                            $excel->getActiveSheet()->setCellValue($rate_row,$value['UnitPrice']);
                            $excel->getActiveSheet()->setCellValue($toal_row,$value['TotAmt']);
                            $excel->getActiveSheet()->setCellValue($dicnt_row,$value['Discount']);
                            $excel->getActiveSheet()->setCellValue($taxable_row,$value['AssAmt']);
                            $excel->getActiveSheet()->setCellValue($sgst_row,$value['SgstAmt']);
                            $excel->getActiveSheet()->setCellValue($cgst_row,$value['CgstAmt']);
                            $excel->getActiveSheet()->setCellValue($igst_row,$value['IgstAmt']);
                            $pr_ROW++;
                            $Product_row = 'B'.$pr_ROW;
                            $sgst2_row = 'J'.$pr_ROW;
                            $cgst2_row = 'K'.$pr_ROW;
                            $igst2_row = 'L'.$pr_ROW;

                            $excel->getActiveSheet()->setCellValue($Product_row,$value['PrdDesc']);
                            $excel->getActiveSheet()->setCellValue($sgst2_row,($value['GstRt']/2).'%');
                            $excel->getActiveSheet()->setCellValue($cgst2_row,($value['GstRt']/2).'%');
                            $excel->getActiveSheet()->setCellValue($igst2_row,$value['GstRt'].'%');
                            $pr_ROW++;
                        }

                        //ValDtls
                        //$excel->getActiveSheet()->setCellValue('I41',$ValDtls['AssVal']);
                        $excel->getActiveSheet()->setCellValue('D40',$total_qty);
                        //$excel->getActiveSheet()->setCellValue('I40',$ValDtls['AssVal']);
                        $excel->getActiveSheet()->setCellValue('J40',$ValDtls['SgstVal']);
                        $excel->getActiveSheet()->setCellValue('K40',$ValDtls['CgstVal']);
                        $excel->getActiveSheet()->setCellValue('L40',$ValDtls['IgstVal']);
                        $totTaxVal = $ValDtls['SgstVal'] + $ValDtls['CgstVal'] + $ValDtls['IgstVal'];
                        $excel->getActiveSheet()->setCellValue('J41',$totTaxVal);
                        $excel->getActiveSheet()->setCellValue('J43',$ValDtls['TotInvVal']);

                        //$tAinwords = getIndianCurrency(floatval($ValDtls['TotInvVal']));
                        $tAinwords = floatval($ValDtls['TotInvVal']);
                        $tAinwords = getIndianCurrency($tAinwords);
                        $tAinwords = "In Words".strtoupper($tAinwords);
                        $excel->getActiveSheet()->setCellValue('A44',$tAinwords);
                        $gstAinwords = $ValDtls['SgstVal'] + $ValDtls['CgstVal'] + $ValDtls['IgstVal'] + $ValDtls['StCesVal'] + $ValDtls['CesVal'] ;
                        $gstAinwords = floatval($gstAinwords);
                        $gstAinwords = getIndianCurrency($gstAinwords);
                        $gstAinwords = "In Words".strtoupper($gstAinwords);
                        $excel->getActiveSheet()->setCellValue('A42',$gstAinwords);
                        $objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
                        $xyz = str_replace('.php', '.xlsx', __FILE__);
                        $objWriter->save($xyz); 
                        rename($xyz,$filNameExcel);
                        unlink($temp);
                        $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);
                        $return_array = array(
                            'status' => 'true',
                            'message' => 'Invoice Uploaded Successfully'
                        );
                        echo $jsonformat = json_encode($return_array);
                        exit;
                    }
                    else{
                        $return_array = array(
                            'status' => 'false',
                            'message' => $temp
                        );
                        echo $jsonformat = json_encode($return_array);
                        exit;
                    }
                }
                $return_array = array(
                    'status' => 'true',
                    'message' => 'File Uploaded Successfully. Please visit View/Download'
                );
                echo $jsonformat = json_encode($return_array);
                exit;
            }
            else{
                $return_array = array(
                    'status' => 'false',
                    'message' => 'Json File Upload Failed. Please Contact Administrator'
                );
                echo $jsonformat = json_encode($return_array);
                exit;
            }
        }
        else{
            $return_array = array(
                'status' => 'false',
                'message' => 'Json File Upload Failed. Please Contact Administrator'
            );
            echo $jsonformat = json_encode($return_array);
            exit;
        }
    }
    else{
        $return_array = array(
            'status' => 'false',
            'message' => 'File Upload Failed. Please Contact Administrator',
        );
        echo $jsonformat = json_encode($return_array);
        exit;
    }
    
}
else{
    $return_array = array(
        'status' => 'false',
        'message' => 'File Upload Failed. Please Contact Administrator',
    );
    echo $jsonformat = json_encode($return_array);
    exit;

}
?>