<?php
defined('BASEPATH') or exit('No direct script access allowed');

require_once(APPPATH . 'libraries/fpdf/fpdf.php');

// =============================================================================
// Custom FPDF: override Footer() agar tampil otomatis di SETIAP halaman
// =============================================================================
class ReceiveOrderJasaFpdf extends FPDF
{
   public $printUsername = '-';
   public $printDate     = '';

   // Properties untuk tabel multiline
   public $widths;
   public $aligns;

   public function __construct($orientation = 'P', $unit = 'mm', $size = 'A4')
   {
      parent::__construct($orientation, $unit, $size);
      // Daftarkan Arial Narrow — file font ada di fpdf/font/Arial_Narrow.php
      $this->AddFont('Arial_Narrow', '',  'Arial_Narrow.php');   // regular
      $this->AddFont('Arial_Narrow', 'B', 'Arial_Narrow_B.php'); // bold (Liberation Sans Narrow Bold)
   }

   public function SetWidths($w)
   {
      $this->widths = $w;
   }

   public function SetAligns($a)
   {
      $this->aligns = $a;
   }

   public function Row($data, $fill = false, $h = 6)
   {
      // Hitung tinggi maksimum baris berdasarkan multiline
      $nb = 0;
      for ($i = 0; $i < count($data); $i++) {
         $nb = max($nb, $this->NbLines($this->widths[$i], $data[$i]));
      }
      $rowH = $h * $nb;

      // Cek apakah perlu ganti halaman secara otomatis
      $this->CheckPageBreak($rowH);

      // Gambar cell pada baris
      for ($i = 0; $i < count($data); $i++) {
         $w = $this->widths[$i];
         $a = isset($this->aligns[$i]) ? $this->aligns[$i] : 'L';

         $x = $this->GetX();
         $y = $this->GetY();

         // Gambar border dan background
         $this->Rect($x, $y, $w, $rowH, $fill ? 'DF' : 'D');
         // Tulis teks menggunakan MultiCell
         $this->MultiCell($w, $h, $data[$i], 0, $a);
         // Geser posisi X ke kanan untuk cell berikutnya
         $this->SetXY($x + $w, $y);
      }
      // Pindah baris
      $this->Ln($rowH);
   }

   public function CheckPageBreak($h)
   {
      // Jika tinggi baris melewati batas, buat halaman baru
      if ($this->GetY() + $h > $this->PageBreakTrigger) {
         $this->AddPage($this->CurOrientation);
      }
   }

   public function NbLines($w, $txt)
   {
      // Menghitung jumlah baris yang akan dihasilkan oleh MultiCell
      $cw = &$this->CurrentFont['cw'];
      if ($w == 0) {
         $w = $this->w - $this->rMargin - $this->x;
      }
      $wmax = ($w - 2 * $this->cMargin) * 1000 / $this->FontSize;
      $s    = str_replace("\r", '', $txt);
      $nb   = strlen($s);
      if ($nb > 0 && $s[$nb - 1] == "\n") {
         $nb--;
      }
      $sep = -1;
      $i   = 0;
      $j   = 0;
      $l   = 0;
      $nl  = 1;
      while ($i < $nb) {
         $c = $s[$i];
         if ($c == "\n") {
            $i++;
            $sep = -1;
            $j   = $i;
            $l   = 0;
            $nl++;
            continue;
         }
         if ($c == ' ') {
            $sep = $i;
         }
         $l += $cw[$c];
         if ($l > $wmax) {
            if ($sep == -1) {
               if ($i == $j) {
                  $i++;
               }
            } else {
               $i   = $sep + 1;
            }
            $sep = -1;
            $j   = $i;
            $l   = 0;
            $nl++;
         } else {
            $i++;
         }
      }
      return $nl;
   }

