<?php
// src/parser.php

class ReportParser {
    private $text;
    private $pdo;
    private $reportId;

    public function __construct(string $text, PDO $pdo, int $reportId) {
        $this->text = $text;
        $this->pdo = $pdo;
        $this->reportId = $reportId;
    }

    public function parseAll() {
        $this->parsePMSBacklog();
        $this->parseOfflineRT1000();
        $this->parseCDRStatus();
        $this->parseWakeupErrors();
        $this->parseESBErrors();
        $this->parseSystemStats();
    }

    // NEW: Centralized check for skipping lines
    private function shouldSkip($line) {
        // Case-insensitive check
        if (stripos($line, 'Test') !== false || stripos($line, 'Cancelled') !== false) {
            return true;
        }
        return false;
    }

    private function parsePMSBacklog() {
        preg_match_all('/PMS Update Backlog - Properties(.*?)(?:Offline RT1000|Room Status|Name display|PS01 Memory|No issues found|$)/is', $this->text, $blocks);
        if (empty($blocks[1])) return;
        foreach ($blocks[1] as $block) {
            $lines = preg_split('/\r?\n/', trim($block));
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '' || stripos($line, 'Property') !== false) continue;
                
                if ($this->shouldSkip($line)) continue; // <--- FILTER ADDED

                if (preg_match('/^(\d+)\s+(.+?)\s+(\d+)\s*$/', $line, $m)) {
                    $stmt = $this->pdo->prepare("INSERT INTO pms_backlog (report_id, property_id, prop_name, count_value) VALUES (?, ?, ?, ?)");
                    $stmt->execute([$this->reportId, intval($m[1]), trim($m[2]), intval($m[3])]);
                }
            }
        }
    }

