<?php 
session_start();
include "../../../config/database.php";
$conct  = new connectionCreat();
$conct->connectToDB();
$conct->selectDB();
include "../../../config/function.php";
$take_action1   = new actionDo();

ini_set('max_input_vars',10000);
ini_set('max_post_vars',10000);
ini_set('max_request_vars',10000);

function get_word($val)
{
    $number = $val;
	$no = round($number);
	$point = round($number - $no, 2) * 100;
	$hundred = null;
	$digits_1 = 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_1) {
	$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) ? ' ' : 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;
	}
	$str = array_reverse($str);
	$result = implode('', $str);
	$points = ($point) ?
	$words[$point / 10] . " " . 
	$words[$point = $point % 10] : '';
	if(!empty($points))
	{   return $result . "Rupees  " . $points . " Paise";	}
	else
	{	return $result . "   "; }
} 
function makecomma($input)
{
    // This function is written by some anonymous person - I got it from Google
    if(strlen($input)<=2)
    { return $input; }
    $length=substr($input,0,strlen($input)-2);
    $formatted_input = makecomma($length).",".substr($input,-2);
    return $formatted_input;
}

function formatInIndianStyle($num)
{
    // This is my function
    $pos = strpos((string)$num, ".");
    if ($pos === false) { $decimalpart="00";}
    else { $decimalpart= substr($num, $pos+1, 2); $num = substr($num,0,$pos); }

    if(strlen($num)>3 & strlen($num) <= 12){
                $last3digits = substr($num, -3 );
                $numexceptlastdigits = substr($num, 0, -3 );
                $formatted = makecomma($numexceptlastdigits);
                $stringtoreturn = $formatted.",".$last3digits.".".$decimalpart ;
    }elseif(strlen($num)<=3){
                $stringtoreturn = $num.".".$decimalpart ;
    }elseif(strlen($num)>12){
                $stringtoreturn = number_format($num, 2);
    }

    if(substr($stringtoreturn,0,2)=="-,"){$stringtoreturn = "-".substr($stringtoreturn,2 );}

    return $stringtoreturn;
}
function getSundays($y,$m)
{ 
	$date = "$y-$m-01";
	$first_day = date('N',strtotime($date));
	$first_day = 7 - $first_day + 1;
	$last_day =  date('t',strtotime($date));
	$days = array();
	for($i=$first_day; $i<=$last_day; $i=$i+7 )
	{
		$days[] = $i;
	}
	return  $days; 
}
//// Check Bill Exists or Not
$month			 = $_SESSION['att_month']	= $_POST['month'];
$year			 = $_SESSION['att_year']		= $_POST['year'];
$d		 		 = cal_days_in_month(CAL_GREGORIAN,$month,$year);
$sun_arr   		 = getSundays($year,$month);
$sunday_dts_arr= array();
foreach($sun_arr as $key)
{
	array_push($sunday_dts_arr,$year."-".$month."-".$key);	 
}
$sunday_dts		= implode("','",$sunday_dts_arr);
$sundays		= $sundays_1    = count($sun_arr);
$from      		= date("Y-m-d",strtotime("01-$month-$year"));
$to	   			= date("Y-m-d",strtotime("$d-$month-$year"));
$_SESSION['att_state']     =  $state	 	= $_POST['state'];	
$bill_type		= "New";
$invoice_no 	= 0;
$invoice_prefix	= "RHLLP/2023-2024/";
$sql_no			= mysql_query("select max(`invoice_no`) from `tbl_invoice` where `invoice_prefix`='$invoice_prefix' ")or die(mysql_error());
$data_no		= mysql_fetch_array($sql_no);
if( ($data_no['max(`invoice_no`)']=='') || ($data_no['max(`invoice_no`)']=='NULL') )
{
	$invoice_no	 = 1;
}
else
{
	$invoice_no	 = $data_no['max(`invoice_no`)']+1;
}
	