   public function Footer()
   {
      $pageW = $this->GetPageWidth() - 30; // sama dengan margin 15+15

      // ── Posisi: 20mm dari bawah halaman ──────────────────────────────────
      $this->SetY(-20);

      // ── Baris 1: Print Oleh (kiri) | Nomor Halaman (tengah) ───────────────
      $colSide   = ($pageW - 40) / 2;
      $colCenter = 40;

      $this->SetFont('Arial_Narrow', '', 7);
      $this->Cell($colSide,   4, 'Print Oleh : ' . $this->printUsername, 0, 0, 'L');
      $this->Cell($colCenter, 4, $this->PageNo() . ' / {nb}',            0, 0, 'C');
      $this->Cell($colSide,   4, '',                                      0, 1, 'R');

      // ── Baris 2: Tgl Print (kiri) ──────────────────────────────────────────
      $this->SetFont('Arial_Narrow', '', 7);
      $this->Cell($colSide, 4, 'Tgl Print   : ' . $this->printDate, 0, 0, 'L');
      $this->Cell($colCenter + $colSide, 4, '', 0, 1, 'L');
   }
}

// =============================================================================
// Controller
// =============================================================================
class Rpt_receive_order_jasa extends MY_Controller
{
   // ── Properti bersama antar fungsi PDF ─────────────────────────────────────
   /** @var ReceiveOrderJasaFpdf */
   private $_pdf;
   private $_pageW;
   private $_header_data;
   private $_username;

   public function __construct()
   {
      parent::__construct();
   }

   public function index()
   {
      echo "Receive Order Jasa Report API";
   }

   // =========================================================================
   // ENDPOINT: pdf
   // GET/POST: id (ReceiveOrderPoID), username (opsional)
   // =========================================================================
   public function pdf()
   {
      try {
         $id       = intval($this->input->get_post('id'));
         $username = trim($this->input->get_post('username') ?? '');

         if ($id <= 0) {
            $this->sys_error("ID tidak valid");
            exit;
         }

         // ── Ambil data header & detail dari DB ────────────────────────────
         $header  = $this->_get_header($id);
         $details = $this->_get_detail($id);

         // ── Inisialisasi FPDF custom ──────────────────────────────────────
         $this->_pdf                  = new ReceiveOrderJasaFpdf('P', 'mm', 'A4');
         $this->_pdf->printUsername   = $username !== '' ? $username : '-';
         $this->_pdf->printDate       = date('d-m-Y H:i:s');
         $this->_pageW                = $this->_pdf->GetPageWidth() - 30;
         $this->_header_data          = $header;
         $this->_username             = $this->_pdf->printUsername;

         $this->_pdf->AliasNbPages();                 // aktifkan alias total halaman
         $this->_pdf->SetMargins(15, 15, 15);
         $this->_pdf->SetAutoPageBreak(true, 22);     // 22mm ruang footer di bawah
         $this->_pdf->AddPage();

         // ── Susun isi halaman ─────────────────────────────────────────────
         $this->_pdf_header();
         $this->_pdf_data($details);
         $this->_pdf_inspeksi($details);
         $this->_pdf_terms();

         // ── Output ────────────────────────────────────────────────────────
         $filename = 'RO_JASA_' . str_replace('/', '-', $header['ReceiveOrderPoNumber']) . '.pdf';
         header('Content-Type: application/pdf');
         header('Content-Disposition: inline; filename="' . $filename . '"');
         header('Cache-Control: private, max-age=0, must-revalidate');
         header('Pragma: public');
         echo $this->_pdf->Output('S');
      } catch (Exception $exc) {
         $this->sys_error($exc->getMessage());
      }
   }

