<?php
// generate_pedido_pdf.php
header('Content-Type: application/json');
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
require_once __DIR__ . '/../includes/session_control.php';
require_once __DIR__ . '/../cotizaciones/api/_node.php';

$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();

use setasign\Fpdi\Tcpdf\Fpdi;

require_once('../vendor/tecnickcom/tcpdf/tcpdf.php');
require_once('../vendor/setasign/fpdi/src/autoload.php');

$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$id) {
    echo json_encode(['success' => false, 'error' => 'ID inválido']);
    exit;
}

// Encabezado desde Node
$hdrRes = cpn_node_request('GET', $base . '/api/ordenes/pedidos/' . urlencode((string)$id), $token, null);
if (!isset($hdrRes['ok']) || $hdrRes['ok'] !== true) {
    $msg = $hdrRes['error']['message'] ?? 'Pedido no encontrado';
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}
$hdr = $hdrRes['data'] ?? [];

// Detalle desde Node
$detRes = cpn_node_request('GET', $base . '/api/ordenes/pedidos/' . urlencode((string)$id) . '/detalle', $token, null);
if (!isset($detRes['ok']) || $detRes['ok'] !== true) {
    $msg = $detRes['error']['message'] ?? 'Error cargando detalle';
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}
$items = $detRes['data']['items'] ?? [];

// Totales desde Node (Node ejecuta el procedimiento)
$totRes = cpn_node_request('GET', $base . '/api/ordenes/pedidos/' . urlencode((string)$id) . '/resumen', $token, null);
if (!isset($totRes['ok']) || $totRes['ok'] !== true) {
    $msg = $totRes['error']['message'] ?? 'Error cargando totales';
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}
$tot = $totRes['data'] ?? [];

