<?php 

require('session.php');
require('pdf-generate/fpdf.php');
extract($_REQUEST);

$pdf = new FPDF();
$pdf->AddPage();


error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('magic_quotes_runtime', 0);

if(isset($_REQUEST['sel_customer']) && !empty($_REQUEST['sel_customer']) ){
	$customer_id = $_REQUEST['sel_customer'];
	$financial_id = $_REQUEST['financial_id'];
	$company_id = $_REQUEST['sel_company'];

	$customerRow = $db->get_rsltset("SELECT cus_id, cus_name,cus_city,cus_state,cus_gstno,cus_postcode FROM m_customer WHERE cus_id='" . $customer_id . "'");

				$companyRow = $db->get_rsltset("SELECT company_name FROM m_company WHERE company_id='" . $company_id . "'");
	// echo $company_id;
	// echo $financial_id;
	// echo $customer_id;
	$financial_query = "SELECT f_end_date, f_start_date FROM m_financial_year WHERE financial_id='" . $financial_id . "'";
	$financial_date = $db->get_rsltset($financial_query);

	$from_date = $financial_date[0]['f_start_date'];
    $to_date = $financial_date[0]['f_end_date'];

	$formatted_from_date = date("d-m-Y", strtotime($from_date));
	$formatted_to_date = date("d-m-Y", strtotime($to_date));

	$sales = $db->get_rsltset("SELECT * FROM t_sales_entry_main WHERE company_id='" . $company_id . "' AND cus_id='" . $customer_id . "' AND financial_id='" . $financial_id . "' AND IsActive=1 AND createddate BETWEEN '" . $from_date . "' AND '" . $to_date . "' ");
	// print_r($sales);
	$company_name = $companyRow[0]['company_name'];
	$customer_name = $customerRow[0]['cus_name'];
	
	 "<h1>Company: " . $companyRow[0]['company_name'] . "</h1>";
	 "<h2>Customer: " . $customerRow[0]['cus_name'] . "</h2>";
         "<h3>Financial Year: " . $formatted_from_date . " to " . $formatted_to_date . "</h3>";

		 $pdf->SetFont('Arial', 'B', 16);
		 $pdf->Cell(0, 10, 'Company: ' . $company_name, 0, 1);
		 
		 $pdf->SetFont('Arial', 'B', 14);
		 $pdf->Cell(0, 10, 'Customer: ' . $customer_name, 0, 1);
		 $pdf->SetFont('Arial', 'B', 12);
		 $pdf->Cell(0, 10, 'Financial Year: ' . $formatted_from_date . ' to ' . $formatted_to_date, 0, 1); 
		 $pdf->Ln(10);
		 

	
		$ledgerEntries = array();
$processedPaymentIds = array();

	if (!empty($sales)) {
		foreach ($sales as $row) {
			$s_bill_no = $row['s_bill_no'];
			$actu_bill_no = $row['actu_bill_no'];
			$query = "SELECT t1.*,  DATE_FORMAT(t1.s_bill_date, '%d-%b-%Y') AS disp_bill_date,
                    t2.company_name, t2.c_address, t2.c_city, t2.c_state, t2.c_country, t2.c_landline, t2.c_mobile,
                    t3.cus_name, t3.cus_address, t3.cus_city, t3.cus_state, t3.cus_country,
                    tr.return_date, tr.final_sale_amt as return_amt,
                    tp.createddate, tp.paid_amt,
                    tpm.payment_type as payment_type, tpm.ref_no as ref_no, tpm.less_amount as less_amount, tpm.id as p_id,
                    spt.payment_type as payment_type_name,
                    mf.financial_id, mf.f_start_date, mf.f_end_date,
                    (SELECT GROUP_CONCAT(t_payment_details.s_bill_no) FROM t_payment_main
                     INNER JOIN t_payment_details ON t_payment_main.id = t_payment_details.payment_id
                     WHERE t_payment_main.id = tpm.id) as bill_no,
                    (SELECT t_payment_main.received_amount FROM t_payment_main
                     WHERE t_payment_main.id = tpm.id) as received_amount,
                    (SELECT t_payment_main.less_amount FROM t_payment_main
                     WHERE t_payment_main.id = tpm.id) as payment_less_amount,
                    (SELECT t_payment_main.createddate FROM t_payment_main
                     WHERE t_payment_main.id = tpm.id) as payment_createddate
					 
                FROM t_sales_entry_main t1
                INNER JOIN m_company t2 ON t1.company_id = t2.company_id
                INNER JOIN m_customer t3 ON t1.cus_id = t3.cus_id
                LEFT JOIN t_return_entry_main tr ON t1.actu_bill_no = tr.actu_bill_no
                LEFT JOIN t_payment_details tp ON t1.actu_bill_no = tp.s_bill_no
                LEFT JOIN t_payment_main tpm ON tp.payment_id = tpm.id
                LEFT JOIN status_payment_type spt ON tpm.payment_type = spt.payment_type_id
                LEFT JOIN m_financial_year mf ON t1.financial_id = mf.financial_id
                WHERE t1.IsActive = 1
                AND t1.s_bill_no = '" . $s_bill_no . "' 
                ";



            $result = $db->get_rsltset($query);
			
			

            if ($result) {
                foreach ($result as $data) {
					
					if (!empty($data['createddate']) && !in_array($data['p_id'], $processedPaymentIds)) {

						$paymentReceivedPart = 'Payment Received  ' ;
						$ref_no = $data['ref_no'];
            			$commissionPart = 'Commission / Less ' ;

						$ledgerEntries[] = array(
							'date' => date('d-M-Y', strtotime($data['createddate'])),
							'bill_no' => $data['bill_no'],
							'particulars' => '',
							'particulars_payment_received' => $paymentReceivedPart,
							'ref_no' => $ref_no,
							'particulars_commission' => $commissionPart,
							'debit' => '',
							'debit_paid' => number_format($data['paid_amt'], 2) ,
							'debit_less' => number_format($data['payment_less_amount'], 2),
							'credit' => ''
						);
						// Add the processed payment ID to the array
						$processedPaymentIds[] = $data['p_id'];
					}
                    // Add ledger entry for sales
                    $ledgerEntries[] = array(
                        'date' => $data['disp_bill_date'],
                        'bill_no' => $data['actu_bill_no'],
                        'particulars' => 'Sales',
						'ref_no' => '',
						'particulars_payment_received' => '', // Empty for sales
            			'particulars_commission' => '', 
                        'debit' => '',
                        'debit_paid' => '',
                        'debit_less' => '',
                        'credit' => number_format($data['final_sale_amt'], 2),
                    );

                    // Add ledger entry for return, if applicable
                    if (!empty($data['return_date'])) {
                        $ledgerEntries[] = array(
                            'date' => date('d-M-Y', strtotime($data['return_date'])),
                            'bill_no' => $data['actu_bill_no'],
                            'particulars' => 'Return',
							'ref_no' => '',
							'particulars_payment_received' => '', // Empty for sales
            				'particulars_commission' => '', 
							'debit_paid' => '',
                        	'debit_less' => '',
                            'debit' => number_format($data['return_amt'], 2),
                            'credit' => ''
                        );
                    }

                    // Add ledger entry for payment, if applicable
                    
                }
				
				

            } else {
                 "No results found for sales entry details.";
            }

			$data = array();

        }

        // Sort ledger entries by date
        usort($ledgerEntries, function($a, $b) {
            return strtotime($a['date']) - strtotime($b['date']);
        });

		$totalDebit = 0;
		$totalCredit = 0;
		foreach ($ledgerEntries as $entry) {
			if (!empty($entry['debit'])) {
				$totalDebit += floatval(str_replace(',', '', $entry['debit'])); // Remove commas and convert to float
			}
			if (!empty($entry['credit'])) {
				$totalCredit += floatval(str_replace(',', '', $entry['credit'])); // Remove commas and convert to float
			}
		}
        // Display ledger entries
		$pdf->SetFont('Arial', 'B', 12);
    $pdf->Cell(30, 10, 'Date', 1);
    $pdf->Cell(30, 10, 'Bill No', 1);
    $pdf->Cell(50, 10, 'Particulars', 1);
    $pdf->Cell(30, 10, 'Debit', 1);
    $pdf->Cell(30, 10, 'Credit', 1);
    $pdf->Ln();
	$pdf->SetFont('Arial', 'B', 8);
	foreach ($ledgerEntries as $entry) {

		$lines = max(count(explode("\n", $entry['particulars_payment_received'])), count(explode("\n", $entry['particulars_commission'])));

		// Calculate the height of the MultiCell based on the number of lines
		$lineHeight = 10; // Adjust as needed
		$particularsHeight = $lines * $lineHeight;

        $pdf->Cell(30, 10, $entry['date'], 1);
        $pdf->Cell(30, 10, $entry['bill_no'], 1);

		// $pdf->Cell(50, 10, '', 1);
		  if (!empty($entry['particulars_payment_received'])) {
        // Add MultiCell for "Particulars" with two lines
        $pdf->MultiCell(50, $lineHeight, $entry['particulars_payment_received']."\n" .$entry['ref_no'], 1);
        // $pdf->Cell(50, $lineHeight, $entry['particulars_commission'], 1);

        // Calculate the height of the Debit cell
        // $debitHeight = max($particularsHeight, 10); // Minimum height of 10
        // $pdf->MultiCell(30, $debitHeight, $entry['debit'], 1);
    } else {
        $pdf->Cell(50, $lineHeight, $entry['particulars'], 1);
        $pdf->Cell(30, $particularsHeight, $entry['debit'], 1);
    }

        $pdf->Cell(30, 10, $entry['credit'], 1);
        $pdf->Ln();
    }
	$pdf->SetFont('Arial', 'B', 10);
    $pdf->Cell(110, 10, 'Total:', 1);
    $pdf->Cell(30, 10, number_format($totalDebit, 2), 1);
    $pdf->Cell(30, 10, number_format($totalCredit, 2), 1);
    $pdf->Ln();

	$closingBalance =  $totalDebit - $totalCredit ;
	$pdf->Cell(110, 10, 'Closing Balance:', 1);
	
	if ($closingBalance < 0) {
		// Display in "Credit" column
		$pdf->Cell(30, 10, '', 1); 
		$pdf->Cell(30, 10, number_format(abs($closingBalance), 2), 1);
		
	} elseif ($closingBalance > 0) {
		// Display in "Debit" column
		$pdf->Cell(30, 10, number_format(abs($closingBalance), 2), 1);
		$pdf->Cell(30, 10, '', 1); 
		
	} else {
		// Display as-is (empty cells)
		$pdf->Cell(30, 10, '', 1);
		$pdf->Cell(30, 10, '', 1);
		
	}
	$pdf->Ln();
	
	$pdf->Output('output.pdf', 'I');
	
        //  "<table>";
        //  "<tr><th>Date</th><th>Bill No</th><th>Particulars</th><th>Debit</th><th>Credit</th></tr>";
        // foreach ($ledgerEntries as $entry) {

        //      "<tr>";
        //      "<td>" . $entry['date'] . "</td>";
        //      "<td>" . $entry['bill_no'] . "</td>";
        //      "<td>" . $entry['particulars'] . "</td>";
        //      "<td>" . $entry['debit'] . "</td>";
        //      "<td>" . $entry['credit'] . "</td>";
        //      "</tr>";

        // }

		// 	 "<tr>";
		// 	 "<td colspan='3'><strong>Total:</strong></td>";
		// 	 "<td><strong>" . number_format($totalDebit, 2) . "</strong></td>";
		// 	 "<td><strong>" . number_format($totalCredit, 2) . "</strong></td>";
		// 	 "</tr>";
		// 	$closingBalance = $totalDebit - $totalCredit;
		// 	 "<tr></br></br></tr>";
			
		// 	 "<tr>";
		// 	 "<td colspan='3'><strong>Closing Balance:</strong></td>";
		// 	if ($closingBalance < 0) {
		// 		// If closing balance is negative, it's a credit balance
		// 		 "<td><strong>" . number_format(abs($closingBalance), 2) . "</strong></td>";
		// 		 "<td><strong>Credit</strong></td>";
		// 	} elseif ($closingBalance > 0) {
		// 		// If closing balance is positive, it's a debit balance
		// 		 "<td><strong>" . number_format($closingBalance, 2) . "</strong></td>";
		// 		 "<td><strong>Debit</strong></td>";
		// 	} else {
		// 		// If closing balance is zero, display as-is
		// 		 "<td><strong>0.00</strong></td>";
		// 		 "<td><strong></strong></td>";
		// 	}
			
		// 	 "</tr>";
			
		//  "</tr>";
        //  "</table>";
    } else {
		 "No results found.";
	}
	
	
	
	
}



