<?php
error_reporting(E_ALL);
ini_set('display_errors', '0');

try {
    if (!isset($_GET['id']) || (int)$_GET['id'] <= 0) {
        header('location: ../purchase_order.php?view');
        exit;
    }
    $po_id = (int)$_GET['id'];

    include_once('../../../classes/manager.class.php');
    include_once('../../../fpdf/fpdf1_po.php');

    $m = new Manager();

    // Project configuration
    $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);

    // Load PO header + items
    $po = PurchaseOrder::GetPurchaseOrderById($po_id);
    if (!$po) {
        header('location: ../purchase_order.php?view&error');
        exit;
    }
    $items = PurchaseOrderItem::GetPurchaseOrderItemsByPO($po_id);

    // helpers
    function dmy($ymd) {
        if (!$ymd) return '';
        $t = strtotime($ymd);
        return $t ? date('d-m-Y', $t) : '';
    }

    // --- PDF setup (PORTRAIT) ---
    $setx  = 10;                 // left padding
    $wPage = 190;                // usable width (210 - 2*10)
    $pdf = new FPDFWithOutWaterMark('P', 'mm', 'A4');  // <-- portrait
    $pdf->SetMargins(0, 0, 0);
    $pdf->SetTitle('Purchase Order - ' . $po->po_code);
    $pdf->AddPage();
    $pdf->Ln();

   
  
  
  
 // --- HEADER SECTION (Logo left, Title + PO box on the right) ---
$yTopHeader = $pdf->GetY();

// 1) Logo on the left
$logoPath = '../../../images/Daniyal-Foods-Logo-1 pvt ltd.png';
$logoH    = 20;
$logoW    = 35;
$logoY    = $yTopHeader + 5;
if (file_exists($logoPath)) {
    $pdf->Image($logoPath, $setx, $logoY, $logoW, 0);
}
$logoBottomY = $logoY + $logoH;

// 2) Right column layout
//    We'll set a fixed box width; the title will start at the same X.
$poBoxW   = 70;              // width of the PO info box (adjust if needed)
$poBoxPad = 3;               // inner padding
$lineH    = 6;               // line height inside box
$titleH   = 8;               // title row height

// Right edge of the usable page:
$rightEdge = $setx + $wPage;

// Left X for both the title and the box (so their left edges align)
$xRightCol = $rightEdge - $poBoxW;

// 3) Title on the FIRST row, left-aligned at $xRightCol
$pdf->SetFont('Arial','B',16);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetXY($xRightCol, $yTopHeader + 8);
$pdf->Cell($poBoxW, $titleH, 'PURCHASE ORDER', 0, 1, 'L'); // <-- left aligned

// 4) PO Date / PO # box on the SECOND row, directly under the title,
//    with left edge == $xRightCol and text left-aligned inside box.
$boxY  = $yTopHeader + 8 + $titleH + 2;   // 2mm gap below title
$boxH  = (2 * $lineH) + (2 * 1);          // height for 2 lines; add tiny breathing room

// draw the box outline (no fill)
$pdf->Rect($xRightCol, $boxY, $poBoxW, $boxH);

// write inside the box
$pdf->SetFont('Arial','B',10);
$pdf->SetTextColor(23, 72, 139);

// PO Date (first line)
$pdf->SetXY($xRightCol + $poBoxPad, $boxY + 1);
$pdf->Cell($poBoxW - 2*$poBoxPad, $lineH, 'PO Date: ' . dmy($po->po_date), 0, 2, 'L');

// PO # (second line)
$pdf->SetXY($xRightCol + $poBoxPad, $boxY + 1 + $lineH);
$pdf->Cell($poBoxW - 2*$poBoxPad, $lineH, 'PO #: ' . $po->po_code, 0, 1, 'L');

// reset text color if you want
$pdf->SetTextColor(0, 0, 0);

