<?php
require_once('includes/load.php');
// Fetch order details
function getOrderOfflineDetails($order_id)
{
  global $db;
  // Query the orders_offline table
  $order_query = "SELECT * FROM orders_offline WHERE id = $order_id";
  $order_result = $db->query($order_query);

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

  $order = $order_result->fetch_assoc();

  // Query the orders_offline_detail table
  $products_query = "SELECT p.name AS name, p.part_number, tb.name as box_name, ood.box, ood.quantity, price, subtotal, ood.code_batch_product FROM orders_offline_detail ood JOIN type_box tb on tb.id = ood.type_box JOIN products p ON p.part_number = ood.product_name WHERE order_id = $order_id";
  $products_result = $db->query($products_query);

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

  return [$order, $products];
}

function getOrderBazzarDetails($order_id)
{
  global $db;
  // Query the orders_offline table
  $order_query = "SELECT * FROM bazzar WHERE id = $order_id";
  $order_result = $db->query($order_query);

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

  $order = $order_result->fetch_assoc();

  // Query the orders_offline_detail table
  $products_query = "SELECT p.name AS name, p.part_number, tb.name as box_name, ood.box, ood.quantity, price, subtotal, ood.code_batch_product FROM orders_offline_detail ood JOIN type_box tb on tb.id = ood.type_box JOIN products p ON p.part_number = ood.product_name WHERE order_id = $order_id";
  $products_result = $db->query($products_query);

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

  return [$order, $products];
}

