<?php
include_once('../../../classes/manager.class.php');
include_once('../../../classes/PHPMailer/PHPMailerAutoload.php');
include_once('../../../fpdf/fpdfreportlogoL.php');

$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$customer_name = "";
$product_id = "";
$totalDiscount = 0;
$productQtyTotal = 0;
$costPriceTotal = 0;
$unitPriceTotal = 0;
$totalProfit = 0;
$mainCat = "";
$catName = "";
$totalQty = 0;
$totalValueExc = 0;
$totalSalesTax = 0;
$totalAmountFinal = 0;
$totaladvanceTaxAmount=0;

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}

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);

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));
}

// Convert only once for use in queries
$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo = date("Y-m-d", strtotime($dateto));

// Preserve original format for display
$datefrom = $datefrom;
$dateto = $dateto;

$filterReport = " WHERE DATE_FORMAT(inv.create_date,'%Y-%m-%d')>='$qryDate' 
                  AND DATE_FORMAT(inv.create_date,'%Y-%m-%d')<='$qryTo' 
                  AND inv.status <> 'Cancel' ";

if (isset($customer_name) && $customer_name != 'All') {
    $filterReport .= " AND inv.customer_id = '$customer_name' ";
}

if (isset($customer_category) && $customer_category != 'All') {
    $filterReport .= " AND cs.category_id = '$customer_category' ";
}

if (isset($advance_tax) && $advance_tax != 'All') {
    if ($advance_tax == '1') {
        $filterReport .= " AND cs.advance_tax = '1' ";
    } elseif ($advance_tax == '0') {
        $filterReport .= " AND (cs.advance_tax = '0' OR cs.advance_tax IS NULL) ";
    }
}

$filterReport .= " GROUP BY inv.id ORDER BY inv.code ";

$qry = Invoice::GetInvoiceReportList($filterReport);

// Get the logged-in user's name from the session
$loggedInUser = $_SESSION['sess_username'];

// Initialize FPDF
$pdf = new FPDFWithOutWaterMark('L', 'mm', 'A4');
$pdf->SetMargins(0, 0, 0);
$pdf->AddPage();
$pdf->Image(__DIR__ . '/../../../images/logo_left_print.png',10,5,25);
$pdf->Image(__DIR__ . '/../../../images/logo_right_print.png',257,5,25);
$pdf->SetFont('Arial', 'B', 12);
$pdf->SetMargins(0, 0, 0);
$pdf->SetTitle('Tax Invoice Status Report');
$pdf->Ln();
$pdf->SetFont('Arial', 'B', 16);
$pdf->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');
$pdf->SetX(10);

$pdf->Ln();
$pdf->SetFont('Arial', 'B', 14);
$pdf->Cell(0, 8, 'Tax Invoice Status Report', 0, 0, 'C');
$pdf->Ln();
$pdf->SetFont('Arial', '', 10);
$pdf->Cell(0, 4, 'For the period of: ' . date('d-m-Y', strtotime($datefrom)) . ' - ' . date('d-m-Y', strtotime($dateto)), 0, 0, 'C');
$pdf->Ln();
$pdf->SetFont('Arial', '', 8);
$pdf->Cell(10, 4, '', 0 ,0,'L');
$pdf->Cell(227, 4, 'Printed By: '.$loggedInUser, 0 ,0,'L');
$pdf->Cell(50, 4, 'Printed Date: ' . date('d-m-Y h:i A'), 0 ,0,'R');
$pdf->Ln();
$pdf->Ln();

// Function to print the table header
function printTableHeader($pdf) {
    $pdf->Ln();
    $pdf->SetX(10);
    $pdf->SetFont('Arial', 'B', 6);
    $pdf->Cell(7, 8, 'S.No', 1, 0, 'C');
    $pdf->Cell(14, 8, 'Date', 1, 0, 'C');
    $pdf->Cell(17, 8, 'Invoice #', 1, 0, 'C');
    $pdf->Cell(70, 8, 'Customer', 1, 0, 'C');
    $pdf->Cell(13, 8, 'NTN/STRN', 1, 0, 'C');
    $pdf->Cell(13, 8, 'Qty.', 1, 0, 'C');
    $pdf->Cell(12, 8, 'Carton.', 1, 0, 'C');
    $pdf->Cell(13, 8, 'Weight(Kg).', 1, 0, 'C');
    $pdf->Cell(25, 8, 'Value Exc. Sales Tax', 1, 0, 'C');
    $pdf->Cell(15, 8, 'Sales Tax %', 1, 0, 'C');
    $pdf->Cell(22, 8, 'Sales Tax Amount', 1, 0, 'C');
    $pdf->Cell(24, 8, 'Value Inc. Sales Tax', 1, 0, 'C');
    $pdf->Cell(19, 8, 'Adv. Tax Amount', 1, 0, 'C');
    $pdf->Cell(20, 8, 'Total', 1, 0, 'C');
    $pdf->Ln();
}

// Call the function to print the table header for the first page
printTableHeader($pdf);

// Initialize totals
$totalQty = 0;
$totalValueExc = 0;
$totalSalesTax = 0;
$totalAmountFinal = 0;

