<?php
namespace App\Libraries;

class PdfHelper
{
    protected $db;
    
    public function __construct($db)
    {
        $this->db = $db;
    }
    
    public function generatePdf(string $accessnumber, int $eng = 0): string
    {
        $reportHelper = new \App\Libraries\ReportHelper($this->db);
        $data = $reportHelper->getReportData($accessnumber, $eng);
        $data['eng'] = $eng;
        $data['accessnumber'] = $accessnumber;
        $data['ispdf'] = 1;
        
        $html = view('report/template', $data);
        $filename = $accessnumber . ($eng == 1 ? '_eng' : '') . '.pdf';
        
        return $this->postHtmlToSpooler($html, $filename, $accessnumber);
    }
    
    public function postHtmlToSpooler(string $html, string $filename, string $accessnumber = ''): string
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://glenlis:3000/api/pdf/generate');
        curl_setopt($ch, CURLOPT_POST, 1);
        
        $payload = [
            'html' => $html,
            'filename' => $filename
        ];
        
        if ($accessnumber) {
            $payload['accessnumber'] = $accessnumber;
        }
        
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode !== 200) {
            log_message('error', "Spooler API returned HTTP $httpCode");
            throw new \Exception('Failed to queue PDF generation');
        }
        
        $data = json_decode($response, true);
        return $data['jobId'];
    }
}
