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

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

$loggedInUser = $_SESSION['sess_username'];
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);

// Set up date filters
$datefrom = isset($_GET['datefrom']) ? date("Y-m-d", strtotime($_GET['datefrom'])) : date('Y-m-d', strtotime("-30 days"));
$dateto = isset($_GET['dateto']) ? date("Y-m-d", strtotime($_GET['dateto'])) : date('Y-m-d');
$supplier_id = $_GET['supplier_id'] ?? 'All';

// Fetch purchase data
$purchases = PurchaseSetup::GetSupplierPurchaseReport($datefrom, $dateto, $supplier_id, $sales_tax_filter);

// Custom FPDF class with Header() override
class PDF extends FPDF {
    function Header() {
        // Set logo and title
        $datefrom = isset($_GET['datefrom']) ? date("Y-m-d", strtotime($_GET['datefrom'])) : date('Y-m-d', strtotime("-30 days"));
        $dateto = isset($_GET['dateto']) ? date("Y-m-d", strtotime($_GET['dateto'])) : date('Y-m-d');
        $loggedInUser = $_SESSION['sess_username'];
        $this->Image(__DIR__ . '/../../../images/logo_left_print.png',10,5,25);
        $this->Image(__DIR__ . '/../../../images/logo_right_print.png',257,5,25);
        $this->SetFont('Arial', 'B', 16);
        $this->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');
        $this->Ln();
        $this->SetFont('Arial', 'B', 14);
        $this->Cell(0, 10, 'Purchase Report', 0, 1, 'C');
        $this->SetFont('Arial', '', 10);
        $this->Cell(0, 4, 'For the period of: ' . date('d-m-Y', strtotime($datefrom)) . ' - ' . date('d-m-Y', strtotime($dateto)), 0, 0, 'C');
        $this->Ln();
        $this->SetFont('Arial', '', 8);
        $this->Cell(220, 4, 'Printed By: '.$loggedInUser, 0 ,0,'L');
        $this->Cell(50, 4, 'Printed Date: ' . date('d-m-Y h:i A'), 0 ,0,'R');
        //$this->Cell(135, 0, 'Printed Date: ' . date('d-m-Y h:i A'), 0, 0, 'L');
        $this->Ln();
        // Table header
        $this->SetFont('Arial', 'B', 7);
        $header = ['S.No.', 'Supplier Name / Invoice Date / Invoice No', 'D.C. No', 'D.C. Date', 'Item', 'Quantity', 'Price', 'Ex. Sales Tax Amount', 'Sales Tax Amount', 'Incl.Sales Tax Amount'];
        $widths = [10, 65, 25, 20, 35, 20, 13, 30, 25, 30];
        
        // Print table header
        foreach ($header as $i => $col) {
            $this->Cell($widths[$i], 7, $col, 1, 0, 'C');
        }
        $this->Ln();
    }

    function Footer() {
        // Position at 1.5 cm from bottom
        $this->SetY(-15);
        // Set font
        $this->SetFont('Arial', 'I', 7);
        // Page number
        $this->Cell(0, 10, 'Page ' . $this->PageNo(), 0, 0, 'C');
    }
}

// Create PDF Object
$pdf = new PDF('L', 'mm', 'A4');
$pdf->AddPage();

// Report data
$pdf->SetFont('Arial', '', 7);
$count = 0;
$grandTotalQty = $grandTotalExAmount = $grandTotalTax = $grandTotalIncAmount = 0;

$currentSupplierId = null;
$supplierSubtotalQty = $supplierSubtotalExAmount = $supplierSubtotalTax = $supplierSubtotalIncAmount = 0;
$currentSupplierName = ''; // Added variable to hold supplier name

