<?php
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');

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

$m = new Manager();

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

extract($_REQUEST);

$datefrom = isset($datefrom) ? $datefrom : "";
$dateto   = isset($dateto) ? $dateto : "";
$cat_name = isset($cat_name) ? $cat_name : "All";

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

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

$displayFrom = date("d-m-Y", strtotime($datefrom));
$displayTo   = date("d-m-Y", strtotime($dateto));

// ---------- Build filter ----------
$filterReport  = " WHERE DATE(inv.create_date) >= '" . $datefrom . "'
                   AND DATE(inv.create_date) <= '" . $dateto . "'
                   AND inv.status NOT IN ('Draft', 'Cancel') ";

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

$filterReport .= " ORDER BY inv.create_date ASC, cc.name ASC, cs.name ASC, inv.id ASC, invPr.id ASC ";

// ---------- Fetch data ----------
$rows = Invoice::GetInvoiceSalesDetailReport($filterReport);

// ---------- Group by invoice ----------
$invoices = array();

if ($rows) {
    foreach ($rows as $r) {

        $invId = $r->invoice_id;

        if (!isset($invoices[$invId])) {
            $invoices[$invId] = array(
                'invoice_id'               => $r->invoice_id,
                'invoice_code'             => $r->invoice_code,
              	'po_number'                => $r->po_number,
                'create_date'              => $r->create_date,
                'customer_id'              => $r->customer_id,
                'customer_name'            => $r->customer_name,
                'customer_category_id'     => $r->customer_category_id,
                'customer_category_name'   => !empty($r->customer_category_name) ? $r->customer_category_name : 'N/A',
                'customer_adv_tax_enabled' => $r->customer_adv_tax_enabled,
                'customer_adv_tax_perc'    => $r->customer_adv_tax_perc,
                'invoice_discount_amount'  => floatval($r->invoice_discount_amount),
                'invoice_is_tax'           => $r->invoice_is_tax,
                'invoice_tax'              => floatval($r->invoice_tax),
                'invoice_tax_amount'       => floatval($r->invoice_tax_amount),
                'invoice_adv_tax_rate'     => floatval($r->invoice_adv_tax_rate),
                'invoice_adv_tax_amount'   => floatval($r->invoice_adv_tax_amount),
                'invoice_total_amount'     => floatval($r->invoice_total_amount),
                'invoice_payment_due'      => floatval($r->invoice_payment_due),
                'lines'                    => array(),
                'invoice_gross_total'      => 0
            );
        }

        $carton = 0;
        if (!empty($r->carton_piece) && floatval($r->carton_piece) > 0) {
            $carton = floatval($r->product_qty) / floatval($r->carton_piece);
        }

        $qtyPcs = floatval($r->product_qty);

        $weightPerPieceKg = 0;
        $unitLower = strtolower(trim($r->product_unit));

        if ($unitLower == 'gm' || $unitLower == 'g') {
            $weightPerPieceKg = floatval($r->product_weight) / 1000;
        } elseif ($unitLower == 'kg') {
            $weightPerPieceKg = floatval($r->product_weight);
        } elseif ($unitLower == 'mg') {
            $weightPerPieceKg = floatval($r->product_weight) / 1000000;
        } else {
            $weightPerPieceKg = 0;
        }

        $lineWeightKg = $weightPerPieceKg * $qtyPcs;
        $lineGross    = $qtyPcs * floatval($r->unit_sale_price);

        $line = array(
            'invoice_product_id' => $r->invoice_product_id,
            'product_id'         => $r->product_id,
            'product_name'       => $r->product_name,
            'product_weight'     => $r->product_weight,
            'product_unit'       => $r->product_unit,
            'carton'             => $carton,
            'qty_pcs'            => $qtyPcs,
            'line_weight_kg'     => $lineWeightKg,
            'unit_sale_price'    => floatval($r->unit_sale_price),
            'line_gross'         => $lineGross
        );

        $invoices[$invId]['lines'][] = $line;
        $invoices[$invId]['invoice_gross_total'] += $lineGross;
    }
}

class PDF extends FPDF
{
    public $reportTitle = 'Detailed Sales Report (Invoice & Products)';
    public $periodText  = '';
    public $categoryText = 'All';

    function Header()
    {
        $this->SetFont('Arial', 'B', 13);
        $this->Cell(0, 7, $this->reportTitle, 0, 1, 'C');

        $this->SetFont('Arial', '', 9);
        $this->Cell(0, 5, 'Period: ' . $this->periodText . '    Category: ' . $this->categoryText, 0, 1, 'C');
        $this->Ln(2);

        $this->PrintTableHeader();
    }

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

