<?php
require_once('includes/load.php');

// Function to get the order details for bazzar
function getBazzarDetails($bazzar_id)
{
  global $db;
  // Query the bazzar table
  $bazzar_query = "SELECT * FROM bazzar WHERE id = $bazzar_id";
  $bazzar_result = $db->query($bazzar_query);

  if ($bazzar_result->num_rows == 0) {
    die("Bazzar not found.");
  }

  $bazzar = $bazzar_result->fetch_assoc();

  // Query the bazzar_detail table
  $products_query = "SELECT p.name AS name, p.part_number, eod.quantity, eod.price, eod.subtotal
                       FROM bazzar_detail eod
                       JOIN products p ON p.part_number = eod.product_name
                       WHERE eod.bazzar_id = $bazzar_id";
  $products_result = $db->query($products_query);

  $products = [];
  while ($row = $products_result->fetch_assoc()) {
    $products[] = $row;
  }

  return [$bazzar, $products];
}

class CustomPDF extends TCPDF
{
  protected $brandName;  // Declare a variable to hold brand name

  // Constructor to pass brand name
  public function __construct($brandName)
  {
    parent::__construct();
    $this->brandName = $brandName;  // Store brand name for use in the header
  }

  // Overriding the Header method
  public function Header()
  {
    global $db;

    // Fetch brand data from the database using the brand name stored in the object
    $query = "SELECT brand_name, logo_path, address FROM brands WHERE brand_name = '{$this->brandName}'";
    $result = $db->query($query);
    $brand = $result->fetch_assoc(); // Fetch brand data

    // Check if brand data is available
    if ($brand) {
      // Add the logo to the header on the left
      $logoPath = $brand['logo_path']; // Path to the logo
      $this->Image($logoPath, 10, 10, 36, 14, 'PNG'); // Logo size and position

      // Set the font for the header text
      $this->SetFont('helvetica', 'B', 12);

      // Move to the right to align the text properly
      $this->SetXY(48, 10); // Adjust X and Y positions to avoid overlapping with the image

      // Add the brand name in the header
      $this->Cell(0, 10, $brand['brand_name'], 0, 1, 'L', 0, '', 0, false, 'T', 'M');

      // Set font for the address
      $this->SetFont('helvetica', '', 9);

      // Add the address in the header
      $this->SetXY(48, 17); // Adjust Y position for the second line
      $this->Cell(0, 10, $brand['address'], 0, 1, 'L', 0, '', 0, false, 'T', 'M');
    }
  }
}

