<?php
include('../../../classes/manager.class.php');
include('../../../classes/PHPMailer/PHPMailerAutoload.php');
include('../../../fpdf/fpdf1.php');

$m = new Manager();

// Parameters
//$fromDate = isset($_GET['fromDate']) ? $_GET['fromDate'] : date('d-m-Y', strtotime('-1 month'));
//$toDate = isset($_GET['toDate']) ? $_GET['toDate'] : date('d-m-Y');
$fromDate = isset($_GET['datefrom']) ? $_GET['datefrom'] : date('d-m-Y', strtotime('-1 month'));
$toDate = isset($_GET['dateto']) ? $_GET['dateto'] : date('d-m-Y');


$cat_type = isset($_GET['cat_type']) ? $_GET['cat_type'] : 'All';
error_log(print_r('$cat_type : '.$cat_type, true));

//$customerType = isset($_GET['customerType']) ? $_GET['customerType'] : 'All';




$qryDate = date("Y-m-d", strtotime($fromDate));
$qryTo = date("Y-m-d", strtotime($toDate));




$catType = "";
//$cat_type = "";

if (isset($cat_type) && $cat_type == 'All') 

{
   // if (isset($cat_name) && $cat_name != 'All') 
   // {
       $cat_name= 'All';
        $cat = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
        $filterCat = " WHERE category_id = '$cat->id'";
        $cust = CustomerSetup::GetCustomerSetupList($filterCat);
        $custArray = array();
        foreach ($cust AS $custRow) 
        {
            $custArray[] = $custRow->id;
        }
        $customers = implode(',', $custArray);
        $catType .= " AND inv.customer_id IN ($customers)";
   
//}
} else 

{
    $catType .= " AND cs.is_mart = '$cat_type'";
}

error_log(print_r('$catType = '.$catType, true));
error_log(print_r('$cat_name = '.$cat_name, true));
error_log(print_r('$cat = '.$cat, true));

/*if ($customerType == 'All') {
    if (isset($cat_name) && $cat_name != 'All') {
        $cat = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
        $filterCat = " WHERE category_id = '$cat->id'";
        $cust = CustomerSetup::GetCustomerSetupList($filterCat);
        
        $custArray = array();
        foreach ($cust as $custRow) {
            $custArray[] = $custRow->id;
        }
        $customers = implode(',', $custArray);
        $catType .= " AND inv.customer_id IN ($customers)";
    }
} else {
    $catType .= " AND cs.is_mart = '$customerType'";
}
*/
// Fetch Ledger Report Data

$reportData = Invoice::getLedgerReport($qryDate, $qryTo, $catType);

$openingBalanceData = $reportData['opening_balance'] ?? [];
$transactionData = $reportData['transactions'] ?? [];

//error_log(print_r($reportData, true));
//error_log(print_r($transactionData, true));


class PDF extends FPDF {
    function Header() {
        $this->SetFont('Arial', 'B', 12);
        $this->Cell(0, 10, 'Ledger Report', 0, 1, 'C');
        $this->Ln(5);
    }

    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
    }
}

//$pdf = new PDF();
//$pdf = new FPDFWithOutWaterMark('L', 'mm', 'A4');
$pdf = new PDF('L', 'mm', 'A4');

$pdf->AddPage();
$pdf->SetFont('Arial', '', 8);

$pdf->Cell(40, 10, 'Date: ' . date('d-m-Y'));
$pdf->Ln(10);