// Table data
$pdf->SetFont('Arial', '', 7);
$counter = 1;
if ($qry) {
    foreach ($qry as $qery) {
        $customer = CustomerSetup::GetCustomerSetupById($qery->customer_id);

        // === CALCULATIONS (MATCH HTML LOGIC) ===
        $productsQtys = 0;
        $productsUnitCostPrice = 0;
        $productsUnitSalePrice = 0;
        $totalCartons = 0;
        $totalWeight = 0;

        $salesTaxAmount   = (float)$qery->invoice_tax_amount;
        $advanceTaxAmount = (float)$qery->invoice_adv_tax_amount;
        $totalAmount      = (float)$qery->invoice_total_amount;
        $discount_price   = (float)$qery->invoice_discount_price;

        // Get invoice products
        $filterProducts = " WHERE invoice_id = '$qery->invoice_id'";
        $productSetup = Invoice::GetInvoiceProducts($filterProducts);

        if ($productSetup) {
            foreach ($productSetup as $productSetupRows) {
                $productsQtys += $productSetupRows->product_qty;

                $productDetails = ProductSetup::GetProductSetupById($productSetupRows->product_id);
                if ($productDetails && (int)$productDetails->carton_pieces > 0) {
                    $cartons = $productSetupRows->product_qty / $productDetails->carton_pieces;
                    $weight  = ($productSetupRows->product_qty * $productDetails->weight) / 1000;
                    $totalCartons += $cartons;
                    $totalWeight  += $weight;
                }

                // Cost & sale value
                $lineCost = $productSetupRows->product_qty * $productSetupRows->unit_cost_price;
                $productsUnitCostPrice += (float)$lineCost;

                // Sale value (mart/non-mart same)
                $lineSale = $productSetupRows->product_qty * $productSetupRows->unit_sale_price;
                $productsUnitSalePrice += (float)$lineSale;
            }
        }

        // === 1) Value EXCLUDING Sales Tax (after discount)
        $valueExclSalesTax = $productsUnitSalePrice - $discount_price;
        if ($valueExclSalesTax < 0) $valueExclSalesTax = 0;

        // === 2) Totals
        $totalQty             += $productsQtys;
        $grandtotalCartons    += $totalCartons;
        $grandtotalWeight     += $totalWeight;
        $totalValueExc        += $valueExclSalesTax;
        $totalSalesTax        += $salesTaxAmount;
        $totaladvanceTaxAmount+= $advanceTaxAmount;
        $totalAmountFinal     += $totalAmount;

        // === 3) Value INCLUDING tax
        $valueIncSalesTax = $valueExclSalesTax + $salesTaxAmount;

        // Check if a new page is needed and print header again
        if ($pdf->GetY() > 250) {
            $pdf->AddPage();
            printTableHeader($pdf);
            $pdf->SetY(55);
        }

        // Output data to PDF
        $pdf->SetX(10);
        $pdf->Cell(7, 8, $counter++, 1, 0, 'C');
        $pdf->Cell(14, 8, date('d-m-Y', strtotime($qery->create_date)), 1, 0, 'C');
        $pdf->Cell(17, 8, $qery->code, 1, 0, 'C');
        $name = (strlen($customer->name) > 45) ? substr($customer->name, 0, 42) . '...' : $customer->name;
        $pdf->Cell(70, 8, $name, 1, 0, 'L');

        $pdf->Cell(13, 8, $customer->ntn, 1, 0, 'C');
        $pdf->Cell(13, 8, number_format($productsQtys), 1, 0, 'R');
        $pdf->Cell(12, 8, number_format($totalCartons, 2), 1, 0, 'R');
        $pdf->Cell(13, 8, number_format($totalWeight, 2), 1, 0, 'R');
        $pdf->Cell(25, 8, number_format($valueExclSalesTax, 2), 1, 0, 'R');

        // Sales Tax %
        $salesTaxPercentage = (isset($qery->invoice_tax_rate) && $qery->invoice_tax_rate !== '')
            ? (float)$qery->invoice_tax_rate
            : (($valueExclSalesTax > 0) ? ($salesTaxAmount / $valueExclSalesTax) * 100 : 0);
        $pdf->Cell(15, 8, number_format($salesTaxPercentage, 2), 1, 0, 'R');

        $pdf->Cell(22, 8, number_format($salesTaxAmount, 2), 1, 0, 'R');
        $pdf->Cell(24, 8, number_format($valueIncSalesTax, 2), 1, 0, 'R');
        $pdf->Cell(19, 8, number_format($advanceTaxAmount, 2), 1, 0, 'R');
        $pdf->Cell(20, 8, number_format($totalAmount, 2), 1, 0, 'R');
        $pdf->Ln();
    }
}

// Add totals row at the bottom
$pdf->SetX(10);
$pdf->SetFont('Arial', 'B', 8, 0, 'C');
$pdf->Cell(121, 10, 'Total', 1, 0, 'R'); // Span across S.No, Date, Invoice #, Customer, NTN/STRN columns
$pdf->SetFont('Arial', 'B', 7, 0, 'C');
$pdf->Cell(13, 10, number_format($totalQty), 1, 0, 'R');
$pdf->Cell(12, 10, number_format($grandtotalCartons, 2), 1, 0, 'R');
$pdf->Cell(13, 10, number_format($grandtotalWeight, 2), 1, 0, 'R');
$pdf->Cell(25, 10, number_format($totalValueExc, 2), 1, 0, 'R');

$pdf->Cell(15, 10, '-', 1, 0, 'C');
$pdf->Cell(22, 10, number_format($totalSalesTax, 2), 1, 0, 'R');
$pdf->Cell(24, 10, number_format($totalValueExc + $totalSalesTax, 2), 1, 0, 'R');
$pdf->Cell(19, 10, number_format($totaladvanceTaxAmount, 2), 1, 0, 'R');
$pdf->Cell(20, 10, number_format($totalAmountFinal, 2), 1, 0, 'R');

// Output the PDF
$pdf->Output();
?>