$monthName  = date('F', mktime(0, 0, 0, $_POST['month'], 10));
$table		= "<section class='sheet padding-10mm'><article>";
$th         = '
<table cellspacing="0" width="100%" border="1">
            <thead>
            <tr>
                <th width="5%">S No.</th>
                <th width="15%">Name</th>
                <th width="5%">Designation</th>
                <th width="5%">Headquarter</th>
                <th width="5%">State</th>
                <th width="5%">'.$monthName." ".$_POST['year'].' Payment</th>        
            </tr>
            </thead>
            <tbody>';
$table		.=$th;			
		
            if($state=='ALL') 
            {
              $sql			= mysql_query(" SELECT distinct `id`,`emp_name`,`desiganation`,`head_qtrer`,`salary_rate`,`da_rate`,`phone_rate`,`ta_rate`,`travel_exp`,`state` FROM `tbl_emp_records` WHERE `status`='0' order by `emp_name`,`state` ASC")or die(mysql_error());
            }
			else
            {
			  $emp_name	    = $_SESSION['att_emp_name']		= $_POST['emp_name'];
			  if($emp_name =='ALL')
			  {
              	$sql			= mysql_query(" SELECT distinct `id`,`emp_name`,`desiganation`,`head_qtrer`,`salary_rate`,`da_rate`,`phone_rate`,`ta_rate`,`travel_exp`,`state` FROM `tbl_emp_records` WHERE `status`='0' and `state`='$state' order by `emp_name`,`state` ASC")or die(mysql_error());
			  }
			  else
			  {
              	$sql			= mysql_query(" SELECT distinct `id`,`emp_name`,`desiganation`,`head_qtrer`,`salary_rate`,`da_rate`,`phone_rate`,`ta_rate`,`travel_exp`,`state` FROM `tbl_emp_records` WHERE `status`='0' and `id`='$emp_name' and `state`='$state' order by `emp_name`,`state` ASC")or die(mysql_error());
			  }
            }
            $i					= 0;
            $j					= 0;
			$total				= 0;
			$cout_rows			= mysql_num_rows($sql);
            while($row			= mysql_fetch_array($sql))
            {
				$state_1		= $row['state'];
				$off_in_month   	= 0;$lea_in_month = 0;$wor_in_month = 0;$per_in_month	= 0;$b_wr_in_month = 0;	$su_w_in_month = 0;$ho_w_in_month	= 0;$days_retailed	= 0;$basic_sal		= 0;$da_sal			= 0;$phone_sal		= 0;$ta_sal			= 0.00;$misc_sal		= 0.0;$salary	= 0;$da_final_sal = 0;$ta_final_sal = 0.00;$ph_final_sal = 0;$misc_final_sal = 0;$final_salary = 0;
				$emp_id				= $row['id'];
				///Seprate Calculate
				/*$sep_qry			= mysql_query(" select max(`date`) from `tbl_attendence` where `emp_id`='$emp_id' and `state`='$state_1' and `mark`='7' and `date` between '$from' and '$to' ")or die(mysql_error());
				$sep_data   		= mysql_fetch_array($sep_qry);
				if(isset($sep_data['max(`date`)']))
				{
					$start 		= new DateTime($from);
					$end 		= new DateTime($sep_data['max(`date`)']);
					$days 		= $start->diff($end, true)->days;					
					$sundays_1 	= intval($days / 7) + ($start->format('N') + $days % 7 >= 7);
				}*/
				///Weekly Off Calculate
				$w_off_qry		= mysql_query(" select count(*) from `tbl_attendence` where `emp_id`='$emp_id' and `state`='$state_1' and `mark`='5' and `date` between '$from' and '$to' ")or die(mysql_error());
				$w_off_data   	= mysql_fetch_array($w_off_qry);
				$w_off_in_month	= $w_off_data['count(*)'];
				///Holidays Calculate
				$off_qry		= mysql_query(" select count(*) from `tbl_attendence` where `emp_id`='$emp_id' and `state`='$state_1' and `mark`='2' and `date` between '$from' and '$to' ")or die(mysql_error());
				$off_data   	= mysql_fetch_array($off_qry);
				$off_in_month	= $off_data['count(*)'];
				///working days
				$wor_in_month	= ($d-$sundays-$off_in_month);
				///Leave Calculate
				$lea_qry		= mysql_query(" select count(*) from `tbl_attendence` where `emp_id`='$emp_id' and `state`='$state_1' and `mark` IN('3','4') and `date` between '$from' and '$to' ")or die(mysql_error());
				$lea_data   	= mysql_fetch_array($lea_qry);
				$lea_in_month	= $lea_data['count(*)'];
				///Persent Calculate
				//and `date` NOT IN('$sunday_dts')
				$per_qry		= mysql_query(" select count(*) from `tbl_attendence` where `emp_id`='$emp_id' and `state`='$state_1' and `mark`='1' and `date` between '$from' and '$to' ")or die(mysql_error());
				$per_data   	= mysql_fetch_array($per_qry);
				$per_in_month	= $per_data['count(*)'];
				//// Balance Workin Days in month
				$b_wr_in_month	= $per_in_month;// - $lea_in_month);
				///Sunday Worked Calculate
				$sun_w_qry		= mysql_query(" select count(*) from `tbl_attendence` where `emp_id`='$emp_id' and `state`='$state_1' and `mark`='1' and `date` IN ('$sunday_dts') ")or die(mysql_error());
				$sun_w_data= mysql_fetch_array($sun_w_qry);
				
				if($_SESSION['att_state']=='West Bangal')
				{
				    $su_w_in_month  = 0;
				}
				else
				{
				    $su_w_in_month  = $sun_w_data['count(*)'];
				}
				
				/////Holidays Working Days
				///Days Retailed
				$days_retailed	= ($b_wr_in_month+$ho_w_in_month+$su_w_in_month);
				///basic salary
				$basic_sal		= $row['salary_rate'];
				$da_sal			= $row['da_rate'];
				$phone_sal		= $row['phone_rate'];
				$ta_sal			= $row['ta_rate'];
				$misc_sal		= $row['travel_exp'];
				/////Main Calculations
				$a              = ($b_wr_in_month+$w_off_in_month+$off_in_month+$su_w_in_month);
				$salary			= ($basic_sal/$d) * $a;
				if($salary>$basic_sal)
				{
					$salary     = $basic_sal;
				}
				
				$da_final_sal	= $days_retailed*$da_sal;
				
				if($_SESSION['att_state']=='West Bangal')
				{
				    if($da_final_sal>3750)
    				{
    					$da_final_sal = 3750;	
    				}    
				}
				else
				{
				    if($da_final_sal>2500)
    				{
    					$da_final_sal = 2500;	
    				}
				}
				
				if(($month==2)&&($da_sal!=0))
				{
					if($_SESSION['att_state']=='West Bangal')
    				{
    				    if($da_final_sal>3750)
        				{
        					$da_final_sal = 3750;	
        				}    
    				}
    				else
    				{
    					if( ($per_in_month+$w_off_in_month)==$d)
    					{
    						$da_final_sal = 2500;	
    					}
    				}
				}
				$ph_final_sal	= ($phone_sal/$d)*$a;
				if($ph_final_sal>500)
				{
					$ph_final_sal = 500;	
				}
				$ta_final_sal	= ($ta_sal)*$days_retailed;
				if($ta_final_sal>3000)
				{
					$ta_final_sal = 3000;	
				}				
				$misc_final_sal	= ($misc_sal);
				$final_salary   = ($salary+$da_final_sal+$ta_final_sal+$ph_final_sal+$misc_final_sal);
				if($final_salary>0)
				{
				////ISR Details 
				mysql_query(" insert into `tbl_isr_details` SET `emp_id`='$emp_id',`invoice_no`='$invoice_no', `invoice_prefix`='$invoice_prefix', `amt`='".round($final_salary)."' ")or die(mysql_error());					
				$i++;
				$j++;
$table       .= '<tr>
            	<td style="text-align:center;">'.$j.'</td>
                <td>'.ucwords(strtolower($row['emp_name'])).'</td>
                <td style="text-align:center;">'.$row['desiganation'].'</td>
                <td style="text-align:center;">'.ucwords(strtolower($row['head_qtrer'])).'</td>
                <td style="text-align:center;">'.ucwords(strtolower($row['state'])).'</td>
                <td style="text-align:right;">&#8377; '.formatInIndianStyle(round($final_salary)).'</td>
            </tr>';
				$total		= $total+round($final_salary);
				}
			
            	if( ($cout_rows>16) && ($i==16) ) 
				{
					$i=0;
					$table       .= '</tbody></table></article></section>
					<section class="sheet padding-10mm"><article>'.$th;
				}
				/*( ($cout_rows>46) && ($i==46) ) 
				{
					$table       .= '</tbody></table></article></section>
					<section class="sheet padding-10mm"><article>'.$th;
				}
				if( ($cout_rows>70) && ($i==70) ) 
				{
					$table       .= '</tbody></table></article></section>
					<section class="sheet padding-10mm"><article>'.$th;
				}
				if( ($cout_rows>96) && ($i==96) ) 
				{
					$table       .= '</tbody></table></article></section>
					<section class="sheet padding-10mm"><article>'.$th;
				}*/
			}