// Crear PDF
$pdf = new Fpdi('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->setPrintHeader(false);
$pdf->SetCreator('Compranet');
$pdf->SetAuthor('COMPRANET COMERCIO ELECTRÓNICO S.A.S.');
$pdf->SetTitle("Orden de Compra No. $id");
$pdf->SetMargins(10, 50, 10);
$pdf->SetAutoPageBreak(true, 20);
$pdf->AddPage();

// Logo
$pdf->Image(
    'https://compranet.com.co/wp-content/uploads/2024/05/compranet-comercio-electronico-logo-16146077571.png',
    15,
    10,
    40
);

// Encabezado izquierdo
$pdf->SetFont('helvetica', 'B', 12);
$y0 = 20;
$pdf->SetXY(15, $y0);
$pdf->Cell(0, 6, 'COMPRANET COMERCIO ELECTRÓNICO S.A.S.', 0, 1);
$pdf->SetFont('', '', 9);
$pdf->SetX(15);
$pdf->Cell(0, 5, 'NIT: 900.615.333-2', 0, 1);
$pdf->SetX(15);
$pdf->Cell(0, 5, 'Calle 69B No 105F-68 Piso 1 PBX 7587999', 0, 1);
$pdf->SetX(15);
$pdf->Cell(0, 5, 'Barrio San Basilio Bogota D.C.', 0, 1);

// Encabezado derecho
$pdf->SetXY(-60, $y0);
$pdf->SetFont('helvetica', 'B', 14);
$pdf->Cell(0, 6, "ORDEN DE COMPRA No $id", 0, 1, 'R');
$pdf->SetFont('', '', 9);
$pdf->SetX(-60);
$pdf->Cell(0, 5, 'Fecha: ' . date('d/m/Y', strtotime($hdr['fechaSolicitud'] ?? 'now')), 0, 1, 'R');
$pdf->SetX(-60);
$pdf->Cell(0, 5, 'A nombre de: ' . ($hdr['Area'] ?? ''), 0, 1, 'R');

// Espacio antes de tabla
$pdf->Ln(6);

// Preparar estilos de tabla
$pdf->SetFillColor(240, 240, 240);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetDrawColor(200, 200, 200);
$pdf->SetFont('helvetica', 'B', 8);

// Columnas
$cols = [
    'Código'      => 28,
    'Imagen'      => 20,
    'Descripción' => 60,
    'Cant'        => 10,
    'Vr Unit'     => 18,
    'IVA'         => 8,
    'Subtotal'    => 20,
    'Total'       => 18,
];

// Cabecera
$pdf->SetX(10);
foreach ($cols as $txt => $w) {
    if ($txt === 'Descripción') {
        $pdf->MultiCell($w, 7, $txt, 1, 'C', 1, 0, null, null, true, 0, false, true, 7, 'M');
    } else {
        $pdf->Cell($w, 7, $txt, 1, 0, 'C', 1);
    }
}
$pdf->Ln();
$pdf->SetFont('', '', 8);

// Filas de detalle
foreach ($items as $row) {
    $pdf->SetX(10);
    // Código
    $pdf->Cell(28, 20, $row['referenciaProveedor'] ?? '', 1);

    // Imagen
    $x = $pdf->GetX();
    $y = $pdf->GetY();
    $pdf->Cell(20, 20, '', 1);
    if (!empty($row['linkImagen'])) {
        $img = str_ireplace('J:/', 'https://sistema.compranet.com.co/', $row['linkImagen']);
        $pdf->Image($img, $x + 1, $y + 1, 18, 0);
    }

    // Descripción
    $pdf->SetXY($x + 20, $y);
    $pdf->MultiCell(60, 20, ($row['producto'] ?? '') . ' – ' . ($row['color'] ?? ''), 1, 'L', 0, 0, null, null, true);

    // Cantidad sin decimales
    $pdf->Cell(10, 20, number_format((float)($row['cantidad'] ?? 0), 0, ',', '.'), 1, 0, 'C');

    // Vr Unit más estrecho
    $pdf->Cell(18, 20, '$ ' . number_format((float)($row['precioCompra'] ?? 0), 0, ',', '.'), 1, 0, 'R');

    // IVA %
    $pdf->Cell(8, 20, round(((float)($row['porcentajeImpuesto'] ?? 0)) * 100) . '%', 1, 0, 'C');

    // Subtotal
    $sub = ((float)($row['cantidad'] ?? 0)) * ((float)($row['precioCompra'] ?? 0));
    $pdf->Cell(20, 20, '$ ' . number_format($sub, 0, ',', '.'), 1, 0, 'R');

    // Total
    $ivaVal   = round($sub * ((float)($row['porcentajeImpuesto'] ?? 0)));
    $totalVal = $sub + $ivaVal;
    $pdf->Cell(18, 20, '$ ' . number_format($totalVal, 0, ',', '.'), 1, 0, 'R');

    $pdf->Ln();
}

// Totales finales (sin deducciones)
$pdf->Ln(4);
$pdf->SetFont('', 'B', 9);
$pdf->SetX(10);
$pdf->Cell(136, 6, '', 0, 0);
$pdf->Cell(25, 6, 'Subtotal:', 0, 0, 'R');
$pdf->Cell(20, 6, '$ ' . number_format((float)($tot['subtotal'] ?? 0), 0, ',', '.'), 1, 1, 'R');

$pdf->SetX(10);
$pdf->Cell(136, 6, '', 0, 0);
$pdf->Cell(25, 6, 'Impuestos:', 0, 0, 'R');
$pdf->Cell(20, 6, '$ ' . number_format((float)($tot['impuestos'] ?? 0), 0, ',', '.'), 1, 1, 'R');

$pdf->SetX(10);
$pdf->Cell(136, 6, '', 0, 0);
$pdf->Cell(25, 6, 'Total:', 0, 0, 'R');
$pdf->Cell(20, 6, '$ ' . number_format((float)($tot['total'] ?? 0), 0, ',', '.'), 1, 1, 'R');

// Pie de página manual
$totalPages = $pdf->getNumPages();
for ($p = 1; $p <= $totalPages; $p++) {
    $pdf->setPage($p);
    $pdf->SetFont('helvetica', 'I', 8);
    $pdf->SetY(-30);
    $pdf->Cell(0, 10, 'Página ' . $p . ' de ' . $totalPages, 0, 0, 'C');
}

// Guardar archivo
$dir = __DIR__ . '/archivos/';
if (!is_dir($dir)) mkdir($dir, 0755, true);
$file = "Orden{$id}.pdf";
$path = $dir . $file;
$pdf->Output($path, 'F');

$url = "https://sistema.compranet.com.co/ordenes/archivos/{$file}";
echo json_encode(['success' => true, 'filename' => $file, 'url' => $url]);
