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

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('../../../classes/PHPMailer/PHPMailerAutoload.php');
    include_once('../../../fpdf/fpdf1.php');

    $m = new Manager();

    // Project configuration (match your pattern)
    $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 (keep simple, like your sample) ---
    function dmy($ymd) {
        if (!$ymd) return '';
        $t = strtotime($ymd);
        return $t ? date('d-m-Y', $t) : '';
    }

    // --- PDF setup (as per your sample) ---
    $font  = 10;
    $setx  = 10;       // left padding like your report
    $wPage = 280;      // usable width in landscape A4 with your margins
    $pdf = new FPDFWithOutWaterMark('L', 'mm', 'A4');
    $pdf->SetMargins(0, 0, 0);
    $pdf->SetTitle('Purchase Order - ' . $po->po_code);
    $pdf->AddPage();
    $pdf->Ln();

    // Header band (match style)
    $pdf->SetFont('Arial', 'B', 16);
    $pdf->Cell(0, 8, PROJECT_NAME, 0, 0, 'C');

    $pdf->SetX($setx);
    $pdf->SetFont('Arial', '', 8);
    $pdf->Cell(0, 8, 'Printed Date: ' . date('d-m-Y h:i A'), 0, 0, 'L');

    $pdf->Ln();
    $pdf->SetFont('Arial', '', 14);
    $pdf->Cell(0, 6, 'Purchase Order', 0, 0, 'C');

    $pdf->Ln();
    $pdf->SetFont('Arial', '', 8);
    $pdf->Cell(0, 4, 'PO#: ' . $po->po_code . '   |   Date: ' . dmy($po->po_date) . '   |   Status: ' . ucfirst($po->status) . '   |   Created By: ' . $po->created_by_name, 0, 0, 'C');

    $pdf->Ln();
    $pdf->Ln();

    // --- Two vendor boxes (Billed From / Shipped From) like simple blocks ---
    // Box widths sum close to $wPage. Split in half with small gap.
    $gap = 5;
    $boxW = ($wPage - $gap); // we will draw two columns manually
    $leftW = ($boxW / 2);
    $rightW = ($boxW / 2);

    $pdf->SetX($setx);
    $pdf->SetFont('Arial','B',10);
    $pdf->Cell($leftW, 7, 'Vendor (Billed From)', 1, 0, 'L');
    $pdf->Cell($gap,   7, '', 0, 0);
    $pdf->Cell($rightW,7, 'Vendor (Shipped From)', 1, 1, 'L');

    // Build lines (simple multi-line like your style)
    $billedLines = [];
    if (!empty($po->billed_company))  $billedLines[] = $po->billed_company;
    if (!empty($po->billed_contact))  $billedLines[] = 'Contact: ' . $po->billed_contact;
    if (!empty($po->billed_phone))    $billedLines[] = 'Phone: '   . $po->billed_phone;
    if (!empty($po->billed_email))    $billedLines[] = 'Email: '   . $po->billed_email;
    if (!empty($po->billed_ntn))      $billedLines[] = 'NTN: '     . $po->billed_ntn;
    if (!empty($po->billed_strn))     $billedLines[] = 'STRN: '    . $po->billed_strn;
    if (!empty($po->billed_address))  $billedLines[] = 'Address: ' . $po->billed_address;

    $shippedLines = [];
    if (!empty($po->shipped_company)) $shippedLines[] = $po->shipped_company;
    if (!empty($po->shipped_contact)) $shippedLines[] = 'Contact: ' . $po->shipped_contact;
    if (!empty($po->shipped_phone))   $shippedLines[] = 'Phone: '   . $po->shipped_phone;
    if (!empty($po->shipped_email))   $shippedLines[] = 'Email: '   . $po->shipped_email;
    if (!empty($po->shipped_ntn))     $shippedLines[] = 'NTN: '     . $po->shipped_ntn;
    if (!empty($po->shipped_strn))    $shippedLines[] = 'STRN: '    . $po->shipped_strn;
    if (!empty($po->shipped_address)) $shippedLines[] = 'Address: ' . $po->shipped_address;

    // Draw both blocks side-by-side (bordered)
    $leftStartY = $pdf->GetY();
    $pdf->SetX($setx);
    $pdf->SetFont('Arial','',10);
    // left block
    $y1 = $pdf->GetY();
    $pdf->MultiCell($leftW, 6, implode("\n", $billedLines) ?: '-', 1, 'L');
    $y2 = $pdf->GetY();

    // right block (same height)
    $pdf->SetXY($setx + $leftW + $gap, $y1);
    $pdf->MultiCell($rightW, 6, implode("\n", $shippedLines) ?: '-', 1, 'L');

    // ensure we are below both boxes
    $pdf->SetY(max($y2, $pdf->GetY()) + 5);

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

    // Widths (sum ~ 280)
    $wr = array(15, 190, 35, 40); // 15+190+35+40 = 280

    // 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
// rows (white background)
$pdf->SetTextColor(0);
$pdf->SetFont('Arial','',10);

$counter = 1;
$counter_pagebreak = 1;
$totalQty = 0.000;

if ($items) {
    foreach ($items as $row) {
        $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'); // no fill param
        $pdf->Cell($wr[1], 7, (strlen($detail) > 95 ? substr($detail,0,95).'...' : $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');

        // page break (reprint colored header on new page)
        if ($counter == 21 || ($counter != 21 && ($counter_pagebreak % 25) == 0)) {
            $counter_pagebreak = 1;
            $pdf->AddPage();
            $pdf->SetX($setx);
            $pdf->SetFont('Arial','B',9);
            $pdf->SetFillColor(224,235,255);
            for ($i = 0; $i < count($header); $i++) {
                $pdf->Cell($wr[$i], 7, $header[$i], 1, 0, 'C', true);
            }
            $pdf->Ln();
            $pdf->SetFont('Arial','',10);
        }

        $pdf->Ln();
        $counter++;
        $counter_pagebreak++;
        $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 (bold + same fill color as header)
$pdf->SetX($setx);
$pdf->SetFont('Arial','B',10);
$pdf->SetFillColor(224,235,255);   // same as header

// keep first (S.No) cell empty like before (no border/fill)
$pdf->Cell($wr[0], 7, '', 0, 0, 'L');

// label + value cells with border and filled background
$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);


    // Remarks
    if (!empty($po->remarks)) {
        $pdf->Ln();
        $pdf->Ln();
        $pdf->SetX($setx);
        $pdf->SetFont('Arial','B',10);
        $pdf->Cell($wPage, 7, 'Remarks', 1, 1, 'L');
        $pdf->SetX($setx);
        $pdf->SetFont('Arial','',10);
        $pdf->MultiCell($wPage, 7, $po->remarks, 1, 'L');
    }

    // Footer signature area (optional; commented like your sample)
    /*
    $pdf->Ln();
    $pdf->Ln();
    $pdf->SetX($setx);
    $pdf->SetFont('Arial','',9);
    $pdf->Cell(90, 7, "Authorized Signature", 'T', 0, 'C');
    */

    $pdf->Output(); // default 'I'
    ob_end_flush();
    exit;

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