$table       .= '<tr>
            	<th style="text-align:center;" colspan="3">State Total</th>
                <th style="text-align:center;" colspan="2">Total : '.$j.'</th>
                <th style="text-align:right;">&#8377; '.formatInIndianStyle($total).'</th>
            </tr>';
			
$table       .= ' </tbody></table>';
///genrate bill insert
mysql_query(" insert into `tbl_invoice` SET `invoice_no`='$invoice_no', `invoice_prefix`='$invoice_prefix', `state`='$state',`month`='$month',`year`='$year',`amt`='$total',`date`='".date("Y-m-d")."' ")or die(mysql_error());

$sql_state		 = mysql_query("select * from `state` where `state_name`='$state' ")or die(mysql_error());
$data_state		 = mysql_fetch_array($sql_state);

$pre_qry		 = "";
if(!empty($invoice_prefix))
{
	$pre_qry	 = " and `invoice_prefix`='$invoice_prefix' ";
}

$sql_no			 = mysql_query("select * from `tbl_invoice` where `invoice_no`='$invoice_no' $pre_qry ")or die(mysql_error());
$data_no		 = mysql_fetch_array($sql_no);
?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Rudraansh Holdings LLP</title>
<link rel="stylesheet" href="normalize.css">
<link rel="stylesheet" href="paper.css">
<style>
body{ margin:0 auto !important;}

