<?php
require_once('../vendor/tecnickcom/tcpdf/tcpdf.php');
require_once('../vendor/setasign/fpdi/src/autoload.php'); // Autoload for FPDI
include '../includes/session_control.php';
include __DIR__ . '/api/_node.php';
require_once __DIR__ . '/../includes/user_activity_log.php';

header('Content-Type: application/json; charset=utf-8');

use setasign\Fpdi\Tcpdf\Fpdi;

$cotizacionId = $_POST['cotizacionId'] ?? null;
$templateType = $_POST['templateType'] ?? null; // Obtener el tipo de plantilla

$cotizacionId = (int)$cotizacionId;
$templateType = (int)$templateType;
if ($cotizacionId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'cotizacionId inválido']);
    exit;
}
if ($templateType !== 1 && $templateType !== 2) {
    $templateType = 1;
}

// Fetch meta from Node (DB access must be in Node)
$token = cpn_node_token_or_fail();
$base = cpn_node_api_base();
$metaUrl = $base . '/api/cotizaciones/' . $cotizacionId . '/pdf/meta';
$metaResp = cpn_node_request('GET', $metaUrl, $token);
if (!isset($metaResp['ok']) || $metaResp['ok'] !== true) {
    $msg = $metaResp['error']['message'] ?? 'Error consultando meta en Node.';
    http_response_code((int)($metaResp['_http'] ?? 500));
    echo json_encode(['success' => false, 'error' => $msg]);
    exit;
}

$meta = $metaResp['data'] ?? [];
$total_items = (int)($meta['totalItems'] ?? 0);
$emailTo = (string)($meta['email'] ?? '');

if ($total_items <= 0) {
    echo json_encode(['success' => false, 'error' => 'No items found for the given cotizacion']);
    exit;
}

// Determine the number of pages needed (each page can contain up to 9 items)
$items_per_page = 9;
$num_pages = ceil($total_items / $items_per_page);

// Create new PDF document with custom page size (matching the image size)
$pdf = new Fpdi('L', PDF_UNIT, array(1650, 1310), true, 'UTF-8', false); // Página con el tamaño exacto de la imagen

// Set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('COMPRANET COMERCIO ELECTRONICO S.A.S.');
$pdf->SetTitle('Cotizacion No. ' . $cotizacionId);
$pdf->SetSubject('Cotizacion');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// Function to fetch image using cURL
function fetch_image($url, $cookieHeader = '')
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 20); // Limite de redirecciones
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Ignorar problemas de certificado SSL
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Tiempo de espera de 30 segundos
    $headers = array(
        "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
    );
    if ($cookieHeader) {
        $headers[] = 'Cookie: ' . $cookieHeader;
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $data = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $final_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // URL final después de las redirecciones
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($data === false) {
        return [
            'ok' => false,
            'error' => 'cURL error: ' . ($curl_error ?: 'desconocido'),
            'http_code' => $http_code,
            'final_url' => $final_url,
        ];
    }

    if ((int)$http_code !== 200) {
        return [
            'ok' => false,
            'error' => 'HTTP ' . $http_code,
            'http_code' => $http_code,
            'final_url' => $final_url,
        ];
    }

    return [
        'ok' => true,
        'data' => $data,
        'http_code' => $http_code,
        'final_url' => $final_url,
    ];
}

// Ensure cURL requests to formatocotizacion.php share this PHP session
$cookieHeader = '';
if (function_exists('session_id')) {
    $sid = session_id();
    if ($sid) {
        $cookieHeader = 'PHPSESSID=' . $sid;
    }
}

// IMPORTANT: release the session lock before doing internal HTTP calls.
// Otherwise, formatocotizacion.php will block on session_start() and the cURL will timeout.
if (function_exists('session_write_close')) {
    @session_write_close();
}

