<?php
include_once('../../../fpdf/fpdfreportlogo.php');
include_once('../../../classes/manager.class.php');

$m = new Manager();

$datefrom      = $_GET['datefrom']      ?? date('d-m-Y', strtotime('-30 days'));
$dateto        = $_GET['dateto']        ?? date('d-m-Y');
$cat_name      = $_GET['cat_name']      ?? 'All';
$customer_name = $_GET['customer_name'] ?? 'All';
$status        = $_GET['status']        ?? 'All';

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

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

if ($cat_name != 'All') {
    if ($customer_name != 'All') {
        $filterReport .= " AND inv.customer_id ='$customer_name'";
    } else {
        $cat       = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
        $filterCat = " WHERE category_id = '$cat->id'";
        $cust      = CustomerSetup::GetCustomerSetupList($filterCat);
        $custArray = array();

        if ($cust) {
            foreach ($cust as $c) {
                $custArray[] = $c->id;
            }
        }

        if (!empty($custArray)) {
            $customers     = implode(',', $custArray);
            $filterReport .= " AND inv.customer_id IN ($customers)";
        }
    }
}

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

/*
 * Status filter fix:
 * The frontend dropdown has:
 * Paid
 * Pending / Partial Paid
 *
 * But database may contain:
 * Pending
 * pending
 * Partial Paid
 * partial paid
 *
 * So we use LOWER(TRIM(inv.status)).
 */
if ($status != 'All') {

    if ($status == 'Pending') {
        $filterReport .= " AND LOWER(TRIM(inv.status)) IN ('pending', 'partial paid')";
    } elseif ($status == 'Paid') {
        $filterReport .= " AND LOWER(TRIM(inv.status)) = 'paid'";
    } else {
        $filterReport .= " AND LOWER(TRIM(inv.status)) = '" . strtolower(trim($status)) . "'";
    }
}

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

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

// ---------------- FPDF Setup ----------------

class PDF extends FPDF
{
    var $datefrom, $dateto, $cat_name, $customer_name, $status;

    function Header()
    {
        $this->Image(__DIR__ . '/../../../images/logo_left_print.png', 10, 6, 30);
        $this->Image(__DIR__ . '/../../../images/logo_right_print.png', 265, 6, 30);

        $this->SetFont('Arial', 'B', 16);
        $this->Cell(0, 10, 'Invoice Status Report', 0, 1, 'C');

        $this->SetFont('Arial', '', 10);
        $this->Cell(0, 8, "Period: {$this->datefrom} to {$this->dateto}", 0, 1, 'C');

        $this->SetFont('Arial', '', 9);
        $this->Cell(0, 6, "Category: {$this->cat_name} | Customer: {$this->customer_name} | Status: {$this->status}", 0, 1, 'C');

        $this->Ln(3);

        $this->SetFont('Arial', 'B', 9);
        $this->SetFillColor(230, 230, 230);

        $this->Cell(10, 7, 'S.No',      1, 0, 'C', true);
        $this->Cell(33, 7, 'Date',      1, 0, 'C', true);
        $this->Cell(22, 7, 'Invoice #', 1, 0, 'C', true);
        $this->Cell(131, 7, 'Customer', 1, 0, 'C', true);
        $this->Cell(20, 7, 'Status',    1, 0, 'C', true);
        $this->Cell(22, 7, 'Total Amt', 1, 0, 'C', true);
        $this->Cell(22, 7, 'Payments',  1, 0, 'C', true);
        $this->Cell(22, 7, 'Balance',   1, 1, 'C', true);
    }
}

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

$pdf->datefrom = $datefrom;
$pdf->dateto   = $dateto;
$pdf->cat_name = $cat_name;

// Resolve category name for header
if ($cat_name != 'All') {
    $catHeader = CustomerCategorySetup::GetCustomerCategorySetupById($cat_name);
    if ($catHeader) {
        if (isset($catHeader->name)) {
            $pdf->cat_name = $catHeader->name;
        } elseif (isset($catHeader->catname)) {
            $pdf->cat_name = $catHeader->catname;
        }
    }
}

// Resolve customer name for header
$pdf->customer_name = 'All';
if ($customer_name != 'All') {
    $customer = CustomerSetup::GetCustomerSetupById($customer_name);
    if ($customer) {
        $pdf->customer_name = $customer->name;
    }
}

// Better status label for print header
$pdf->status = $status;
if ($status == 'Pending') {
    $pdf->status = 'Pending / Partial Paid';
}

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

$totalAmount   = 0;
$totalPayments = 0;
$totalBalance  = 0;
$counter       = 1;

if ($data) {
    foreach ($data as $row) {

        // FINAL invoice total, already includes discounts, tax and advance tax
        $invoiceNetTotal = $row->invoice_total_amount;

        // Total payments for this invoice, non-cancelled
        $payments = $row->payment_received;

        // Per-invoice balance / over-payment
        $balance = $invoiceNetTotal - $payments;

        /*
         * Status text:
         * If payment is between 0 and invoice total, show Partial Paid.
         * Otherwise show invoice status from DB.
         */
        $invoiceStatus = strtolower(trim($row->invoice_status));

        if ($payments > 0 && $payments < $invoiceNetTotal) {
            $statusText = "Partial Paid";
        } elseif ($invoiceStatus == 'paid') {
            $statusText = "Paid";
        } elseif ($invoiceStatus == 'pending') {
            $statusText = "Pending";
        } elseif ($invoiceStatus == 'partial paid') {
            $statusText = "Partial Paid";
        } elseif ($invoiceStatus == 'draft') {
            $statusText = "Draft";
        } elseif ($invoiceStatus == 'cancel') {
            $statusText = "Cancel";
        } else {
            $statusText = $row->invoice_status;
        }

        // Row
        $pdf->Cell(10, 6, $counter++, 1, 0, 'C');
        $pdf->Cell(33, 6, date('d-m-Y h:i A', strtotime($row->create_date)), 1);
        $pdf->Cell(22, 6, $row->code, 1);

        $pdf->SetFont('Arial', '', 8);
        $pdf->Cell(131, 6, $row->customer_name, 1);
        $pdf->SetFont('Arial', '', 9);

        $pdf->Cell(20, 6, $statusText, 1, 0, 'C');
        $pdf->Cell(22, 6, number_format($invoiceNetTotal, 2), 1, 0, 'R');
        $pdf->Cell(22, 6, number_format($payments, 2),       1, 0, 'R');
        $pdf->Cell(22, 6, number_format($balance, 2),        1, 1, 'R');

        // Totals
        $totalAmount   += $invoiceNetTotal;
        $totalPayments += $payments;
        $totalBalance  += $balance;
    }
}

// Grand totals row
$pdf->SetFont('Arial', 'B', 9);
$pdf->Cell(216, 7, 'Grand Total', 1, 0, 'R');
$pdf->Cell(22, 7, number_format($totalAmount,   2), 1, 0, 'R');
$pdf->Cell(22, 7, number_format($totalPayments, 2), 1, 0, 'R');
$pdf->Cell(22, 7, number_format($totalBalance,  2), 1, 1, 'R');

$pdf->Output();
?>