// function getAmountInWords($no) {   
	
// 	//creating array  of word for each digit
// 	 $words = array('0'=> 'Zero' ,'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' => 'ninty','100' => 'hundred','1000' => 'thousand','100000' => 'lac','10000000' => 'crore');
// 	 //$words = array('0'=> '0' ,'1'=> '1' ,'2'=> '2' ,'3' => '3','4' => '4','5' => '5','6' => '6','7' => '7','8' => '8','9' => '9','10' => '10','11' => '11','12' => '12','13' => '13','14' => '14','15' => '15','16' => '16','17' => '17','18' => '18','19' => '19','20' => '20','30' => '30','40' => '40','50' => '50','60' => '60','70' => '70','80' => '80','90' => '90','100' => '100','1000' => '1000','100000' => '100000','10000000' => '10000000');
	 
	 
// 	 //for decimal number taking decimal part
	 
// 	$cash=(int)$no;  //take number wihout decimal
// 	$decpart = $no - $cash; //get decimal part of number
	
// 	$decpart=sprintf("%01.2f",$decpart); //take only two digit after decimal
	
// 	$decpart1=substr($decpart,2,1); //take first digit after decimal
// 	$decpart2=substr($decpart,3,1);   //take second digit after decimal  
	
// 	$decimalstr='';
	