body{ font-family:"Times New Roman", Times, serif;font-size:16px; line-height:24px;}
.wrapper{ margin:0 auto; width:900px;}
.wrapper h4{ margin:0; text-align:center; font-weight:bold; font-size:15px; padding:10px 0}
.wrapper h1{ margin:0; text-align:center; font-weight:bold; font-size:40px; padding:10px 0}
.wrapper h3{ margin:0; text-align:center; font-weight:normal;padding:10px 0;}
.dot_br{ border-bottom:#000 double ; border-top:#000 solid 1px; padding:10px 0;}
table td{ padding:5px !important;}
.top_br{ border-top:#fff solid 1px !important;}
.but_br{ border-bottom:#fff solid 1px !important;}
@page { size: A4 }
</style>
</head>
<body class="A4">
<div class="wrapper">
	<section class="sheet padding-10mm">
<article>
       
<h4>Invoice</h4>
<h1>Rudraansh Holdings LLP</h1>
<h3>Apartment No. C 1st, Chittora Apartments, A-4, Tilak Marg, C-Scheme, Jaipur - 302 001</h3>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="dot_br">
  <tr>
    <td width="7%">PAN</td>
    <td width="33%"><strong>AATFR9757Q</strong></td>
    <td width="29%">&nbsp;</td>
    <td width="9%">GSTN</td>
    <td width="22%"><strong>08AATFR9757Q1ZP</strong></td>
  </tr>
</table><br />

<table width="100%" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <td width="15%"><strong>Invoice No.:</strong></td>
    
    <td width="50%"><?php echo $invoice_prefix.str_pad($invoice_no, 3, '0', STR_PAD_LEFT);?></td>
    <td width="30%" align="right"><strong>Dated :</strong></td>
    <td width="5%" align="left"><?php echo date("d-M-Y");?></td>
  </tr>  
  
  <?php
	if( ($data_no['bill_type']=='Multiple') && ($state=='ALL'))
	{
	?>
    <tr>
    <td colspan="2">To<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>RSPL Limited</strong><br>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Plot No. 119, 120, 121, Block P&T, Kalpi Road, &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fazalganj, Kanpur, Uttar Pradesh</td>
    <td align="right" class="top_br"><strong>GSTN :</strong></td>
    <td align="right"><strong>09AADCS7820A2ZK</strong></td>
    </tr>
    <?php	
	}
	else if( ($data_no['bill_type']=='Multiple') && ($state !='ALL'))
	{
	?>
    <tr>
    <td colspan="2">To<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>RSPL Limited</strong><br>
    <p style="margin-left: 21px;text-align: justify;margin-top: 0px;">
    <?php echo ucwords(strtolower($data_state['st_address']));?>
    </p>
    </td>
    <td align="right" class="top_br"><strong>GSTN :</strong></td>
    <td align="right"><strong><?php echo $data_state['gst_no'];?></strong></td>
    </tr>
    <?php	
	}
	else
	{?>
    <tr>
    <td colspan="2">To<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>RSPL Limited</strong><br>
    <p style="margin-left: 21px;text-align: justify;margin-top: 0px;">
    <?php echo ucwords(strtolower($data_state['st_address']));?>
    </p>
    </td>
    <td align="right" class="top_br"><strong>GSTN :</strong></td>
    <td align="right"><strong><?php echo $data_state['gst_no'];?></strong></td>
    </tr>
    <?php } ?>
  
</table>
<br />

<table width="100%" border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td width="5%"><strong>S. No.</strong></td>
    <td width="49%" align="center"><strong>Particulars</strong></td>
    <td width="16%" align="center"><strong>Month &amp; State</strong></td>
    <td width="12%" align="center"><strong>No. of Persons engaged</strong></td>
    <td width="18%" align="center"><strong>Amount</strong></td>
  </tr>
  <tr>
    <td class="but_br" style="text-align:center;">1</td>
    <td class="but_br">Workforce engaged </br>Service Accounting Code (SAC) <span style="float:right !important; display:block;"><strong>998513</strong></span></td>
    <td align="center" valign="top" rowspan="3"><?php echo $monthName;?> <?php echo $year;?> <br /><?php if($state=='ALL') {echo "PAN India";} else { echo $state;}?></td>
    <td align="right" valign="top" rowspan="3"><?php echo $j;?></td>
    <td class="but_br" align="right">&#8377; <?php echo round($service_amt  = ( (($total*117.10)/100)*103)/100, 2); ?></td>
  </tr>
  
  <tr>
    <td class="but_br" style="text-align:center;">2</td>
    <td class="but_br">
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td width="71%">IGST</td>
        <td width="10%">@</td>
        <td width="19%"><strong>18.00%</strong></td>
      </tr>
    </table>
    </td>
    <td class="but_br" align="right">&#8377; <?php echo round($final_amt = ($service_amt*18)/100,2); ?></td>
  </tr>
  
  <tr>
    <td style="text-align:center;">3</td>
    <td>Rounding-off figure</td>
    <td  align="right">&#8377; <?php $total_amt_final = round($service_amt,2)+ round($final_amt,2);$total_amt_round = round($total_amt_final)  ;echo round( ($total_amt_round-$total_amt_final),2)?></td>
  </tr> 
  <tr>
    <td colspan="3" style="text-align:center;"><strong>Total</strong></td>
    <td align="right"><?php echo $j;?></td>
    <td align="right">&#8377; <?php echo formatInIndianStyle(round($final_amt+$service_amt));?></td>
  </tr>
  <tr>
    <td colspan="5">RUPEES <strong><?php echo ucfirst(strtolower(get_word(round($final_amt+$service_amt))));?> ONLY</strong></td>
    
  </tr>
</table>
<br /><br />
<p><strong>For Rudraansh Holdings LLP</strong></p>
<img src="../../img/dipak_sign.png" width="200"/>
<p>Partner / Authorised Signatory</p>
</article>
</section>
</div>

</body>
</html>