private function parseOfflineRT1000() {

    // Detect all service provider blocks (BluIP, 14IP US, etc.)
    preg_match_all(
        '/(BluIP|14IP US|14IP Int|14IP INT|US Hybrid1|Shaw Prod|Charter Prod)(.*?)(?=BluIP|14IP US|14IP Int|14IP INT|US Hybrid1|Shaw Prod|Charter Prod|$)/is',
        $this->text,
        $providerBlocks,
        PREG_SET_ORDER
    );

    foreach ($providerBlocks as $block) {

        $providerName = trim($block[1]);
        $content      = $block[2];

        // Extract only Offline RT1000 section inside each provider block
        preg_match(
            '/Offline RT1000 Properties(.*?)(?:PMS Update|Room Status|No issues found|$)/is',
            $content,
            $rtSection
        );

        if (empty($rtSection[1])) continue;

        $lines = preg_split('/\r?\n/', trim($rtSection[1]));

        foreach ($lines as $line) {

            $line = trim($line);
            if ($line === '') continue;
            if (stripos($line, 'Property') !== false) continue;

            // ID   NAME   R1JET-XXXXXX
            if (preg_match('/^(\d+)\s+(.+?)\s+(R1[A-Z]+-\d+)/i', $line, $m)) {

                $stmt = $this->pdo->prepare("
                    INSERT INTO offline_rt1000 
                    (report_id, property_id, prop_name, rt_name, service_provider)
                    VALUES (?, ?, ?, ?, ?)
                ");

                $stmt->execute([
                    $this->reportId,
                    $m[1],
                    $m[2],
                    $m[3],
                    $providerName
                ]);
            }
        }
    }
}

    private function parseCDRStatus() {
        preg_match_all('/CDR Status(.*?)(?:PMS Update|Offline RT1000|Room Status|No issues found|$)/is', $this->text, $blocks);
        if (empty($blocks[1])) return;
        foreach ($blocks[1] as $block) {
            $lines = preg_split('/\r?\n/', trim($block));
            foreach ($lines as $line) {
                $line = trim($line);
                if ($line === '' || stripos($line, 'Property') !== false) continue;

                if ($this->shouldSkip($line)) continue; // <--- FILTER ADDED

                if (preg_match('/^(\d+)\s+(.+?)\s+(Broadworks|Legacy|BROADWORKS)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+([\d\/:\.-]+)/i', $line, $m)) {
                    $stmt = $this->pdo->prepare('INSERT INTO cdr_status (report_id, property_id, prop_name, pbx_type, pbx_number, pbx_raw_seq, enterprise_code, group_code, last_posted_on) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
                    $stmt->execute([$this->reportId, intval($m[1]), $m[2], $m[3], $m[4], $m[5], $m[6], $m[7], $this->tryParseDate($m[8])]);
                }
            }
        }
    }

    private function parseWakeupErrors() {
        if (!preg_match('/Wakeup Errors(.*?)(?:\r?\n\r?\n|PMS Update Backlog|CDR Status|$)/is', $this->text, $m)) return;
        $lines = preg_split('/\r?\n/', trim($m[1]));
        foreach ($lines as $line) {
            $line = trim($line);
            if ($line === '' || stripos($line, 'Property Id') !== false) continue;
            
            if ($this->shouldSkip($line)) continue; // <--- FILTER ADDED

            if (preg_match('/^\s*(\d+)\s+(.+?)\s+(\d+)\s+(\d+)\s+([\d\/:\.\- ]+)\s+([\d\/:\.\- ]+)\s+(.+)$/', $line, $m2)) {
                $this->insertWakeup((int)$m2[1], trim($m2[2]), $m2[3], (int)$m2[4], $this->tryParseDate($m2[5]), $this->tryParseDate($m2[6]), trim($m2[7]));
            }
        }
    }

    private function insertWakeup($pid, $propName, $room, $attempts, $sch, $w, $status) {
        $stmt = $this->pdo->prepare('INSERT INTO wakeup_errors (report_id, property_id, prop_name, room_number, attempts, schedule_time, wakeup_time, status_text) VALUES (?,?,?,?,?,?,?,?)');
        $stmt->execute([$this->reportId, $pid, $propName, $room, $attempts, $sch, $w, $status]);
    }

    private function parseESBErrors() {
        if (preg_match_all('/(W3SVC\d+)\s+([^\s]+)\s+([A-Z]+)\s+(\d+)\s+([\d\-\s:]+)\s+(\d{3})/i', $this->text, $m, PREG_SET_ORDER)) {
            foreach ($m as $row) {
                // Not usually property names here, but can add check if needed:
                // if ($this->shouldSkip($row[0])) continue; 
                $this->insertESB($row[2], $row[3], (int)$row[4], $this->tryParseDate($row[5]), (int)$row[6]);
            }
        }
    }

    private function insertESB($path, $method, $count, $time, $status) {
        $stmt = $this->pdo->prepare('INSERT INTO esb_errors (report_id, service_path, method, count, time_occurred, status_code) VALUES (?,?,?,?,?,?)');
        $stmt->execute([$this->reportId, $path, $method, $count, $time, $status]);
    }

    private function parseSystemStats() {
        $nameDisplay = null; $ps01 = null;
        if (preg_match('/Message Queue Backlog- Name Display:\s*(\d+)/i', $this->text, $m)) $nameDisplay = (int)$m[1];
        if (preg_match('/PS-01: Memory:\s*([\d\.]+)%/i', $this->text, $m2)) $ps01 = floatval($m2[1]);
        if ($nameDisplay !== null || $ps01 !== null) {
            $stmt = $this->pdo->prepare('INSERT INTO system_stats (report_id, name_display_queue, ps01_memory) VALUES (?,?,?)');
            $stmt->execute([$this->reportId, $nameDisplay, $ps01]);
        }
    }

    private function tryParseDate($s) {
        $s = preg_replace('/\.000$/','', trim($s));
        $ts = strtotime($s);
        return ($ts === false) ? null : date('Y-m-d H:i:s', $ts);
    }
}
?>