// 	//if given no. is decimal than  preparing string for decimal digit's word
	
// 	if($decpart>0)
// 	{
// 	 $decimalstr.="point ".$numbers[$decpart1]." ".$numbers[$decpart2];
// 	}
	 
// 	if($no == 0)
// 		return ' ';
// 	else {
// 		$novalue='';
// 		$highno=$no;
// 		$remainno=0;
// 		$value=100;
// 		$value1=1000;       
// 		while($no>=100)    {
// 			if(($value <= $no) &&($no  < $value1))    {
// 			$novalue=$words["$value"];
// 			$highno = (int)($no/$value);
// 			$remainno = $no % $value;
// 			break;
// 			}
// 			$value= $value1;
// 			$value1 = $value * 100;
// 		}       
// 		if(array_key_exists("$highno",$words))  //check if $high value is in $words array
// 			return $words["$highno"]." ".$novalue." ".getAmountInWords($remainno).$decimalstr;  //recursion
// 		else {
// 			$unit=$highno%10;
// 			$ten =(int)($highno/10)*10;
// 			return $words["$ten"]." ".$words["$unit"]." ".$novalue." ".getAmountInWords($remainno
// 			).$decimalstr; //recursion
// 		}
// 	}
// }

// $pdf = new FPDF();
// $pdf->AddPage();
// $dir_path = $_SERVER['DOCUMENT_ROOT'].'/hmbeta/';
// //$pdf->Image($dir_path.'pdf-generate/receipt-copy.jpg','','',-310);