   // =========================================================================
   // DATABASE: Ambil data header
   // =========================================================================
   private function _get_header($id)
   {
      $sql = "
         SELECT 
            ro.ReceiveOrderPoID,
            ro.ReceiveOrderPoNumber,
            ro.ReceiveOrderPoIDate,
            ro.ReceiveOrderPoRefNumber,
            ro.ReceiveOrderPoNote,
            ro.ReceiveOrderPoConfirmed,
            sup.SupplierName,
            sup.SupplierAddress,
            sup.SupplierPhone,
            b.M_BranchName,
            b.M_BranchAddress,
            po.PurchaseOrderNumber,
            kj.T_KontrakJasaJenisKontrak AS JenisKontrak,
            kj.T_KontrakJasaStartDate AS StartDate,
            kj.T_KontrakJasaEndDate AS EndDate,
            kj.T_KontrakJasaJumlahPI AS JumlahPI,
            kj.T_KontrakJasaUsedCount AS UsedCount
         FROM receive_order_po ro
         JOIN receive_order_po_detail rod ON rod.ReceiveOrderPoDetailReceiveOrderPoID = ro.ReceiveOrderPoID
            AND rod.ReceiveOrderPoDetailIsActive = 'Y'
         LEFT JOIN purchase_order po ON po.PurchaseOrderID = rod.ReceiveOrderPoDetailPurchaseOrderID
         LEFT JOIN supplier sup ON sup.SupplierID = ro.ReceiveOrderPoSupplierID
         LEFT JOIN t_kontrak_jasa kj ON kj.T_KontrakJasaPurchaseOrderID = rod.ReceiveOrderPoDetailPurchaseOrderID
            AND kj.T_KontrakJasaM_BranchCode = ro.ReceiveOrderPoM_BranchCode
            AND kj.T_KontrakJasaIsActive = 'Y'
         LEFT JOIN m_branch b ON b.M_BranchCode = ro.ReceiveOrderPoM_BranchCode
         WHERE ro.ReceiveOrderPoIsActive = 'Y'
           AND ro.ReceiveOrderPoID = ?
         LIMIT 1
      ";
      $qry = $this->db->query($sql, array($id));
      if (!$qry || $qry->num_rows() === 0) {
         $this->sys_error("Data Receive Order Jasa tidak ditemukan");
         exit;
      }
      return $qry->row_array();
   }

   // =========================================================================
   // DATABASE: Ambil data detail
   // =========================================================================
   private function _get_detail($id)
   {
      $sql = "
         SELECT 
            rod.ReceiveOrderPoDetailID,
            rod.ReceiveOrderPoDetailQty AS Qty,
            rod.ReceiveOrderPoDetailPrice AS Price,
            (rod.ReceiveOrderPoDetailQty * rod.ReceiveOrderPoDetailPrice) AS TotalPrice,
            item.M_ItemCode,
            item.M_ItemDesc,
            iu.ItemUnitName,
            iu.ItemUnitCode,
            insp.OrderJasaInspeksiHasilPengerjaan AS HasilPengerjaan,
            insp.OrderJasaInspeksiCatatanPengerjaan AS CatatanPengerjaan,
            insp.OrderJasaInspeksiKesimpulan AS Kesimpulan,
            insp.OrderJasaInspeksiCatatan AS CatatanKesimpulan,
            insp.OrderJasaInspeksiPetugasPengerjaan AS Pekerja,
            uP.M_UserUsername AS PemeriksaName
         FROM receive_order_po_detail rod
         JOIN m_item item ON item.M_ItemID = rod.ReceiveOrderPoItemID
            AND item.M_ItemIsActive = 'Y'
         LEFT JOIN itemunit iu ON iu.ItemUnitID = rod.ReceiveOrderPoItemUnitID
            AND iu.ItemUnitIsActive = 'Y'
         LEFT JOIN order_jasa_inspeksi insp ON insp.OrderJasaInspeksiReceiveOrderPoDetailID = rod.ReceiveOrderPoDetailID
            AND insp.OrderJasaInspeksiIsActive = 'Y'
         LEFT JOIN m_user uP ON uP.M_UserID = insp.OrderJasaInspeksiStaffPemeriksaID
         WHERE rod.ReceiveOrderPoDetailIsActive = 'Y'
           AND rod.ReceiveOrderPoDetailReceiveOrderPoID = ?
         ORDER BY rod.ReceiveOrderPoDetailID ASC
      ";
      $qry = $this->db->query($sql, array($id));
      return $qry ? $qry->result_array() : array();
   }

