<?php
require_once 'lib/ErrorHandler.php';
register_error_handler();

session_start();

$correlation_id = $GLOBALS['correlation_id']; // Use correlation_id from the global error handler
error_log($correlation_id . ': Bulk print badges request started.');

require_once 'WorkflowEngine.php';
require_once 'lib/tfpdf/font/unifont/ttfonts.php';
define('FPDF_FONTPATH', 'lib/tfpdf/font/');
require_once 'lib/tfpdf/tfpdf.php';

// Authentication check
if (!isset($_SESSION['user_id'])) {
    if (ob_get_length()) ob_end_clean();
    http_response_code(403);
    header('Content-Type: application/json');
    $error_message = 'Brak uprawnień.';
    error_log($correlation_id . ': ' . $error_message);
    echo json_encode(['error' => ['message' => $error_message], 'correlation_id' => $correlation_id]);
    exit;
}

// Input validation
$person_ids = json_decode($_POST['person_ids'] ?? '[]', true);
error_log($correlation_id . ': Received ' . count($person_ids) . ' person_ids.');

if (empty($person_ids)) {
    if (ob_get_length()) ob_end_clean();
    http_response_code(400);
    header('Content-Type: application/json');
    $error_message = 'Nie wybrano żadnych osób.';
    error_log($correlation_id . ': ' . $error_message);
    echo json_encode(['error' => ['message' => $error_message], 'correlation_id' => $correlation_id]);
    exit;
}

$workflowEngine = new WorkflowEngine();
$peopleDetails = $workflowEngine->getPeopleDetails($person_ids);
error_log($correlation_id . ': Fetched ' . count($peopleDetails) . ' rows from database.');

class PDF extends tFPDF
{
    function __construct($orientation='P', $unit='mm', $size='A4')
    {
        parent::__construct($orientation, $unit, $size);
        $this->AddFont('DejaVu','','DejaVuSans.ttf',true);
        $this->AddFont('DejaVu','B','DejaVuSans-Bold.ttf',true);
        $this->SetFont('DejaVu', '', 14);
    }

    function generateBadge($person) {
        $this->AddPage();
        $this->Image('assets/pasted-20260112-081646-4e946aad.png', 0, 0, $this->GetPageWidth(), $this->GetPageHeight());
        $this->SetY(20);
        $this->SetFont('DejaVu', 'B', 12);
        $this->Cell(0, 6, $person['first_name'] . ' ' . $person['last_name'], 0, 1, 'C');
        $this->SetFont('DejaVu', 'B', 8);
        $this->Cell(0, 3, $person['company_name'] ?? 'N/A', 0, 1, 'C');
        $this->SetFont('DejaVu', '', 6);
        $this->Cell(0, 3, $person['industry'] ?? 'N/A', 0, 1, 'C');
        
        $this->SetXY(2.5,13);
        $this->SetFont('DejaVu', 'B', 6);
        $this->Cell(22, 3, $person['bni_group_name'] ?? 'GOŚĆ', 0, 0, 'C');
    }
}

$pdf = new PDF('L', 'mm', array(85, 55));

foreach ($peopleDetails as $person) {
    // No need for converting the entire array, FPDF with iconv handles it.
    $pdf->generateBadge($person);
}

// 2. Generate PDF content as a string
$pdfData = $pdf->Output('S');
error_log($correlation_id . ': PDF data generated. Length: ' . strlen($pdfData) . ' bytes.');
error_log($correlation_id . ': Memory usage: ' . memory_get_usage());

// 3. Validate PDF data
if (empty($pdfData) || !is_string($pdfData)) {
    if (ob_get_length()) ob_end_clean();
    http_response_code(500);
    header('Content-Type: application/json');
    $error_message = 'Failed to generate PDF data.';
    error_log($correlation_id . ': ' . $error_message);
    echo json_encode(['error' => ['message' => $error_message], 'correlation_id' => $correlation_id]);
    exit;
}

// 4. Clean any potential output that occurred before this point
if (ob_get_length()) {
    ob_end_clean();
}

// 5. Send correct headers
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="badges.pdf"');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
header('Content-Length: ' . strlen($pdfData));

// 6. Output the raw PDF data and terminate
echo $pdfData;
exit;