// 5) Move below the lower of the logo bottom and the PO box
$afterHeaderY = max($logoBottomY, $boxY + $boxH);
$pdf->SetY($afterHeaderY + 6);


  
  
  
  

    // --- Two vendor boxes (Billed / Shipped) in PORTRAIT ---
    $gap    = 5;    // gap between boxes
    $pad    = 3;    // inner padding
    $titleH = 7;    // title bar height
    $lineH  = 6;    // row height

    $leftW  = ($wPage - $gap) / 2;   // billed width
    $rightW = $leftW;                // shipped width

    // starting coords
    $yStart = $pdf->GetY();
    $xLeft  = $setx;
    $xRight = $setx + $leftW + $gap;

    // helper: estimate MultiCell lines
    if (!function_exists('nbLines')) {
        function nbLines($pdf, $w, $txt){
            $cw = $pdf->CurrentFont['cw'];
            $s = str_replace("\r", '', (string)$txt);
            $nb = strlen($s);
            if ($nb > 0 && $s[$nb-1] == "\n") $nb--;
            $wmax = ($w - 2*$pdf->cMargin) * 1000 / $pdf->FontSize;
            $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] ?? 0);
                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;
        }
    }

    // build strings to allow wrapping
    $companyB = 'Company Name: ' . (($po->billed_company ?? '') ?: '-');
    $contactB = 'Contact: '      . (($po->billed_contact ?? '') ?: '-');
    $phoneB   = 'Phone: '        . (($po->billed_phone ?? '') ?: '-');
    $emailB   = 'Email: '        . (($po->billed_email ?? '') ?: '-');
    $ntnB     = 'NTN: '          . (($po->billed_ntn ?? '') ?: '-');
    $strnB    = 'STRN: '         . (($po->billed_strn ?? '') ?: '-');
    $addrB    = 'Address: '      . (($po->billed_address ?? '') ?: '-');

    $companyS = 'Company Name: ' . (($po->shipped_company ?? '') ?: '-');
    $contactS = 'Contact: '      . (($po->shipped_contact ?? '') ?: '-');
    $phoneS   = 'Phone: '        . (($po->shipped_phone ?? '') ?: '-');
    $emailS   = 'Email: '        . (($po->shipped_email ?? '') ?: '-');
    $ntnS     = 'NTN: '          . (($po->shipped_ntn ?? '') ?: '-');
    $strnS    = 'STRN: '         . (($po->shipped_strn ?? '') ?: '-');
    $addrS    = 'Address: '      . (($po->shipped_address ?? '') ?: '-');

    // compute box height from wrapped lines (company/contact/phone/email wrap too)
    $halfL = ($leftW  - 2*$pad)/2;
    $halfR = ($rightW - 2*$pad)/2;

    $billedLines =
        nbLines($pdf, $leftW  - 2*$pad, $companyB) +
        nbLines($pdf, $leftW  - 2*$pad, $contactB) +
        nbLines($pdf, $leftW  - 2*$pad, $phoneB)   +
        nbLines($pdf, $leftW  - 2*$pad, $emailB)   +
        max(nbLines($pdf, $halfL, $ntnB), nbLines($pdf, $halfL, $strnB)) +
        nbLines($pdf, $leftW  - 2*$pad, $addrB);

    $shippedLines =
        nbLines($pdf, $rightW - 2*$pad, $companyS) +
        nbLines($pdf, $rightW - 2*$pad, $contactS) +
        nbLines($pdf, $rightW - 2*$pad, $phoneS)   +
        nbLines($pdf, $rightW - 2*$pad, $emailS)   +
        max(nbLines($pdf, $halfR, $ntnS), nbLines($pdf, $halfR, $strnS)) +
        nbLines($pdf, $rightW - 2*$pad, $addrS);

    $boxH = $titleH + max($billedLines, $shippedLines) * $lineH + 2;

    // draw rectangles (two boxes only)
    $pdf->Rect($xLeft,  $yStart, $leftW,  $boxH);
    $pdf->Rect($xRight, $yStart, $rightW, $boxH);

    // titles
    $pdf->SetFont('Arial','B',10);
    $pdf->SetXY($xLeft + $pad,  $yStart + 1.5);
    $pdf->Cell($leftW  - 2*$pad, 5, 'Vendor (Billed From)', 0, 1, 'L');

    $pdf->SetXY($xRight + $pad, $yStart + 1.5);
    $pdf->Cell($rightW - 2*$pad, 5, 'Vendor (Shipped From)', 0, 1, 'L');

    // content font
    $pdf->SetFont('Arial','',10);

    // --- helper to write one wrapped field and advance Y ---
    $write = function($x, &$y, $w, $text) use ($pdf, $pad, $lineH) {
        $pdf->SetXY($x + $pad, $y);
        $pdf->MultiCell($w - 2*$pad, $lineH, $text, 0, 'L');
        $y += nbLines($pdf, $w - 2*$pad, $text) * $lineH;
    };

    // -------- Billed --------
    $y = $yStart + $titleH;

    $write($xLeft,  $y, $leftW,  $companyB);
    $write($xLeft,  $y, $leftW,  $contactB);
   // $write($xLeft,  $y, $leftW,  $phoneB);
    $write($xLeft,  $y, $leftW,  $emailB);

   // NTN on its own line