   // =========================================================================
   // PDF SECTION: Header — Judul + Informasi Dokumen (2 kolom)
   // =========================================================================
   private function _pdf_header()
   {
      $pdf    = $this->_pdf;
      $pageW  = $this->_pageW;
      $header = $this->_header_data;

      // ── Judul utama ───────────────────────────────────────────────────────
      $pdf->SetFont('Arial_Narrow', 'B', 14);
      $pdf->Cell($pageW, 8, 'TANDA TERIMA JASA (RECEIVE ORDER SERVICE)', 0, 1, 'L');
      $pdf->SetDrawColor(0, 0, 0);
      $pdf->SetLineWidth(0.5);
      $pdf->Line(15, $pdf->GetY(), 15 + $pageW, $pdf->GetY());
      $pdf->Ln(2);

      $startY = $pdf->GetY();
      $halfW  = $pageW / 2;
      $lblW   = 28;
      $valW   = $halfW - $lblW - 4;

      // ── Kolom Kiri ────────────────────────────────────────────────────────
      $pdf->SetY($startY);

      // Format Jenis Kontrak
      $jenisKontrak = '-';
      if (!empty($header['JenisKontrak'])) {
         $jenisKontrak = ($header['JenisKontrak'] === 'once') ? 'Sekali Bayar (Once)' : 'Berkala (Recurring)';
      }

      // Periode kontrak
      $periodeJasa = '-';
      if (!empty($header['StartDate']) && $header['StartDate'] !== '0000-00-00') {
         $periodeJasa = $this->_fmt_date($header['StartDate']) . ' s/d ' . $this->_fmt_date($header['EndDate']);
      }

      // Termin / usedcount
      $terminInfo = '-';
      if (intval($header['JumlahPI'] ?? 0) > 0) {
         $terminInfo = "Termin ke-" . ($header['UsedCount'] ?? 0) . " dari " . $header['JumlahPI'];
      }

      $leftItems = array(
         array('Nomor',      $header['ReceiveOrderPoNumber'], true),
         array('Tanggal',    $this->_fmt_date($header['ReceiveOrderPoIDate']), false),
         array('Cabang',         $header['M_BranchName'] ?: '-', false),
      );

      foreach ($leftItems as $item) {
         $pdf->SetX(15);
         $pdf->SetFont('Arial_Narrow', '', 9);
         $pdf->Cell($lblW, 5, $item[0], 0, 0, 'L');
         $pdf->Cell(4,    5, ':', 0, 0, 'C');
         if ($item[2]) {
            $pdf->SetFont('Arial_Narrow', 'B', 9);
         } else {
            $pdf->SetFont('Arial_Narrow', '', 9);
         }
         $pdf->Cell($valW, 5, $item[1], 0, 1, 'L');
      }

      // Keterangan / Note langsung di bawah (tanpa spasi vertikal)
      if (!empty($header['ReceiveOrderPoNote'])) {
         $pdf->SetX(15);
         $pdf->SetFont('Arial_Narrow', '', 9);
         $pdf->Cell($lblW, 5, 'Keterangan', 0, 0, 'L');
         $pdf->Cell(4,    5, ':', 0, 0, 'C');
         $pdf->MultiCell($valW, 5, $header['ReceiveOrderPoNote'], 0, 'L');
      }
      $leftY = $pdf->GetY();

      // ── Kolom Kanan ───────────────────────────────────────────────────────
      $pdf->SetY($startY);
      $rightX = 15 + $halfW;

      $rightItems = array(
         array('Supplier',         $header['SupplierName'] ?: '-'),
         array('Alamat Supplier',  $header['SupplierAddress'] ?: '-'),
         array('Telp Supplier',    $header['SupplierPhone'] ?: '-'),
         array('Jenis Kontrak',    $jenisKontrak),
         array('Periode Jasa',     $periodeJasa),
         array('Termin Realisasi', $terminInfo),
      );

      foreach ($rightItems as $item) {
         $pdf->SetX($rightX);
         $pdf->SetFont('Arial_Narrow', '', 9);
         $pdf->Cell($lblW, 5, $item[0], 0, 0, 'L');
         $pdf->Cell(4,    5, ':', 0, 0, 'C');
         $pdf->SetFont('Arial_Narrow', '', 9);

         if ($item[0] === 'Alamat Supplier') {
            $pdf->MultiCell($valW, 5, $item[1], 0, 'L');
         } else {
            $pdf->Cell($valW, 5, $item[1], 0, 1, 'L');
         }
      }
      $rightY = $pdf->GetY();

      // Posisikan Y ke yang paling bawah + margin
      $pdf->SetY(max($leftY, $rightY) + 4);
   }

