<?php
ob_start();
session_start();
include "config/config.php";
include "config/session.php";

if(!isset($session)) {
		header('location: login.php'); 
		exit;
}



$statement_users = $pdo->prepare("SELECT * FROM  tbl_users WHERE tbl_users.id=?");
$statement_users->execute(array($session_id));
$user_datas = $statement_users->fetchAll(PDO::FETCH_ASSOC);
$session_user_name = $user_datas[0]['name'];
$current_date_time = date("d/m/Y h:i:s A");


function daysToMonths($days) {
    $averageDaysInMonth = 365 / 12; // approximately 30.44
    $months = $days / $averageDaysInMonth;
    return round($months); // Round to the nearest whole number
}




$ids = $_GET['id'];
$statement = $pdo->prepare("SELECT ad.*,
c.customer_name, c.mobile_no,
c.address, c.state,
c.nominee_name, c.nominee_mobile_no, c.nominee_address, c.nominee_type,
tbl_ids_purity.short_name,
tbl_ids_products.name as ids_product_name,
(SELECT COALESCE(SUM(amount),0) FROM tbl_payments WHERE tbl_payments.advance_id=ad.id) as Paid_Advance_amount,
sp.name as sales_person_name
FROM `tbl_advance_voucher` ad 
LEFT JOIN tbl_customers c ON c.id=ad.customer_id
LEFT JOIN tbl_ids_purity ON tbl_ids_purity.id=ad.purity
LEFT JOIN tbl_ids_products ON tbl_ids_products.id=ad.product_ids 
LEFT JOIN tbl_users sp ON sp.id=ad.created_user_id
WHERE ad.id=?");
$statement->execute(array($ids));
$datas = $statement->fetchAll(PDO::FETCH_ASSOC);
$totalData = $statement->rowCount();
if($totalData>0){
    
    $advance_no = $datas[0]['advance_no'];
    $advance_date = date('d/m/Y', strtotime($datas[0]['date']));
    $expected_date = date('d/m/Y', strtotime($datas[0]['expected_date']));
    $customer_name = $datas[0]['customer_name'];
    $customer_address = $datas[0]['address'];
    $mobile_no = $datas[0]['mobile_no'];
    $net_advance = $datas[0]['advance_amount'];
    $remarks = $datas[0]['remarks'];
    
    
$days = $datas[0]['validity_days'];
$months = daysToMonths($days);
    
$statement_payments = $pdo->prepare("SELECT tbl_payments.*,
tbl_payment_type.name as payment_type_name
FROM `tbl_payments` 
LEFT JOIN tbl_payment_type ON tbl_payment_type.id=tbl_payments.payment_type
WHERE tbl_payments.advance_id=?");
$statement_payments->execute(array($ids));
$payments_datas = $statement_payments->fetchAll(PDO::FETCH_ASSOC);
$payments_totalData = $statement_payments->rowCount();


    
$statement_items = $pdo->prepare("SELECT * FROM tbl_sale_items e WHERE e.sale_id=?");
$statement_items->execute(array($ids));
$items_datas = $statement_items->fetchAll(PDO::FETCH_ASSOC);
$items_totalData = $statement_items->rowCount();



$statement_locations = $pdo->prepare("SELECT * FROM tbl_business_branch b WHERE b.id=?");
$statement_locations->execute(array($datas[0]['location_id']));
$business_locations_datas = $statement_locations->fetchAll(PDO::FETCH_ASSOC);
$business_loations_totalData = $statement_locations->rowCount();

if($business_loations_totalData>0){
    $business_name = $business_locations_datas[0]['business_name'];
}

        $statement_price = $pdo->prepare("SELECT tbl_prices.* FROM `tbl_prices` WHERE tbl_prices.product_id=?");
		$statement_price->execute(array($product_ids));
		$price_data = $statement_price->fetchAll(PDO::FETCH_ASSOC);
        
        
        if($price_data[0]['product_id'] == 1){
            
            $statement_gold_price = $pdo->prepare("SELECT tbl_prices.* FROM `tbl_prices` WHERE tbl_prices.product_id=? AND tbl_prices.purity_id=?");
    		$statement_gold_price->execute(array($product_ids,2));
    		$gold_price_data = $statement_gold_price->fetchAll(PDO::FETCH_ASSOC);
		
		    $gold_rate = $gold_price_data[0]['amount'];
          
        }else{
            $gold_rate = $price_data[0]['amount'];
        }
        
        $product_ids = $datas[0]['product_ids'];
        $advance_type = $datas[0]['type'];
    
        if($product_ids == 1){
            $product_item = 'Gold';
            $product_wt = 'GW';
        }elseif($product_ids == 2){
            $product_item = 'DIAMOND';
            $product_wt = 'DW';
        }elseif($product_ids == 3){
            $product_item = 'SILVER';
            $product_wt = 'SW';
        }elseif($product_ids == 4){
            $product_item = 'PRECIOUS';
            $product_wt = 'PW';
        }
        
        if($advance_type == 1){
            $advance_item = 'Order';
        }elseif($advance_type == 2){
            $advance_item = 'Stock';
        }

?>

<?php
   $number = $net_advance;
   $no = floor($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) ? '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;
  }
  $str = array_reverse($str);
  $result = implode('', $str);
  $points = ($point) ?
    "." . $words[$point / 10] . " " . 
          $words[$point = $point % 10] : '';
  $amount_in_words =  $result . "Rupees Only";
?>


<p>Duplicate For Recipient</p>
<table style="width:100%;border-collapse: collapse;">
	<tr style="border-top: 1px solid black;">
		<td style="border-top: 1px solid black;padding:3px">
			<center><b style="font-family: system-ui;">ADVANCE RECEIPT VOUCHER</b></center>
		</td>
	</tr>
	<tr style="border-bottom: 1px solid black;">
		<td style="border-bottom: 1px solid black;padding:3px">
			<center>
			    <span style="font-size: 12px;">
			    Section 31(3)(d) and Rule 50 of CGST Act and Rules.2017
			    </span>
			</center>
		</td>
	</tr>
</table>
<table style="width: 100%;border-collapse: collapse;">
	<tr style="border-bottom: 1px solid black;">
		<td style="border-bottom: 1px solid black;width: 60%;font-size: 11px;">
			<table>
				<tr>
					<td style="width:30%;" class="titless">Billed To</td>
					<td style="width:2%;"  class="colon">:</td>
					<td style="width:68%;" class="valuess"><?=$customer_name?></td>
				</tr>
				<tr>
					<td class="titless">Address</td>
					<td class="colon">:</td>
					<td class="valuess"><?=nl2br($customer_address)?></td>
				</tr>
				<tr>
					<td class="titless">Mobile</td>
					<td class="colon">:</td>
					<td class="valuess"><?=$mobile_no?></td>
				</tr>
				<tr>
					<td class="titless">State</td>
					<td class="colon">:</td>
					<td class="valuess"><?=$datas[0]['state']?></td>
				</tr>
				
				<!--<tr>
					<td class="titless">ST</td>
					<td class="colon">:</td>
					<td class="valuess">33</td>
				</tr>-->
				<tr>
					<td class="titless">Nominee Name</td>
					<td class="colon">:</td>
					<td class="valuess"><?=$datas[0]['nominee_name']?></td>
				</tr>
				<tr>
					<td class="titless">Nominee Phone</td>
					<td class="colon">:</td>
					<td class="valuess"><?=$datas[0]['nominee_mobile_no']?></td>
				</tr>
				<tr>
					<td class="titless">Nominee Address</td>
					<td class="colon">:</td>
					<td class="valuess"><?=$datas[0]['nominee_address']?></td>
				</tr>
				
				<tr>
					<td class="titless">Relation With Nominee</td>
					<td class="colon">:</td>
					<td class="valuess"><?=$datas[0]['nominee_type']?></td>
				</tr>
				

			</table>
		</td>
		<td style="border-bottom: 1px solid black; border-left: 1px solid black;vertical-align: top;width: 40%;font-size: 11px;">
			<span x>
			<table style="width:100%;vertical-align: top;">
				<tr>
					<td style="width:40%;" class="titless">Receipt ID</td>
					<td style="width:2%;" class="colon">:</td>
					<td style="width:58%;" class="valuess"><?=$advance_no?></td>
				</tr>
				<tr>
					<td class="titless">Advance No</td>
					<td class="colon">:</td>
					<td class="valuess"><?=$advance_no?></td>
				</tr>
				<tr>
					<td class="titless">Advance Date</td>
					<td class="colon">:</td>
					<td class="valuess"><?=$advance_date?></td>
				</tr>
				<tr>
					<td class="titless">Expected Purchase Date</td>
					<td class="colon">:</td>
					<td class="valuess"><?=$expected_date?></td>
				</tr>
				<!--<tr>
					<td>Suplier GSTIN</td>
					<td>:</td>
					<td>33AAICA7468H1ZH</td>
				</tr>-->
				<tr>
					<td class="titless">Currency</td>
					<td class="colon">:</td>
					<td class="valuess">INR</td>
				</tr>
				<tr>
					<td class="titless">Max <?=$product_item?> Rate</td>
					<td class="colon">:</td>
					<td class="valuess"><?=number_format($datas[0]['per_gram_amount'],2)?></td>
				</tr>
				<tr>
					<td class="titless">Place of Supply</td>
					<td class="colon">:</td>
					<td class="valuess">Tamil Nadu</td>
				</tr>
				<!--<tr>
					<td>Tax is payable On Reverse Charge</td>
					<td>:</td>
					<td>No</td>
				</tr>-->
				<tr>
					<td class="titless">Purity</td>
					<td class="colon">:</td>
					<td class="valuess"><?=$datas[0]['short_name']?></td>
				</tr>
			</table>
		</span>
			
		</td>
	</tr>
</table>
<br>

<table style="width: 100%; border-collapse: collapse;border: 1px solid black;border-left:none !important;border-right: none !important;font-size: 11px;">
	<tr>
		<td style="border-left: none !important;border: 1px solid black;width: 60%;text-align: right;" class="titles">
			Advance Received
		</td>
		<td style="border: 1px solid black;border-right: none !important;width: 40%;text-align: right;" class="titles">
			Net Advance
		</td>
	</tr>
	<tr>
		<td style="border-left: none !important;border: 1px solid black;width: 60%;text-align: right;" class="values">
			<?=number_format($datas[0]['Paid_Advance_amount'], 2)?>
		</td>
		<td style="border: 1px solid black;border-right: none !important;width: 40%;text-align: right;" class="values">
			<?=number_format($net_advance, 2)?>
		</td>
	</tr>
</table>
<p style="font-size: 11px;">(<?=$amount_in_words?>)</p>
<table style="width: 100%; font-size:11px;">
	<tr>
		<td>
			<table>
				<tr>
					<td style="font-size: 11px;">Towards the advance against purchase of approximate <?=number_format($datas[0]['advance_weight'],2)?> GM</td>
					
				</tr>
				
				<tr>
					<td style="font-size: 11px;">Validity &nbsp; &nbsp; <?=$months?> months &nbsp;&nbsp; (<?=$datas[0]['validity_days']?>) Days &nbsp; &nbsp; Offer Expire Date (<?=$expected_date?>)</td>
					
				</tr>
				<tr>
					<td style="font-size: 11px;">Max <?=$product_item?> rate per gram : <?=number_format($datas[0]['per_gram_amount'],2)?></td>
					
				</tr>
				<tr>
					<td style="font-size: 11px;">Deposit Type : <?=$advance_item?> Advance </td>
				</tr>
			</table>
		</td>
		
		<td >
			<table>
				<tr>
					<td><?=$datas[0]['ids_product_name']?> (HSN Code:7113)</td>
					
				</tr>
				<tr>
					<td><b>Payment Mode:</b></td>
                </tr>
            <?php if($payments_totalData>0){
                foreach($payments_datas as $payments){
            ?>
				<tr>
					<td><?=$payments['payment_type_name']?>/Received      : <?=number_format($payments['amount'],2)?></td>
				</tr>
			<?php }  } ?>
			</table>
		</td>
	</tr>
</table>
<p style="font-size: 11px;"><b>Order Details:</b></p>
<p style="font-size: 11px;"><b>Item 1:</b> GST_ORDER, <?=$product_wt?>: <?=number_format($datas[0]['per_gram_amount'],2)?> Unit, Amount: <?=number_format($datas[0]['total_amount'],2)?>, Package:</p>
<p style="font-size: 11px;"><b>Remarks:</b> <?=$remarks?></p>
<hr>
<p style="font-size: 11px;"><b>Terms And Conditions:</b></p>
<p style="font-size: 11px;">Gold rate on the date of order or on the date of purchase which ever is less will be applicable subject to the following conditions of advance payment.</p>

<!--<table style="width: 100%;">
    <tr>
        <td style="width: 1%;"><p class="p10">1.</p></td>
        <td style="width: 99%;"><p class="p10">Original receipt should be produced at the time of purchase.</p></td>
    </tr>
</table>-->
<!--<p style="font-size: 10px;">-->
<!--    <br>1. Original receipt should be produced at the time of purchase.-->
<!--    <br>2. Advance is not transferable.-->
<!--    <br>3. Cash refund is not admissible.-->
<!--    <br>4. This scheme is for purchase of ornaments only, not applicable for gold coins or gold bars.-->
<!--    <br>5. Gold rate of the date of advance payment will be applicable for purchase, if the advance is made by way old gold exchange / sales return.-->
<!--    <br>6. If the purchase is not made within the stipulated period of the scheme, benefit of lower gold rate will be applicable only for the gold weight equivalent to the amount advanced.-->
<!--    <br>7. The quantity of gold for which advance is made should be purchased.-->
<!--    <br>8. The jewellery purchase under these advance system will be subject to making charges and all applicable goverment taxes.-->
<!--    <br>9. Change in government tax rules will be applicable accordingly.-->
<!--    <br>10. Making charge will be calculated based on the billing day's gold rate and it should be paid at the time of purchase.-->
<!--    <br>11. Cheque payments are subject to realisation.<br>&nbsp Final billing gold rate would be this max gold rate or purchase day gold rate(which ever is lower) -->
<!--</p>-->
<p style="font-size: 10px;">
    I acknowledge all the terms and conditions of this advance
</p>
<br><br>


<p5 style="padding-left: 55%; font-size: 11px;"><b>FOR <?=$business_name?></b><p5><br>
<p5 style="padding-left: 55%;font-size: 11px;"><b>Authorised Signatory</b><p5><br>
<p6 style="font-size: 11px;"><b>Customer Signature</b></p6><br><br>
<p5 style="padding-left: 55%;font-size: 11px;">Sales Person: <?=$datas[0]['sales_person_name']?><p5><br>
<p5 style="padding-left: 55%;font-size: 11px;">Generated by: <?=$session_user_name?>,<p5><br>
<p5 style="padding-left: 55%;font-size: 11px;">Print date : <?=$current_date_time?><p5>






<?php } ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" ></script>
<script>
    window.print(); 
    setTimeout(function(){window.close();},1000);
</script>

<style>
    .p10{
        font-size: 10px;
    }
	.titles{
	    font-size: 10px;
	    font-weight: 600;
	    color: black;
	    vertical-align: top;
	}
	.values{
	    font-size: 10px;
	    font-weight: 600;
	    color: black;
	    vertical-align: top;
	}
	.titless{
	    font-size: 10px;
	    font-weight: 600;
	    color: black;
	    vertical-align: top;
	}
	.valuess{
	    font-size: 10px;
	    font-weight: 600;
	    color: black;
	    vertical-align: top;
	}
	.colon{
	    font-size: 10px;
	    font-weight: 600;
	    color: black;
	    vertical-align: top;
	}
</style>