class CustomPDF extends TCPDF
{
  public function Header()
  {
    // Add the logo to the header on the left
    $this->Image('assets/img/logo-bca-black.png', 10, 10, 36, 14, 'PNG'); // Adjust path and size as needed

    // 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 header title
    $this->Cell(0, 10, 'PT. BALI CAHAYA ASIA', 0, 1, 'L', 0, '', 0, false, 'T', 'M');
    $this->SetFont('helvetica', '', 9);
    // Add the header string (address)
    $this->SetXY(48, 17); // Adjust Y position for the second line
    $this->Cell(0, 10, 'Jl. Keputih Tegal Nomor 52, Keputih, Sukolilo Kota Surabaya Jawa Timur', 0, 1, 'L', 0, '', 0, false, 'T', 'M');
  }
}
// Generate the PDF
function createSuratJalan($order, $products)
{
  generateBarcode($order['kode_js']);
  $formattedDate = date('d F Y', strtotime($order['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
  );

  $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();
  $pdf->SetMargins(10, 30, 10);
  $pdf->SetFooterMargin(0);
  $pdf->SetAutoPageBreak(TRUE, 0);

  // Add a page
  $pdf->AddPage();
  // Order details
  $pdf->SetFont('helvetica', '', 9);
  $pdf->Image('storage/barcode_' . $order['kode_js'] . '.png', $centerX, $yPosition, $barcodeWidth, $barcodeHeight, 'PNG');
  $pdf->Ln(7);
  $pdf->Cell(0, 10,   $order['kode_js'], 0, 1, 'C'); // Placeholder for date
  $pdf->SetFont('helvetica', 'B', 12);
  $pdf->Cell(0, 10, 'SURAT JALAN', 0, 1, 'C');

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

  // Adjust the starting position to be 30px (approximately 8mm) lower
  $pdf->SetY(58); // 30px from the top (default margin is 10mm, so 30px ≈ 8mm)

  // Left section: "Kepada"
  $pdf->Cell(40, 5, 'Kepada : ' . $order['customer_name'], 0, 1); // Label
  $pdf->MultiCell(110, 5, $order['address'], 0, 1); // Placeholder for recipient name

  // 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); // Placeholder for date

  $pdf->SetX(120); // Keep the alignment on the right
  $pdf->Cell(18, 5, 'No. SJ', 0, 0); // Label
  $pdf->Cell(0, 5, ': ' . $order['kode_js'], 0, 1); // Placeholder for No. SJ

  $pdf->SetX(120); // Keep the alignment on the right
  $pdf->Cell(18, 5, 'No. Telp', 0, 0); // Label
  $pdf->Cell(0, 5, ': ' . $order['phone'], 0, 1); // Placeholder for phone number

  $pdf->SetX(120); // Keep the alignment on the right
  $pdf->Cell(18, 5, 'No. PO', 0, 0); // Label
  $pdf->Cell(0, 5, ': ' . $order['order_sn'], 0, 1); // Placeholder for No. PO
  // Add product details table

  $pdf->Ln(5); // Add a line break
  $pdf->SetFont('helvetica', 'B', 9);

  // Table header
  $pdf->Cell(83, 5, 'Product Name', 1, 0, 'C'); // Column for Product Name
  $pdf->Cell(70, 5, 'Part Number', 1, 0, 'C'); // Column for Part Number
  $pdf->Cell(17, 5, 'Type Box', 1, 0, 'C'); // Column for Type Box
  $pdf->Cell(10, 5, 'Box', 1, 0, 'C'); // Column for Box
  $pdf->Cell(10, 5, 'Qty', 1, 1, 'C'); // Column for Quantity, move to the next line

  $pdf->SetFont('helvetica', '', 9); // Reset font for table rows
  // Initialize totals
  $total_boxes = 0;
  $total_quantity = 0;
  // Table rows
  foreach ($products as $product) {
    $pdf->SetFont('helvetica', '', 9);
    $pdf->Cell(83, 5, $product['name'], 1, 0, 'C'); // Product Name
    $pdf->SetFont('helvetica', '', 9); // Reset font for table rows
    $pdf->Cell(70, 5, $product['part_number'], 1, 0, 'C'); // Part Number
    $pdf->Cell(17, 5, $product['box_name'], 1, 0, 'C'); // Type Box
    $pdf->Cell(10, 5, $product['box'], 1, 0, 'C'); // Box
    $pdf->Cell(10, 5, number_format($product['quantity'], 0), 1, 1, 'C'); // Quantity, move to the next line
    // Accumulate totals
    $total_boxes += $product['box'];
    $total_quantity += $product['quantity'];
  }


  // Add totals row
  $pdf->SetFont('helvetica', 'B', 9); // Bold font for totals
  $pdf->Cell(170, 5, 'Total', 1, 0, 'C'); // Merge cells for "Total" label
  $pdf->Cell(10, 5, $total_boxes, 1, 0, 'C'); // Total boxes
  $pdf->Cell(10, 5, number_format($total_quantity, 0), 1, 1, 'C'); // Total quantity
  $pdf->Ln(5); // Add a line break (20mm)

  $pdf->SetFont('helvetica', '', 8); // Set font for terms and conditions
  $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); // Add some space after the terms and conditions

  // Set font for signature labels
  $pdf->SetFont('helvetica', '', 9);

  // Gudang
  $pdf->SetX(0); // Set position for Gudang
  $pdf->Cell(70, 5, 'Gudang', 0, 0, 'C'); // Label for Gudang
  $pdf->SetX(80); // Set position for Driver
  $pdf->Cell(50, 5, 'Pengirim', 0, 0, 'C'); // Label for Driver
  $pdf->SetX(150); // Set position for Penerima
  $pdf->Cell(50, 5, 'Penerima', 0, 1, 'C'); // Label for Penerima

  // Add "Tanggal" below each signature box
  $pdf->Ln(30); // Move below the signature boxes
  $pdf->SetX(0); // Position for Gudang "Tanggal"
  $pdf->Cell(70, 10, 'Tanggal: ....................', 0, 0, 'C'); // Tanggal for Gudang
  $pdf->SetX(80); // Position for Driver "Tanggal"
  $pdf->Cell(50, 10, 'Tanggal: ....................', 0, 0, 'C'); // Tanggal for Driver
  $pdf->SetX(150); // Position for Penerima "Tanggal"
  $pdf->Cell(50, 10, 'Tanggal: ....................', 0, 1, 'C'); // Tanggal for Penerima
  // Output the PDF
  $pdf->Output('awb_' . $order['order_sn'] . '.pdf', 'I'); // For viewing in the browser
  return "";

  // return $file_path; // Return file path
}
$order_id = $_GET['order_id']; // Replace with the actual order ID
list($order, $products) = getOrderOfflineDetails($order_id);
$file_path = createSuratJalan($order, $products);

// echo "PDF generated successfully: " . $file_path;