    function PrintTableHeader()
    {
        $this->SetFont('Arial', 'B', 7);
        $this->SetFillColor(230, 230, 230);

        $this->Cell(8,  8, 'S#',      1, 0, 'C', true);
        $this->Cell(30, 8, 'Invoice / Date', 1, 0, 'C', true);
        $this->Cell(42, 8, 'Product', 1, 0, 'C', true);
        $this->Cell(18, 8, 'Weight',  1, 0, 'C', true);
        $this->Cell(16, 8, 'Carton',  1, 0, 'C', true);
        $this->Cell(16, 8, 'Qty',     1, 0, 'C', true);
        $this->Cell(20, 8, 'Wt(KG)',  1, 0, 'C', true);
        $this->Cell(22, 8, 'Gross',   1, 0, 'C', true);
        $this->Cell(20, 8, 'Disc.',   1, 0, 'C', true);
        $this->Cell(22, 8, 'Excl Tax',1, 0, 'C', true);
        $this->Cell(18, 8, 'Sales Tax',1, 0, 'C', true);
        $this->Cell(18, 8, 'Adv Tax', 1, 0, 'C', true);
        $this->Cell(22, 8, 'Incl Total',1, 1, 'C', true);
    }

    function CheckPageBreakCustom($height)
    {
        if ($this->GetY() + $height > 185) {
            $this->AddPage('L', 'A4');
        }
    }

    function RowCells($data, $fills = false, $fontStyle = '', $fontSize = 7)
    {
        $this->SetFont('Arial', $fontStyle, $fontSize);

        $this->Cell(8,  6, $data[0],  1, 0, 'C', $fills);
        $this->Cell(30, 6, $data[1],  1, 0, 'L', $fills);
        $this->Cell(42, 6, $data[2],  1, 0, 'L', $fills);
        $this->Cell(18, 6, $data[3],  1, 0, 'C', $fills);
        $this->Cell(16, 6, $data[4],  1, 0, 'R', $fills);
        $this->Cell(16, 6, $data[5],  1, 0, 'R', $fills);
        $this->Cell(20, 6, $data[6],  1, 0, 'R', $fills);
        $this->Cell(22, 6, $data[7],  1, 0, 'R', $fills);
        $this->Cell(20, 6, $data[8],  1, 0, 'R', $fills);
        $this->Cell(22, 6, $data[9],  1, 0, 'R', $fills);
        $this->Cell(18, 6, $data[10], 1, 0, 'R', $fills);
        $this->Cell(18, 6, $data[11], 1, 0, 'R', $fills);
        $this->Cell(22, 6, $data[12], 1, 1, 'R', $fills);
    }
}

// ---------- Category text ----------
$categoryText = 'All';
if ($cat_name != 'All') {
    $catObj = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
    if ($catObj) {
        $categoryText = $catObj->name;
    }
}

// ---------- PDF ----------
$pdf = new PDF('L', 'mm', 'A4');
$pdf->AliasNbPages();
$pdf->reportTitle = 'Detailed Sales Report (Invoice & Products)';
$pdf->periodText = $displayFrom . ' to ' . $displayTo;
$pdf->categoryText = $categoryText;
$pdf->SetMargins(5, 8, 5);
$pdf->AddPage('L', 'A4');

// ---------- Totals ----------
$grand_carton    = 0;
$grand_qty       = 0;
$grand_weight_kg = 0;
$grand_gross     = 0;
$grand_discount  = 0;
$grand_excl      = 0;
$grand_tax       = 0;
$grand_adv_tax   = 0;
$grand_incl      = 0;

$srno = 1;

