<?php
namespace App\Libraries;

class PdfBatchService
{
    protected $db;
    protected $reportHelper;
    
    public function __construct($db)
    {
        $this->db = $db;
        $this->reportHelper = new ReportHelper($db);
    }
    
    public function generatePdf(string $accessnumber): array
    {
        $sql = "SELECT REPORT_LANG FROM GDC_CMOD.dbo.CM_REQUESTS WHERE ACCESSNUMBER=?";
        $row = $this->db->query($sql, [$accessnumber])->getRowArray();
        $eng = (int) ($row['REPORT_LANG'] ?? 0);
        
        $data = $this->reportHelper->getReportData($accessnumber, $eng);
        $data['eng'] = $eng;
        $data['accessnumber'] = $accessnumber;
        $data['ispdf'] = 1;
        
        $html = view('report/template', $data);
        $filename = $accessnumber . ($eng == 1 ? '_eng' : '') . '.pdf';
        $collectionDate = $data['collectionDate'] ?? '';
        $hostnumber = $data['hostnumber'] ?? '';
        
        try {
            $jobId = $this->postToSpooler($html, $filename, $collectionDate, $accessnumber, $hostnumber);
            
            $sqlCheck = "SELECT COUNT(*) as cnt FROM GDC_CMOD.dbo.AUDIT_REQUESTS 
                         WHERE ACCESSNUMBER = ? AND STEPTYPE IN ('GEN_PDF', 'REGEN_PDF')";
            $result = $this->db->query($sqlCheck, [$accessnumber])->getRowArray();
            
            $stepType = ($result['cnt'] > 0) ? 'REGEN_PDF' : 'GEN_PDF';
            $stepStatus = $eng == 1 ? 'English' : 'Indonesian';
            
            $sqlLog = "INSERT INTO GDC_CMOD.dbo.AUDIT_REQUESTS(ACCESSNUMBER, STEPDATE, STEPTYPE, STEPSTATUS)
                       VALUES (?, GETDATE(), ?, ?)";
            $this->db->query($sqlLog, [$accessnumber, $stepType, $stepStatus]);

            try {
                $oruDir = 'c:\\inetpub\\wwwroot\\spooler_db\\process_oru';
                if (!is_dir($oruDir)) {
                    mkdir($oruDir, 0777, true);
                }

                $oruFile = "$oruDir/$accessnumber.oru";
                $date = date('Y-m-d H:i');
                $status = $data['status'] ?? 'PENDING';
                $file = fopen($oruFile, 'w+');
                fwrite($file, "$accessnumber\r\n$hostnumber\r\n$date\r\n$status\r\n-");
                fclose($file);

                $sqlOruLog = "INSERT INTO GDC_CMOD.dbo.AUDIT_REQUESTS(ACCESSNUMBER, STEPDATE, STEPTYPE, STEPSTATUS)
                              VALUES (?, GETDATE(), 'ORU_FILE', 'Created')";
                $this->db->query($sqlOruLog, [$accessnumber]);
            } catch (\Throwable $e) {
                log_message('error', "ORU file creation failed for $accessnumber: " . $e->getMessage());
            }

            return [
                'success' => true,
                'jobId' => $jobId,
                'lang' => $eng == 1 ? 'English' : 'Indonesian',
                'isRegen' => ($stepType === 'REGEN_PDF')
            ];
        } catch (\Exception $e) {
            log_message('error', "PDF generation failed for $accessnumber: " . $e->getMessage());
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
    
    private function postToSpooler($html, $filename, $collectionDate = '', $accessnumber = '', $hostnumber = '')
    {
        $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 ($collectionDate) {
            $payload['collectionDate'] = $collectionDate;
        }
        
        if ($accessnumber) {
            $payload['accessnumber'] = $accessnumber;
        }
        
        if ($hostnumber) {
            $payload['hostnumber'] = $hostnumber;
        }
        
        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, 3);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        if ($curlError) {
            throw new \Exception('Spooler connection failed: ' . $curlError);
        }
        
        if ($httpCode !== 200) {
            throw new \Exception('Spooler returned HTTP ' . $httpCode);
        }
        
        $data = json_decode($response, true);
        if (!isset($data['jobId'])) {
            throw new \Exception('Invalid spooler response');
        }
        
        return $data['jobId'];
    }
}