if (empty($transactionData)) {
    $pdf->Cell(0, 10, 'No data found!', 1, 1, 'C');
} else {
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->Cell(8, 10, 'S.No.', 1);
    $pdf->Cell(15, 10, 'Head', 1);
    $pdf->Cell(18, 10, 'Date', 1);
    $pdf->Cell(25, 10, 'Reference Code', 1);
    $pdf->Cell(50, 10, 'Customer', 1);
    $pdf->Cell(12, 10, 'Status', 1);
    $pdf->Cell(22, 10, 'Payment Type', 1);
    $pdf->Cell(20, 10, 'Bank Name', 1);
    $pdf->Cell(20, 10, 'CHQ Number', 1);
    $pdf->Cell(30, 10, 'CHQ Date', 1);
    $pdf->Cell(20, 10, 'Debit', 1);
    $pdf->Cell(20, 10, 'Credit', 1);
    $pdf->Cell(20, 10, 'Balance', 1);
    $pdf->Ln();
  
    $pdf->SetFont('Arial', '', 8);
    
    $grandTotalDebit = 0;
    $grandTotalCredit = 0;
    $currentCustomer = '';
    $balance = 0;
    $totalDebit = 0;
    $totalCredit = 0;
	$counter = 1;
    foreach ($transactionData as $row) {
        if ($currentCustomer != $row->customer_name) {
            if ($currentCustomer != '') {
                // Previous customer subtotal
                $pdf->SetFont('Arial', 'B', 8);
                $pdf->Cell(220, 10, 'Subtotal', 1);
                $pdf->Cell(20, 10, number_format($totalDebit, 2), 1, 0, 'R');
                $pdf->Cell(20, 10, number_format($totalCredit, 2), 1, 0, 'R');
                $pdf->Cell(20, 10, number_format($balance, 2), 1, 0, 'R');
                $pdf->Ln();
                $pdf->SetFont('Arial', '', 8);
            }

            // New customer header
            $currentCustomer = $row->customer_name;
            $pdf->Cell(280, 10, 'Customer: ' . $currentCustomer, 1, 1, 'L');

            // Fetch and display opening balance
            $openingBalance = $openingBalanceData[$currentCustomer] ?? 0;
            $pdf->Cell(240, 10, 'Opening Balance', 1);
            $pdf->Cell(20, 10, '', 1);
            $pdf->Cell(20, 10, number_format($openingBalance, 2), 1, 0, 'R');
          
            $pdf->Ln();
            
            // Reset totals for this customer
            $totalDebit = 0;
            $totalCredit = 0;
            $balance = $openingBalance;
        }

        // Transaction data (Fixed Object Access)
        $pdf->Cell(8, 10, $counter, 1);
        $pdf->Cell(15, 10, $row->transaction_type, 1);
        $pdf->Cell(18, 10, date('d-m-Y', strtotime($row->create_date)), 1);
        $pdf->Cell(25, 10, $row->reference_code , 1);
        $pdf->Cell(50, 10, $row->customer_name, 1);
        $pdf->Cell(12, 10, $row->status, 1);
        $pdf->Cell(22, 10, $row->payment_type, 1);
        $pdf->Cell(20, 10, $row->from_bank_name, 1);
        $pdf->Cell(20, 10, $row->cheque_number, 1);
        $pdf->Cell(30, 10, $row->cheque_date, 1);
        $pdf->Cell(20, 10, number_format($row->debit, 2), 1, 0, 'R');
        $pdf->Cell(20, 10, number_format($row->credit, 2), 1, 0, 'R');

        // Update balance
        $balance += $row->debit - $row->credit;
        $pdf->Cell(20, 10, number_format($balance, 2), 1, 0, 'R');
        $pdf->Ln();
		
        $totalDebit += $row->debit;
        $totalCredit += $row->credit;
        $grandTotalDebit += $row->debit;
        $grandTotalCredit += $row->credit;
    }

    // Last Customer Subtotal
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->Cell(220, 10, 'Subtotal', 1);
    $pdf->Cell(20, 10, number_format($totalDebit, 2), 1, 0, 'R');
    $pdf->Cell(20, 10, number_format($totalCredit, 2), 1, 0, 'R');
    $pdf->Cell(20, 10, number_format($balance, 2), 1, 0, 'R');
    $pdf->Ln();

    // Grand Total
    $pdf->Cell(220, 10, 'Grand Total', 1);
    $pdf->Cell(20, 10, number_format($grandTotalDebit, 2), 1, 0, 'R');
    $pdf->Cell(20, 10, number_format($grandTotalCredit, 2), 1, 0, 'R');
    $pdf->Cell(20, 10, number_format($balance, 2), 1, 0, 'R');
}

$pdf->Output();


?>
