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

session_start();

$correlation_id = $GLOBALS['correlation_id'];
error_log($correlation_id . ': Bulk print attendance list 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 generateAttendanceList($people)
    {
        $this->AddPage();
        
        // Title
        $this->SetFont('DejaVu', 'B', 20);
        $this->Cell(0, 10, 'Lista obecności', 0, 1, 'C');
        $this->Ln(2);

        // Subtitle - Date
        $this->SetFont('DejaVu', '', 10);
        $this->Cell(0, 10, date('Y-m-d H:i'), 0, 1, 'C');
        $this->Ln(10);

        // Table Header
        $this->SetFont('DejaVu', 'B', 12);
        $this->SetFillColor(240, 240, 240);
        $this->Cell($this->GetPageWidth() * 0.7, 10, 'Imię i nazwisko', 1, 0, 'L', true);
        $this->Cell($this->GetPageWidth() * 0.3 - $this->lMargin - $this->rMargin, 10, 'Podpis', 1, 1, 'L', true);

        // Table Body
        $this->SetFont('DejaVu', '', 12);
        foreach ($people as $person) {
            $name = $person['first_name'] . ' ' . $person['last_name'];
            $this->Cell($this->GetPageWidth() * 0.7, 15, $name, 1, 0, 'L');
            $this->Cell($this->GetPageWidth() * 0.3 - $this->lMargin - $this->rMargin, 15, '', 1, 1, 'L');
        }
    }
}

$pdf = new PDF();
$pdf->generateAttendanceList($peopleDetails);

$pdfData = $pdf->Output('S');
error_log($correlation_id . ': PDF data generated. Length: ' . strlen($pdfData) . ' bytes.');

if (empty($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;
}

if (ob_get_length()) {
    ob_end_clean();
}

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

echo $pdfData;
exit;