// $pdf->SetFont('Arial','B',11);
// //Bill No
// $pdf->SetXY(46, 10);
// $pdf->Cell(0,0,$actu_bill_no);

// //Bill Date
// $pdf->SetXY(182, 21);
// $pdf->Cell(0,0,date('d-m-Y',strtotime($sales['s_bill_date'])));

// $pdf->SetFont('Arial','B',10);
// //Customer Details
// //1, Name
// $pdf->SetXY(30, 60);
// $pdf->Cell(0,0,'M/S. '.$sales['cus_name']);
// //2,Address
// $pdf->SetXY(30, 65);
// $pdf->Cell(0,0,$sales['cus_address']);
// //3,Postal Code
// $pdf->SetXY(30, 75);
// $pdf->Cell(0,0,$sales['cus_postcode']);
// //4,City
// $pdf->SetXY(30, 70);
// $pdf->Cell(0,0,$sales['cus_city']);
// //5,State
// $pdf->SetXY(30, 80);
// $pdf->Cell(0,0,$sales['cus_state']);
// //5,GST NO
// $pdf->SetXY(30, 85);
// $pdf->Cell(0,0,'GST No: '.$sales['cus_gstno']);


// //Order Line Details 
// $line_height = 106;
// $increase_left = 4;
// $i=1;
// $pdf->SetFont('Arial','B',8);
// foreach($rslt_pdt_det as $r){
// 	$sku_code = mt_rand(100000,999999);
// 	//Line 1#detail
// 	$pdf->SetXY(28+$increase_left, $line_height);
// 	$pdf->Cell(0,0,$i);
// 	$pdf->SetXY(35+$increase_left, $line_height);
// 	$pdf->Cell(0,0,$r['pdt_sku']);
// 	$pdf->SetXY(55+$increase_left, $line_height);
// 	$pdf->Cell(0,0,substr($r['saree_desc'],0,55));
// 	$pdf->SetXY(155+$increase_left, $line_height);
// 	$pdf->Cell(0,0,'1');
// 	$pdf->SetXY(175+$increase_left, $line_height);
// 	$pdf->Cell(0,0,$r['tot_amount']);
// 	$pdf->SetXY(198+$increase_left, $line_height);
// 	$pdf->Cell(0,0,'-');
// 	$line_height += 6;
// 	$i++;
// }