// Function to generate Surat Jalan PDF for bazzar
function createSuratJalan($bazzar, $products)
{
  $formattedDate = date('d F Y', strtotime($bazzar['created_at']));
  $formattedDate = str_replace(
    ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
    ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'],
    $formattedDate
  );
  generateBarcode($bazzar['bazzar_sj']);
  $pageWidth = 210; // Width of A4 in mm

  // Barcode dimensions
  $barcodeWidth = 80; // Width of the barcode in mm
  $barcodeHeight = 10; // Height of the barcode in mm

  // Fixed Y position (adjust as needed)
  $yPosition = 30; // Vertical position in mm

  // Calculate the horizontal center position
  $centerX = ($pageWidth - $barcodeWidth) / 2; // Center horizontally
  // Create instance of TCPDF
  $pdf = new CustomPDF('Wiselie');
  $pdf->SetMargins(10, 30, 10);
  $pdf->SetFooterMargin(0);
  $pdf->SetAutoPageBreak(TRUE, 0);

  // Add a page
  $pdf->AddPage();
  // Order details
  $pdf->SetFont('helvetica', '', 9);
  // Barcode generation logic here
  // Assuming the barcode generation is done separately and the barcode image exists
  $pdf->Image('storage/barcode_' . $bazzar['bazzar_sj'] . '.png', $centerX, $yPosition, $barcodeWidth, $barcodeHeight, 'PNG');
  $pdf->Ln(7);
  $pdf->Cell(0, 10,   $bazzar['bazzar_sj'], 0, 1, 'C'); // Bazzar SN
  $pdf->SetFont('helvetica', 'B', 12);
  $pdf->Cell(0, 10, 'SURAT JALAN', 0, 1, 'C');

  $pdf->SetFont('helvetica', '', 9);

  // Adjust the starting position
  $pdf->SetY(58); // Adjust Y position for the content

  // Left section: "Kepada"
  $pdf->Cell(40, 5, 'Kepada : ' . $bazzar['customer_name'], 0, 1); // Customer name
  $pdf->MultiCell(110, 5, $bazzar['address'], 0, 1); // Address

  // Right section: Details
  $pdf->SetY(58); // Reset Y position for the right section
  $pdf->SetX(120); // Move to the right side of the page
  $pdf->Cell(18, 5, 'Tanggal', 0, 0); // Label
  $pdf->Cell(0, 5, ': ' . $formattedDate, 0, 1); // Date

  $pdf->SetX(120); // Align right
  $pdf->Cell(18, 5, 'No. Edors', 0, 0); // No. SJ Label
  $pdf->Cell(0, 5, ': ' . $bazzar['bazzar_sn'], 0, 1); // Bazzar SJ

  $pdf->SetX(120); // Align right
  $pdf->Cell(18, 5, 'No. Telp', 0, 0); // Phone label
  $pdf->Cell(0, 5, ': ' . $bazzar['phone'], 0, 1); // Phone number

  // Product details table
  $pdf->Ln(5);
  $pdf->SetFont('helvetica', 'B', 9);

  // Table header
  $pdf->Cell(83, 5, 'Product Name', 1, 0, 'C');  // Adjusted column width for Product Name
  $pdf->Cell(97, 5, 'Part Number', 1, 0, 'C');    // Column for Part Number
  $pdf->Cell(10, 5, 'Qty', 1, 1, 'C');            // Column for Quantity

  $pdf->SetFont('helvetica', '', 9);
  $total_quantity = 0;

  // Table rows for product details
  foreach ($products as $product) {
    $pdf->Cell(83, 5, $product['name'], 1, 0, 'C');  // Product Name
    $pdf->Cell(97, 5, $product['part_number'], 1, 0, 'C');  // Part Number
    $pdf->Cell(10, 5, number_format($product['quantity'], 0), 1, 1, 'C');  // Quantity

    // Accumulate totals
    $total_quantity += $product['quantity'];
  }

  // Add totals row
  $pdf->SetFont('helvetica', 'B', 9);
  $pdf->Cell(180, 5, 'Total', 1, 0, 'C');  // Adjusted cell width for "Total"
  $pdf->Cell(10, 5, number_format($total_quantity, 0), 1, 1, 'C');  // Total quantity

  $pdf->Ln(5);
  // Add terms and conditions
  $pdf->SetFont('helvetica', '', 8);
  $pdf->MultiCell(0, 10, "Terms and Conditions :\n1. Barang/jasa yang diterima sepenuhnya menjadi tanggung jawab PIHAK KEDUA sesuai kesepakatan.\n2. Kedua belah pihak menandatangani Berita Acara ini sebagai bukti serah terima telah dilakukan.\n3. Batas retur (kondisi produk cacat produksi, pecah, bocor, barang tidak sesuai pesanan, tidak ada NIE dan Exp date) dapat dilakukan penukaran barang maksimal 3 hari sejak barang diterima.\n4. Barang dapat dikembalikan maksimal 3 (tiga) bulan sejak dilakukan evaluasi.", 0, 'L', false);
  $pdf->Ln(5);
  // Signature section
  $pdf->SetFont('helvetica', '', 9);
  $pdf->SetX(0);
  $pdf->Cell(70, 5, 'Gudang', 0, 0, 'C');
  $pdf->SetX(80);
  $pdf->Cell(50, 5, 'Pengirim', 0, 0, 'C');
  $pdf->SetX(150);
  $pdf->Cell(50, 5, 'Penerima', 0, 1, 'C');

  $pdf->Ln(30); // Move below signature boxes
  $pdf->SetX(0);
  $pdf->Cell(70, 10, 'Tanggal: ....................', 0, 0, 'C');
  $pdf->SetX(80);
  $pdf->Cell(50, 10, 'Tanggal: ....................', 0, 0, 'C');
  $pdf->SetX(150);
  $pdf->Cell(50, 10, 'Tanggal: ....................', 0, 1, 'C');

  // Output the PDF
  $pdf->Output('bazzar_surat_jalan_' . $bazzar['bazzar_sn'] . '.pdf', 'I');
}

// Fetch the bazzar ID from URL and generate the Surat Jalan
$bazzar_id = $_GET['order_id']; // Replace with the actual bazzar ID
list($bazzar, $products) = getBazzarDetails($bazzar_id);
createSuratJalan($bazzar, $products);