// Generate each page
for ($page = 0; $page < $num_pages; $page++) {
    $offset = $page * $items_per_page;
    $link = "https://sistema.compranet.com.co/cotizaciones/formatocotizacion.php?id_cotizacion=$cotizacionId&tipo=$templateType&desde=$offset&pag=" . ($page + 1) . "&pags=$num_pages";

    // Fetch the image content from the link using cURL
    $imgResp = fetch_image($link, $cookieHeader);
    if (!is_array($imgResp) || empty($imgResp['ok'])) {
        http_response_code(502);
        echo json_encode([
            'success' => false,
            'error' => 'No se pudo generar la imagen de la página de cotización.',
            'details' => [
                'url' => $link,
                'final_url' => $imgResp['final_url'] ?? null,
                'http_code' => $imgResp['http_code'] ?? null,
                'message' => $imgResp['error'] ?? null,
            ],
        ]);
        exit;
    }

    $image_content = $imgResp['data'];

    // Save the image content to a temporary file
    $tmp = tempnam(sys_get_temp_dir(), 'cotizacion');
    if ($tmp === false) {
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'No se pudo crear archivo temporal.']);
        exit;
    }
    $temp_image_path = $tmp . '.png';
    file_put_contents($temp_image_path, $image_content);

    // Add a page
    $pdf->AddPage();

    // Add the image to the PDF without margins, fitting it exactly to the page size
    $pdf->Image($temp_image_path, 0, 0, 1650, 1275, '', '', '', false, 300, '', false, false, 0, 'L', false);

    // Remove the temporary file
    unlink($temp_image_path);
}

// Add Anexo1.pdf and Anexo2.pdf
$anexo1Path = __DIR__ . '/templates/Anexo1.pdf';
$anexo2Path = __DIR__ . '/templates/Anexo2.pdf';

function addPdfToDocument($pdf, $filePath, $targetWidth, $targetHeight)
{
    $pageCount = $pdf->setSourceFile($filePath);
    for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
        $templateId = $pdf->importPage($pageNo);
        $size = $pdf->getTemplateSize($templateId);
        $scale = min($targetWidth / $size['width'], $targetHeight / $size['height']);
        $width = $size['width'] * $scale;
        $height = $size['height'] * $scale;
        $x = ($targetWidth - $width) / 2;
        $y = ($targetHeight - $height) / 2;
        $pdf->AddPage('L', array($targetWidth, $targetHeight));
        $pdf->useTemplate($templateId, $x, $y, $width, $height, true);
    }
}

// Definir el tamaño objetivo (1650 x 1310 px)
$targetWidth = 1650;
$targetHeight = 1310;

// Agregar los anexos redimensionados
if (file_exists($anexo1Path)) {
    addPdfToDocument($pdf, $anexo1Path, $targetWidth, $targetHeight);
}
if (file_exists($anexo2Path)) {
    addPdfToDocument($pdf, $anexo2Path, $targetWidth, $targetHeight);
}

// Output PDF to a file
// Output PDF to a file (ruta relativa al script)
$outputDir = __DIR__ . '/clientes/';
if (!is_dir($outputDir)) {
    mkdir($outputDir, 0777, true);
}
if (!is_writable($outputDir)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => "La carpeta $outputDir no es escribible"]);
    exit;
}
$pdf_file_name = 'cotizacion_' . $cotizacionId . '.pdf';
$pdf_file_path = $outputDir . $pdf_file_name;
$pdf->Output($pdf_file_path, 'F');



// Crear la URL web
$pdf_url = 'https://sistema.compranet.com.co/cotizaciones/clientes/' . $pdf_file_name;

cpn_activity_log_event(
    'Cotizaciones',
    'cotizaciones.pdf_generate',
    'Generó PDF de la cotización #' . (int)$cotizacionId,
    'cotizacion',
    (int)$cotizacionId,
    ['templateType' => $templateType]
);

echo json_encode(['success' => true, 'pdf' => $pdf_file_path, 'pdfurl' => $pdf_url, 'email' => $emailTo]);

exit;