// //Total Display
// //Total
// $pdf->SetXY(180, 210);
// $pdf->Cell(0,0,$rslt_main_det['total_sale_amount']);

// //Less
// $pdf->SetXY(180, 216);
// $pdf->Cell(0,0,($rslt_main_det['total_sale_amount'] - $rslt_main_det['after_discount_amt']));

// //Less Percent
// //Less (1%)
// $pdf->SetXY(146, 216);
// $pdf->Cell(0,0,'('.$rslt_main_det['discount_per'].'%)');

// //Taxable Amount
// $pdf->SetXY(180, 222);
// $pdf->Cell(0,0,$rslt_main_det['after_discount_amt']);

// //GST Calculation
// $cgst_per = ($rslt_main_det['igst_per']==0)?$rslt_main_det['cgst_total']:'-';
// $sgst_per = ($rslt_main_det['igst_per']==0)?$rslt_main_det['sgst_total']:'-';
// $igst_per = ($rslt_main_det['igst_per']!=0)?$rslt_main_det['igst_total']:'-';

// //if($rslt_main_det['igst_per']==0) {
// 	//CGST
// 	$pdf->SetXY(180, 229);
// 	$pdf->Cell(0,0,$cgst_per);
// 	//SGST
// 	$pdf->SetXY(180, 235);
// 	$pdf->Cell(0,0,$sgst_per);
// //}
// //if($rslt_main_det['igst_per']!=0) {
// 	//IGST
// 	$pdf->SetXY(180, 241);
// 	$pdf->Cell(0,0,$igst_per);
// //}
// //GRAND Total
// $pdf->SetFont('Arial','B',11);
// $pdf->SetXY(180, 250);
// $pdf->Cell(0,0,$rslt_main_det['final_sale_amt']);

// $pdf->SetFont('Arial','B',8);
// //Notes
// $pdf->SetXY(45, 260);
// $pdf->Cell(0,0,$rslt_main_det['notes']);

// //GRAND Total in words
// $pdf->SetFont('Arial','B',9);
// $pdf->SetXY(57, 249);
// $pdf->Cell(0,0,':'.ucfirst(getAmountInWords($rslt_main_det['final_sale_amt'])).' only.');
// $pdf->Output('I');
?>
<!-- <script language="javascript">
window.print();
</script> -->
