<?php
try {
    if (!isset($_REQUEST['datefrom'])) {
        header('location: ../invoice.php');
        exit;
    }

    $customer_name = $_GET['customer_name'];

    include_once('../../../classes/manager.class.php');
    include_once('../../../classes/PHPMailer/PHPMailerAutoload.php');
    include_once('../../../fpdf/fpdf1.php');

    $m = new Manager();
    extract($_REQUEST);
    $param_data = ControlConfifguration::GetConfiguration();
    define('PROJECT_NAME', $param_data->name);
    define('PROJECT_ADDRESS', $param_data->address);
    define('PROJECT_TEL', $param_data->contact);
    define('PROJECT_EMAIL', $param_data->email);
    define('PROJECT_WEBSITE', $param_data->website);
    define('PROJECT_COLOR', $param_data->color);
    define('PROJECT_DISCOUNT', $param_data->is_discount);
    define('PROJECT_TAX', $param_data->is_tax);

    $balanceAmount = 0;
    $totalCreditAmount = 0;
    $totalDebitAmount = 0;

    if ($datefrom == "") {
        $datefrom = date('Y-m-d', strtotime("-30 days"));
    } else {
        $datefrom = date("Y-m-d", strtotime($datefrom));
    }
    if ($dateto == "") {
        $dateto = date('Y-m-d');
    } else {
        $dateto = date("Y-m-d", strtotime($dateto));
    }
    $datefrom = date("d-m-Y", strtotime($datefrom));
    $dateto = date("d-m-Y", strtotime($dateto));

    $qryDate = date("Y-m-d", strtotime($datefrom));
    $qryTo = date("Y-m-d", strtotime($dateto));

    // Ledger Report Data
    $filterReport = "WHERE DATE_FORMAT(create_date, '%Y-%m-%d') >= '$qryDate' 
                    AND DATE_FORMAT(create_date, '%Y-%m-%d') <= '$qryTo'";

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

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

    if (!empty($reportData)) {
        $pdf = new FPDFWithOutWaterMark('L', 'mm', 'A4');
        $pdf->AddPage();
        $pdf->SetFont('Arial', 'B', 16);
        $pdf->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');
        $pdf->Ln(10);

        $pdf->SetFont('Arial', 'B', 14);
        $pdf->Cell(0, 6, 'Customer Type Ledger Report', 0, 0, 'C');
        $pdf->Ln(10);

        $pdf->SetFont('Arial', '', 10);
        $pdf->Cell(0, 4, 'From: ' . $datefrom . ' To: ' . $dateto, 0, 0, 'C');
        $pdf->Ln(8);

        $header = ['S.No', 'Head', 'Date', 'Reference Code', 'Customer', 'Status', 'Payment Type', 'Bank Name', 'CHQ Number', 'CHQ Date', 'Debit', 'Credit', 'Balance'];
        $widths = [12, 30, 20, 25, 50, 20, 25, 30, 25, 25, 20, 20, 20];

        // Draw Table Header
        $pdf->SetFont('Arial', 'B', 10);
        foreach ($header as $index => $title) {
            $pdf->Cell($widths[$index], 7, $title, 1, 0, 'C');
        }
        $pdf->Ln();

        // Data Section
        $pdf->SetFont('Arial', '', 9);
        $grandTotalDebit = $grandTotalCredit = $grandTotalBalance = 0;
        $counter = 1;

        foreach ($openingBalanceData as $ob) {
            $customerName = $ob->customer_name;
            $totalPayment = $ob->total_payment;
            $totalInvoice = $ob->total_invoice;
            $openingBalance = $ob->opening_balance;
            $runningBalance = $openingBalance;

            // Customer Name Header
            $pdf->SetFont('Arial', 'B', 10);
            $pdf->Cell(0, 7, $customerName, 1, 1, 'L');

            // Opening Balance Row
            $pdf->SetFont('Arial', '', 9);
            $pdf->Cell($widths[0], 6, $counter++, 1);
            $pdf->Cell($widths[1], 6, 'Opening Balance', 1);
            $pdf->Cell($widths[2], 6, '-', 1);
            $pdf->Cell($widths[3], 6, '-', 1);
            $pdf->Cell($widths[4], 6, $customerName, 1);
            $pdf->Cell($widths[5], 6, '-', 1);
            $pdf->Cell($widths[6], 6, '-', 1);
            $pdf->Cell($widths[7], 6, '-', 1);
            $pdf->Cell($widths[8], 6, '-', 1);
            $pdf->Cell($widths[9], 6, '-', 1);
            $pdf->Cell($widths[10], 6, $totalInvoice, 1);
            $pdf->Cell($widths[11], 6, $totalPayment, 1);
            $pdf->Cell($widths[12], 6, $openingBalance, 1);
            $pdf->Ln();

            $subtotalDebit = $totalInvoice;
            $subtotalCredit = $totalPayment;

            // Transactions
            foreach ($transactionData as $transaction) {
                if ($transaction->customer_id === $ob->customer_id) {
                    $debit = floatval($transaction->debit);
                    $credit = floatval($transaction->credit);
                    $runningBalance += (floatval($credit) - floatval($debit));

                    $subtotalDebit += floatval($debit);
                    $subtotalCredit += floatval($credit);

                    $pdf->Cell($widths[0], 6, $counter++, 1);
                    $pdf->Cell($widths[1], 6, $transaction->transaction_type, 1);
                    $pdf->Cell($widths[2], 6, $transaction->create_date, 1);
                    $pdf->Cell($widths[3], 6, $transaction->reference_code, 1);
                    $pdf->Cell($widths[4], 6, $customerName, 1);
                    $pdf->Cell($widths[5], 6, $transaction->status, 1);
                    $pdf->Cell($widths[6], 6, $transaction->payment_type, 1);
                    $pdf->Cell($widths[7], 6, $transaction->from_bank_name, 1);
                    $pdf->Cell($widths[8], 6, $transaction->cheque_number, 1);
                    $pdf->Cell($widths[9], 6, $transaction->cheque_date, 1);
                    $pdf->Cell($widths[10], 6, $debit, 1);
                    $pdf->Cell($widths[11], 6, $credit, 1);
                    $pdf->Cell($widths[12], 6, $runningBalance, 1);
                    $pdf->Ln();
                }
            }

            // Subtotal Row
            $pdf->SetFont('Arial', 'B', 10);
            $pdf->Cell(200, 7, "Subtotal for {$customerName}", 1, 0, 'R');
            $pdf->Cell(20, 7, $subtotalDebit, 1, 0, 'R');
            $pdf->Cell(20, 7, $subtotalCredit, 1, 0, 'R');
            $pdf->Cell(20, 7, $runningBalance, 1, 0, 'R');
            $pdf->Ln();

            $grandTotalDebit += $subtotalDebit;
            $grandTotalCredit += $subtotalCredit;
            $grandTotalBalance += $runningBalance;
        }

        // Grand Total Row
        $pdf->SetFont('Arial', 'B', 10);
        $pdf->Cell(200, 7, 'Grand Total', 1, 0, 'R');
        $pdf->Cell(20, 7, $grandTotalDebit, 1, 0, 'R');
        $pdf->Cell(20, 7, $grandTotalCredit, 1, 0, 'R');
        $pdf->Cell(20, 7, $grandTotalBalance, 1, 0, 'R');

        $pdf->Output();
        exit;
    }
} catch (Exception $e) {
    echo $e->getMessage();
}
?>