   // =========================================================================
   // PDF SECTION: Data — Tabel detail item
   // =========================================================================
   private function _pdf_data($details)
   {
      $pdf    = $this->_pdf;
      $pageW  = $this->_pageW;
      $header = $this->_header_data;

      // ── Definisi kolom: [label, lebar, align] ─────────────────────────────
      // Total lebar = 180mm (A4 portrait: 210 - margin 15 kiri - 15 kanan)
      // 8 + 75 + 20 + 15 + 30 + 32 = 180
      $cols = array(
         array('No',                8,  'C'),
         array('Nama', 75, 'L'),
         array('Unit',              20, 'C'),
         array('Qty',               15, 'C'),
         array('Harga',             30, 'R'),
         array('Total',             32, 'R'),
      );

      // Header kolom
      $pdf->SetLineWidth(0.3); // border medium
      $pdf->SetFont('Arial_Narrow', 'B', 8);
      $pdf->SetFillColor(220, 220, 220);
      $pdf->SetDrawColor(0, 0, 0);
      foreach ($cols as $c) {
         $pdf->Cell($c[1], 7, $c[0], 1, 0, 'C', true);
      }
      $pdf->Ln();

      // Set lebar dan alignment kolom untuk metode Row()
      $pdf->SetWidths(array_column($cols, 1));
      $pdf->SetAligns(array_column($cols, 2));

      // Baris data
      $pdf->SetLineWidth(0.2); // border lebih tipis di data
      $pdf->SetFont('Arial_Narrow', '', 8);
      $pdf->SetFillColor(255, 255, 255);
      $no        = 1;
      $totalPay  = 0;

      foreach ($details as $d) {
         $row_data = array(
            $no,
            $d['M_ItemDesc'] ?: ($d['M_ItemCode'] ?: '-'),
            $d['ItemUnitName'] ?: ($d['ItemUnitCode'] ?: '-'),
            $this->_fmt_qty($d['Qty']),
            $this->_fmt_rp($d['Price']),
            $this->_fmt_rp($d['TotalPrice']),
         );

         $pdf->Row($row_data);

         $totalPay += floatval($d['TotalPrice']);
         $no++;
      }

      // Baris TOTAL
      $span = array_sum(array_column(array_slice($cols, 0, 5), 1));
      $pdf->SetLineWidth(0.3);
      $pdf->SetFont('Arial_Narrow', 'B', 8);
      $pdf->SetFillColor(220, 220, 220);
      $pdf->Cell($span,        7, 'TOTAL',                     1, 0, 'R', true);
      $pdf->Cell($cols[5][1], 7, $this->_fmt_rp($totalPay),    1, 0, 'R', true);
      $pdf->Ln(8);
   }

