<?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 '../db/db.php';

use setasign\Fpdi\Tcpdf\Fpdi;

$cotizacionId = $_POST['cotizacionId'];
$templateType = $_POST['templateType']; // Obtener el tipo de plantilla

// Fetch the total number of items in the cotizacion and email
$sql_items_count = "SELECT tb_cotizacion_detalle.idCotizacion, tb_cotizacion_detalle.id, tb_usuarios.email
FROM (tb_cotizacion_detalle INNER JOIN tb_cotizaciones ON tb_cotizacion_detalle.idCotizacion = tb_cotizaciones.id) INNER JOIN tb_usuarios ON tb_cotizaciones.idUsuario = tb_usuarios.id
WHERE tb_cotizacion_detalle.idCotizacion = ?";
$stmt_items_count = $conn->prepare($sql_items_count);
$stmt_items_count->bind_param("i", $cotizacionId);
$stmt_items_count->execute();
$result_items_count = $stmt_items_count->get_result();
$cotizacion = $result_items_count->fetch_assoc();
$total_items = $result_items_count->num_rows;

if ($total_items <= 0) {
    die('No items found for the given cotizacion');
}

// 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) {
    $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
    curl_setopt($ch, CURLOPT_HTTPHEADER, 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"
    ));
    $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 ($http_code !== 200) {
        die("Failed to fetch content from $url (final URL: $final_url) with HTTP code $http_code. cURL error: $curl_error");
    }

    return $data;
}

// 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
    $image_content = fetch_image($link);

    if ($image_content === false) {
        die("Failed to fetch content from $link");
    }

    // Save the image content to a temporary file
    $temp_image_path = tempnam(sys_get_temp_dir(), 'cotizacion') . '.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 = 'E:/www/sistema.compranet.com.co/public/cotizaciones/templates/Anexo1.pdf';
$anexo2Path = 'E:/www/sistema.compranet.com.co/public/cotizaciones/templates/Anexo2.pdf'; // Path to the uploaded 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
addPdfToDocument($pdf, $anexo1Path, $targetWidth, $targetHeight);
addPdfToDocument($pdf, $anexo2Path, $targetWidth, $targetHeight);

// Output PDF to a file
$pdf_file_name = 'cotizacion_' . $cotizacionId . '.pdf';
$pdf_file_path = 'E:/www/sistema.compranet.com.co/public/cotizaciones/clientes/' . $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;

echo json_encode(['success' => true, 'pdf' => $pdf_file_path, 'pdfurl' => $pdf_url,'email' => $cotizacion['email']]);

$conn->close();
?>