if (!empty($invoices)) {
    foreach ($invoices as $inv) {

        $invoiceTaxRate    = ($inv['invoice_is_tax'] == 1) ? floatval($inv['invoice_tax']) : 0;
        $invoiceDiscount   = floatval($inv['invoice_discount_amount']);
        $invoiceGrossTotal = floatval($inv['invoice_gross_total']);

        $invoiceAdvTaxAmount = 0;
        if (!empty($inv['customer_adv_tax_enabled']) && $inv['customer_adv_tax_enabled'] == 1) {
            $invoiceAdvTaxAmount = floatval($inv['invoice_adv_tax_amount']);
        }

        $inv_carton    = 0;
        $inv_qty       = 0;
        $inv_weight_kg = 0;
        $inv_gross     = 0;
        $inv_discount  = 0;
        $inv_excl      = 0;
        $inv_tax       = 0;
        $inv_adv_tax   = 0;
        $inv_incl      = 0;

        // invoice header line
        $pdf->CheckPageBreakCustom(7);
        $pdf->SetFont('Arial', 'B', 8);
        $pdf->SetFillColor(245, 245, 245);

        $invoiceHeaderText = 'Invoice: ' . $inv['invoice_code']
                . ' | PO #: ' . (!empty($inv['po_number']) ? $inv['po_number'] : 'N/A')
                . ' | Date: ' . date('d-m-Y h:i A', strtotime($inv['create_date']))
                . ' | Customer: ' . $inv['customer_name']
                . ' | Tax Rate: ' . number_format($invoiceTaxRate, 2) . '%';

            if ($invoiceAdvTaxAmount > 0) {
                $invoiceHeaderText .= ' | Adv. Tax: ' . number_format($invoiceAdvTaxAmount, 2);
            }

            $pdf->Cell(272, 7, $invoiceHeaderText, 1, 1, 'L', true);
        foreach ($inv['lines'] as $line) {

            $share = ($invoiceGrossTotal > 0) ? ($line['line_gross'] / $invoiceGrossTotal) : 0;
            $line_discount = $share * $invoiceDiscount;
            $value_excl    = $line['line_gross'] - $line_discount;
            $line_tax      = $value_excl * ($invoiceTaxRate / 100);
            $line_adv_tax  = $share * $invoiceAdvTaxAmount;
            $value_incl    = $value_excl + $line_tax + $line_adv_tax;

            $inv_carton    += $line['carton'];
            $inv_qty       += $line['qty_pcs'];
            $inv_weight_kg += $line['line_weight_kg'];
            $inv_gross     += $line['line_gross'];
            $inv_discount  += $line_discount;
            $inv_excl      += $value_excl;
            $inv_tax       += $line_tax;
            $inv_adv_tax   += $line_adv_tax;
            $inv_incl      += $value_incl;

            $pdf->CheckPageBreakCustom(6);

            $invoiceCol = $inv['invoice_code'] . "\n" . date('d-m-Y', strtotime($inv['create_date']));
          
            $productCol = $line['product_name'];

            $pdf->RowCells(array(
                $srno,
                substr($invoiceCol, 0, 25),
                substr($productCol, 0, 38),
                $line['product_weight'] . ' ' . $line['product_unit'],
                number_format($line['carton'], 2),
                number_format($line['qty_pcs'], 2),
                number_format($line['line_weight_kg'], 3),
                number_format($line['line_gross'], 2),
                number_format($line_discount, 2),
                number_format($value_excl, 2),
                number_format($line_tax, 2),
                number_format($line_adv_tax, 2),
                number_format($value_incl, 2)
            ));

            $srno++;
        }

        // Invoice total row
        $pdf->CheckPageBreakCustom(7);
        $pdf->SetFillColor(224, 224, 224);
        $pdf->RowCells(array(
            '',
            'Invoice Total',
            '',
            '',
            number_format($inv_carton, 2),
            number_format($inv_qty, 2),
            number_format($inv_weight_kg, 3),
            number_format($inv_gross, 2),
            number_format($inv_discount, 2),
            number_format($inv_excl, 2),
            number_format($inv_tax, 2),
            number_format($inv_adv_tax, 2),
            number_format($inv_incl, 2)
        ), true, 'B', 7);

        $grand_carton    += $inv_carton;
        $grand_qty       += $inv_qty;
        $grand_weight_kg += $inv_weight_kg;
        $grand_gross     += $inv_gross;
        $grand_discount  += $inv_discount;
        $grand_excl      += $inv_excl;
        $grand_tax       += $inv_tax;
        $grand_adv_tax   += $inv_adv_tax;
        $grand_incl      += $inv_incl;
    }

    // Grand total row
    $pdf->CheckPageBreakCustom(8);
    $pdf->SetFillColor(207, 216, 220);
    $pdf->RowCells(array(
        '',
        'GRAND TOTAL',
        '',
        '',
        number_format($grand_carton, 2),
        number_format($grand_qty, 2),
        number_format($grand_weight_kg, 3),
        number_format($grand_gross, 2),
        number_format($grand_discount, 2),
        number_format($grand_excl, 2),
        number_format($grand_tax, 2),
        number_format($grand_adv_tax, 2),
        number_format($grand_incl, 2)
    ), true, 'B', 7);

} else {
    $pdf->SetFont('Arial', '', 10);
    $pdf->Cell(272, 10, 'No records found for selected criteria.', 1, 1, 'C');
}

ob_end_clean();
$pdf->Output('sales_detailed_report_' . date('d-m-Y_H-i-s') . '.pdf', 'I');
exit;

?>