   // =========================================================================
   // PDF SECTION: Inspeksi & Verifikasi Jasa (Blok Terpisah)
   // =========================================================================
   private function _pdf_inspeksi($details)
   {
      $pdf   = $this->_pdf;
      $pageW = $this->_pageW;

      // Cek apakah ada data inspeksi yang terisi
      $hasInspeksi = false;
      foreach ($details as $d) {
         if (!empty($d['HasilPengerjaan']) || !empty($d['Kesimpulan']) || !empty($d['Pekerja'])) {
            $hasInspeksi = true;
            break;
         }
      }

      if (!$hasInspeksi) {
         return;
      }

      $pdf->Ln(2);
      $pdf->SetFont('Arial_Narrow', 'B', 10);
      $pdf->Cell($pageW, 6, 'DETAIL HASIL INSPEKSI & VERIFIKASI JASA', 0, 1, 'L');

      $pdf->SetLineWidth(0.3);
      $pdf->Line(15, $pdf->GetY(), 15 + $pageW, $pdf->GetY());
      $pdf->Ln(2);

      $no = 1;
      foreach ($details as $d) {
         // Lewati jika item ini tidak memiliki data inspeksi sama sekali
         if (empty($d['HasilPengerjaan']) && empty($d['Kesimpulan']) && empty($d['Pekerja'])) {
            continue;
         }

         $pdf->SetFont('Arial_Narrow', 'B', 9);
         $pdf->Cell($pageW, 5, $no . '. ' . ($d['M_ItemDesc'] ?: ($d['M_ItemCode'] ?: '-')), 0, 1, 'L');

         // Indentasi isi detail inspeksi
         $lblW = 32;
         $valW = $pageW - $lblW - 4;

         $items = array(
            array('Petugas Pengerjaan', $d['Pekerja'] ?: '-'),
            array('Staff Pemeriksa',    $d['PemeriksaName'] ?: '-'),
            array('Hasil Pengerjaan',   $d['HasilPengerjaan'] ?: '-'),
            array('Catatan Pengerjaan', $d['CatatanPengerjaan'] ?: '-'),
            array('Kesimpulan Hasil',   $d['Kesimpulan'] ?: '-'),
            array('Catatan Pemeriksa',  $d['CatatanKesimpulan'] ?: '-'),
         );

         foreach ($items as $item) {
            $pdf->SetX(18); // Indent slightly to the right
            $pdf->SetFont('Arial_Narrow', '', 9);
            $pdf->Cell($lblW, 5, $item[0], 0, 0, 'L');
            $pdf->Cell(4,    5, ':', 0, 0, 'C');
            $pdf->MultiCell($valW, 5, $item[1], 0, 'L');
         }

         $pdf->Ln(2);
         $pdf->SetDrawColor(200, 200, 200);
         $pdf->SetLineWidth(0.1);
         $pdf->Line(15, $pdf->GetY(), 15 + $pageW, $pdf->GetY());
         $pdf->Ln(2);
         $pdf->SetDrawColor(0, 0, 0); // restore black
         $no++;
      }
   }

   // =========================================================================
   // PDF SECTION: Syarat & Ketentuan
   // =========================================================================
   private function _pdf_terms()
   {
      $pdf   = $this->_pdf;
      $pageW = $this->_pageW;

      $terms = array(
         'Penerimaan pengerjaan jasa ini berdasarkan hasil verifikasi/inspeksi petugas di lapangan.',
         'Tanda Terima Jasa (TTJ) ini sah untuk digunakan sebagai lampiran dokumen penagihan vendor.',
         'Jika terdapat komplain/ketidaksesuaian hasil pengerjaan di kemudian hari, harap merujuk ke Berita Acara inspeksi.',
         'Dokumen ini dicetak dan divalidasi secara otomatis melalui sistem ERP.'
      );

      $pdf->SetFont('Arial_Narrow', 'B', 9);
      $pdf->Cell($pageW, 5, 'Syarat & Ketentuan:', 0, 1, 'L');

      $pdf->SetFont('Arial_Narrow', '', 8);
      foreach ($terms as $i => $t) {
         $pdf->Cell(6,            5, ($i + 1) . '.', 0, 0, 'R');
         $pdf->Cell($pageW - 6,   5, $t,             0, 1, 'L');
      }
   }

   // =========================================================================
   // HELPER: Format tampilan
   // =========================================================================
   private function _fmt_date($d)
   {
      if (!$d || $d === '0000-00-00') return '-';
      return date('d-m-Y', strtotime($d));
   }

   private function _fmt_datetime($d)
   {
      if (!$d || $d === '0000-00-00 00:00:00') return '-';
      return date('d-m-Y H:i', strtotime($d));
   }

   private function _fmt_num($n)
   {
      return number_format(floatval($n), 2, ',', '.');
   }

   // format jumlah/qty: tanpa desimal
   private function _fmt_qty($n)
   {
      return number_format(floatval($n), 0, ',', '.');
   }

   private function _fmt_rp($n)
   {
      return 'Rp ' . number_format(floatval($n), 2, ',', '.');
   }
}
