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

// Function to get the order details for endorse
function getEndorseDetails($endorse_id)
{
  global $db;
  // Query the endorse table
  $endorse_query = "SELECT * FROM endorse WHERE id = $endorse_id";
  $endorse_result = $db->query($endorse_query);

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

  $endorse = $endorse_result->fetch_assoc();

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

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

  return [$endorse, $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 endorse
function createSuratJalan($endorse, $products)
{
  // Format the date to Indonesian language
  $formattedDate = date('d F Y', strtotime($endorse['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
  );

  // Barcode generation (ensure barcode image is generated elsewhere)
  generateBarcode($endorse['endorse_sj']);

  // A4 page width in mm
  $pageWidth = 210;
  $barcodeWidth = 80; // Barcode width in mm
  $barcodeHeight = 10; // Barcode height in mm
  $yPosition = 30; // Vertical position for barcode
  $centerX = ($pageWidth - $barcodeWidth) / 2; // Center barcode horizontally

  // Create an instance of TCPDF
  $pdf = new CustomPDF($endorse['brand']);
  $pdf->SetMargins(10, 30, 10);
  $pdf->SetFooterMargin(0);
  $pdf->SetAutoPageBreak(TRUE, 0);

  $pdf->AddPage();
  $pdf->SetFont('helvetica', '', 9);
  // Add barcode image (assuming barcode is generated separately)
  $pdf->Image('storage/barcode_' . $endorse['endorse_sj'] . '.png', $centerX, $yPosition, $barcodeWidth, $barcodeHeight, 'PNG');
  $pdf->Ln(7);
  $pdf->Cell(0, 10,   $endorse['endorse_sj'], 0, 1, 'C'); // endorse SN
  $pdf->SetFont('helvetica', 'B', 12);
  $pdf->Cell(0, 10, 'SURAT JALAN', 0, 1, 'C');

  // Add order details
  $pdf->SetFont('helvetica', '', 9);
  $pdf->SetY(58); // Starting position for content

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

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

  $pdf->SetX(120);
  $pdf->Cell(18, 5, 'No. endors', 0, 0);
  $pdf->Cell(0, 5, ': ' . $endorse['endorse_sn'], 0, 1);

  $pdf->SetX(120);
  $pdf->Cell(18, 5, 'No. Telp', 0, 0);
  $pdf->Cell(0, 5, ': ' . $endorse['phone'], 0, 1);

  // Product details table
  $pdf->Ln(5);
  $pdf->SetFont('helvetica', 'B', 9);
  $pdf->Cell(83, 5, 'Product Name', 1, 0, 'C');
  $pdf->Cell(97, 5, 'Part Number', 1, 0, 'C');
  $pdf->Cell(10, 5, 'Qty', 1, 1, 'C');

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

  // Product rows
  foreach ($products as $product) {
    $pdf->Cell(83, 5, $product['name'], 1, 0, 'C');
    $pdf->Cell(97, 5, $product['part_number'], 1, 0, 'C');
    $pdf->Cell(10, 5, number_format($product['quantity'], 0), 1, 1, 'C');
    $total_quantity += $product['quantity'];
  }

  // Add total quantity row
  $pdf->SetFont('helvetica', 'B', 9);
  $pdf->Cell(180, 5, 'Total', 1, 0, 'C');
  $pdf->Cell(10, 5, number_format($total_quantity, 0), 1, 1, 'C');

  $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);

  // Signature section
  $pdf->Ln(5);
  $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');

  // Signature date section
  $pdf->Ln(30);
  $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('endorse_surat_jalan_' . $endorse['endorse_sn'] . '.pdf', 'I');
}


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