$pdf->SetXY($xLeft + $pad, $y);
$pdf->MultiCell($leftW - 2*$pad, $lineH, $ntnB, 0, 'L');
$y += nbLines($pdf, $leftW - 2*$pad, $ntnB) * $lineH;

// STRN on its own line
$pdf->SetXY($xLeft + $pad, $y);
$pdf->MultiCell($leftW - 2*$pad, $lineH, $strnB, 0, 'L');
$y += nbLines($pdf, $leftW - 2*$pad, $strnB) * $lineH;

    // Address
    $write($xLeft, $y, $leftW, $addrB);

    // -------- Shipped --------
    $y = $yStart + $titleH;

    $write($xRight, $y, $rightW, $companyS);
    $write($xRight, $y, $rightW, $contactS);
    $write($xRight, $y, $rightW, $phoneS);
    $write($xRight, $y, $rightW, $emailS);

// NTN on its own line (shipped)
$pdf->SetXY($xRight + $pad, $y);
$pdf->MultiCell($rightW - 2*$pad, $lineH, $ntnS, 0, 'L');
$y += nbLines($pdf, $rightW - 2*$pad, $ntnS) * $lineH;

// STRN on its own line (shipped)
$pdf->SetXY($xRight + $pad, $y);
$pdf->MultiCell($rightW - 2*$pad, $lineH, $strnS, 0, 'L');
$y += nbLines($pdf, $rightW - 2*$pad, $strnS) * $lineH;


    // Address
    $write($xRight, $y, $rightW, $addrS);

    // move below vendor boxes
    $pdf->SetY($yStart + $boxH + 6);

    // --- Items table ---
    $header = array('S.No', 'Item Detail', 'Unit', 'Quantity');

    // PORTRAIT widths sum to $wPage (190)
    $wr = array(12, 118, 20, 40); // 12+118+20+40 = 190

    // table header
    $pdf->SetX($setx);
    $pdf->SetFillColor(224,235,255);
    $pdf->SetTextColor(0);
    $pdf->SetDrawColor(128,0,0);
    $pdf->SetLineWidth(.3);
    $pdf->SetFont('Arial','B',9);
    for ($i = 0; $i < count($header); $i++) {
        $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
    }
    $pdf->Ln();

    // rows
    $pdf->SetTextColor(0);
    $pdf->SetFont('Arial','',10);

    $totalQty = 0.000;

    // helper to reprint header when near bottom (portrait)
    $limitY = 275; // page bottom threshold in mm
    $printTableHeader = function() use ($pdf, $setx, $header, $wr) {
        $pdf->SetX($setx);
        $pdf->SetFillColor(224,235,255);
        $pdf->SetFont('Arial','B',9);
        for ($i = 0; $i < count($header); $i++) {
            $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
        }
        $pdf->Ln();
        $pdf->SetFont('Arial','',10);
    };

    if ($items) {
        $counter = 1;
        foreach ($items as $row) {
            // page break check
            if ($pdf->GetY() + 7 > $limitY) {
                $pdf->AddPage();
                $printTableHeader();
            }
            $detail = $row->item_name;
            if (!empty($row->item_desc)) $detail .= " - " . $row->item_desc;

            $pdf->SetX($setx);
            $pdf->Cell($wr[0], 7, $counter, 'LRBT', 0, 'C');
            $pdf->Cell($wr[1], 7, (strlen($detail) > 75 ? substr($detail,0,75).'...' : $detail), 'LRBT', 0, 'L');
            $pdf->Cell($wr[2], 7, ($row->unit ?: ''), 'LRBT', 0, 'C');
            $pdf->Cell($wr[3], 7, number_format((float)$row->quantity, 3, '.', ''), 'LRBT', 0, 'R');

            $pdf->Ln();
            $counter++;
            $totalQty += (float)$row->quantity;
        }
    } else {
        $pdf->SetX($setx);
        $pdf->Cell($wr[0], 7, '',             'LRBT', 0, 'C');
        $pdf->Cell($wr[1], 7, 'No items found','LRBT', 0, 'L');
        $pdf->Cell($wr[2], 7, '',             'LRBT', 0, 'C');
        $pdf->Cell($wr[3], 7, '',             'LRBT', 0, 'R');
        $pdf->Ln();
    }

    // Total row
    $pdf->SetX($setx);
    $pdf->SetFont('Arial','B',10);
    $pdf->SetFillColor(224,235,255);
    $pdf->Cell($wr[0], 7, '', 0, 0, 'L');
    $pdf->Cell($wr[1] + $wr[2], 7, 'Total Quantity', 'LRBT', 0, 'R', true);
    $pdf->Cell($wr[3], 7, number_format($totalQty, 3, '.', ''), 'LRBT', 0, 'R', true);
    $pdf->Ln();

    // --- Notes (full width), then Remarks UNDER Notes ---
    $pdf->Ln(4);

    // NOTES
    $notes = [
        'Make sure to send invoice along with the stock',
        'Purchase order should be attached with the delivery challan',
        'Deliver the stock within working hours i.e. 10 am - 5 pm',
        'No delivery will be entertained after 5 pm.',
        'Sunday is off.'
    ];
    $pdf->SetFont('Arial','B',10);
    $pdf->SetFillColor(224,235,240);
    $pdf->SetX($setx);
    $pdf->Cell($wPage, 7, 'Note:', 1, 1, 'L', true);

    $noteText = '';
    foreach ($notes as $i => $line) { $noteText .= ($i+1).'. '.$line."\n"; }

    $pdf->SetFont('Arial','',10);
    $pdf->SetX($setx);
    $pdf->MultiCell($wPage, 6, $noteText, 1, 'L');

    // REMARKS (directly under Notes)
    $remarksText = trim((string)$po->remarks) !== '' ? (string)$po->remarks : '-';

    $pdf->SetFont('Arial','B',10);
    $pdf->SetFillColor(224,235,240);
    $pdf->SetX($setx);
    $pdf->Cell($wPage, 7, 'Remarks', 1, 1, 'L', true);

    $pdf->SetFont('Arial','',10);
    $pdf->SetX($setx);
    $pdf->MultiCell($wPage, 6, $remarksText, 1, 'L');

    // --- Created By (one line below, right aligned) ---
    $pdf->SetX($setx);
    $pdf->SetFont('Arial','',10);
    $pdf->Cell($wPage, 7, 'Created by: ' . $po->created_by_name, 0, 1, 'R');
  
 


    $pdf->Output(); // default 'I'
    if (ob_get_level() > 0) { ob_end_flush(); }
    exit;

} catch (Exception $e) {
    echo $e->getMessage();
}