foreach ($purchases as $row) {
    if ($currentSupplierId !== null && $currentSupplierId !== $row['supplier_id']) {
        // Supplier subtotal row, fixed supplier name issue
        $pdf->SetFont('Arial', 'B', 7);
        $pdf->Cell(155, 7, "Total for {$currentSupplierName}", 1, 0, 'R'); // Use currentSupplierName for correct supplier name
        $pdf->Cell(20, 7, number_format($supplierSubtotalQty, 4), 1, 0, 'R');
        $pdf->Cell(13, 7, '', 1);
        $pdf->Cell(30, 7, number_format($supplierSubtotalExAmount, 2), 1, 0, 'R');
        $pdf->Cell(25, 7, number_format($supplierSubtotalTax, 2), 1, 0, 'R');
        $pdf->Cell(30, 7, number_format($supplierSubtotalIncAmount, 2), 1, 0, 'R');
        $pdf->Ln();

        // Reset supplier subtotals for next supplier
        $supplierSubtotalQty = $supplierSubtotalExAmount = $supplierSubtotalTax = $supplierSubtotalIncAmount = 0;
    }

    // Display supplier and invoice information once per invoice
    $currentSupplierId = $row['supplier_id'];
    $currentSupplierName = $row['supplier_name']; // Store current supplier name
    $count += 1;
    $purchaseInvoiceDate = ($row['purchase_invoice_date'] !== '0000-00-00') ? date('d-m-Y', strtotime($row['purchase_invoice_date'])) : '-';
    $deliveryChallanDate = ($row['delivery_challan_date'] !== '0000-00-00') ? date('d-m-Y', strtotime($row['delivery_challan_date'])) : '-';
  	$deliveryChallanNo = $row['delivery_challan_no'];

    $pdf->SetFont('Arial', '', 6);
    $pdf->Cell(10, 7, $count, 1, 0, 'C');
    $pdf->Cell(65, 7, $row['supplier_name'] .' / '.$purchaseInvoiceDate.' / '.$row['purchase_invoice_no'],1);
    $pdf->Cell(25, 7, $deliveryChallanNo, 1);
    $pdf->Cell(20, 7, $purchaseInvoiceDate, 1);

    $isFirstItem = true; // To check if it's the first item of the invoice

    foreach ($row['items'] as $item) {
        if (!$isFirstItem) {
            // Add empty cells for repeated rows under the same invoice
            $pdf->Cell(10, 7, '', 1, 0);
            $pdf->Cell(110, 7, '', 1, 0);
        }
        $itemTotal = $item['qty'] * $item['rate'];
        $pdf->Cell(35, 7, $item['ingredient_name'], 1);
        $pdf->Cell(20, 7, number_format($item['qty'], 4), 1, 0, 'R');
        $pdf->Cell(13, 7, number_format($item['rate'], 2), 1, 0, 'R');
        $pdf->Cell(30, 7, number_format($itemTotal, 2), 1, 0, 'R');
        $pdf->Cell(25, 7, number_format($item['tax_amount'], 2), 1, 0, 'R');
        $pdf->Cell(30, 7, number_format($itemTotal + $item['tax_amount'], 2), 1, 0, 'R');
        $pdf->Ln();
        $isFirstItem = false;
    }

    // Invoice totals row
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->Cell(155, 7, "Invoice Total", 1, 0, 'R');
    $pdf->Cell(20, 7, number_format($row['qty'], 4), 1, 0, 'R');
    $pdf->Cell(13, 7, '', 1);
    $pdf->Cell(30, 7, number_format($row['total_ex_amount'], 2), 1, 0, 'R');
    $pdf->Cell(25, 7, number_format($row['tax_price'], 2), 1, 0, 'R');
    $pdf->Cell(30, 7, number_format($row['total_amount'], 2), 1, 0, 'R');
    $pdf->Ln();

    // Update supplier subtotals
    $supplierSubtotalQty += $row['qty'];
    $supplierSubtotalExAmount += $row['total_ex_amount'];
    $supplierSubtotalTax += $row['tax_price'];
    $supplierSubtotalIncAmount += $row['total_amount'];
  
  $grandTotalQty += $row['qty'];
    $grandTotalExAmount += $row['total_ex_amount'];
    $grandTotalTax += $row['tax_price'];
    $grandTotalIncAmount += $row['total_amount'];
}

// Final supplier subtotal row after all data
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(155, 7, "Total for {$currentSupplierName}", 1, 0, 'R');
$pdf->Cell(20, 7, number_format($supplierSubtotalQty, 4), 1, 0, 'R');
$pdf->Cell(13, 7, '', 1);
$pdf->Cell(30, 7, number_format($supplierSubtotalExAmount, 2), 1, 0, 'R');
$pdf->Cell(25, 7, number_format($supplierSubtotalTax, 2), 1, 0, 'R');
$pdf->Cell(30, 7, number_format($supplierSubtotalIncAmount, 2), 1, 0, 'R');
$pdf->Ln();

// Grand total row
$pdf->SetFont('Arial', 'B', 8);
$pdf->Cell(155, 7, 'Grand Total', 1, 0, 'R');
$pdf->Cell(20, 7, number_format($grandTotalQty, 4), 1, 0, 'R');
$pdf->Cell(13, 7, '', 1);
$pdf->Cell(30, 7, number_format($grandTotalExAmount, 2), 1, 0, 'R');
$pdf->Cell(25, 7, number_format($grandTotalTax, 2), 1, 0, 'R');
$pdf->Cell(30, 7, number_format($grandTotalIncAmount, 2), 1, 0, 'R');
$pdf->Output();
?>
