<?php
// ✅ Only require FPDF if not already loaded (handles different include paths)
if (!class_exists('FPDF')) {
    // Try multiple possible paths for FPDF
    $possible_paths = [
        __DIR__ . '/../fpdf/fpdf.php',  // From ajax/ folder
        __DIR__ . '/fpdf/fpdf.php',      // From root folder
        'fpdf/fpdf.php',                  // Relative from current script
        '../fpdf/fpdf.php'                // One level up
    ];
    
    $fpdf_loaded = false;
    foreach ($possible_paths as $path) {
        if (file_exists($path)) {
            require_once $path;
            $fpdf_loaded = true;
            break;
        }
    }
    
    if (!$fpdf_loaded) {
        die('FPDF library not found. Please ensure fpdf/fpdf.php exists in your project.');
    }
}

class AudiometryReport extends FPDF {
    private $hospitalName;
    private $hospitalAddress;
    private $hospitalPO;
    private $hospitalPhone;
    private $hospitalEmail;
    private $hospitalWebsite;
    
    private $frequencies = [];
    // Template-style dB range: -10 to 110 dB HL (matches Audiogram.pdf)
    private $dbRange = [-10, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110];
    private $logoPath = '';
    
    function __construct($frequencies = null, $settings = null) {
        parent::__construct('L', 'mm', 'A4'); // Landscape orientation
        $this->frequencies = $frequencies ?: [125, 250, 500, 750, 1000, 1500, 2000, 3000, 4000, 6000, 8000];
        
        // Template defaults (Audiogram.pdf style); override with $settings if provided
        $this->hospitalName = $settings['hospital_name'] ?? '4th Avenue Towers 8th floor';
        $this->hospitalAddress = $settings['hospital_address'] ?? '(Upper Hill, 4th Ngong Avenue)';
        $this->hospitalPO = $settings['hospital_pobox'] ?? 'P.O Box 19429 - 00202, Nairobi.';
        $ph = $settings['hospital_phone'] ?? '0722 279159/+254 20-2302732';
        $this->hospitalPhone = $ph ? 'Tel: ' . $ph : 'Tel: 0722 279159/+254 20-2302732';
        $em = $settings['hospital_email'] ?? 'info@prodigykenya.com';
        $this->hospitalEmail = $em ? 'Email: ' . $em : 'Email: info@prodigykenya.com';
        $this->hospitalWebsite = $settings['hospital_website'] ?? 'www.prodigykenya.com';
        
        // Check for logo file
        $possiblePaths = [
            '../assets/images/logo.png',
            '../assets/logo.png',
            'assets/images/logo.png',
            'logo.png'
        ];
        
        foreach ($possiblePaths as $path) {
            if (file_exists($path)) {
                $this->logoPath = $path;
                break;
            }
        }
        
        // Disable automatic page breaks
        $this->SetAutoPageBreak(false, 0);
    }
    
    function Header() {
        // Logo on the left (if exists)
        if ($this->logoPath && file_exists($this->logoPath)) {
            try {
                $this->Image($this->logoPath, 10, 10, 25, 25); // x, y, width, height
            } catch (Exception $e) {
                // If logo fails to load, draw a placeholder box
                $this->Rect(10, 10, 25, 25);
                $this->SetXY(10, 20);
                $this->SetFont('Arial', 'B', 8);
                $this->Cell(25, 5, 'LOGO', 0, 0, 'C');
            }
        } else {
            // Draw placeholder box if logo doesn't exist
            $this->SetDrawColor(200, 200, 200);
            $this->Rect(10, 10, 25, 25);
            $this->SetDrawColor(0, 0, 0);
        }
        
        // Title - Centered
        $this->SetFont('Arial', 'B', 18);
        $this->SetY(10);
        $this->Cell(0, 10, 'PURE TONE AUDIOMETRY', 0, 1, 'C');
        
        // Hospital name and address - Left side (after logo)
        $this->SetY(22);
        $this->SetX(40);
        $this->SetFont('Arial', 'B', 10);
        $this->Cell(100, 5, $this->hospitalName, 0, 1, 'L');
        $this->SetX(40);
        $this->SetFont('Arial', '', 9);
        $this->Cell(100, 4, $this->hospitalAddress, 0, 1, 'L');
        $this->SetX(40);
        $this->Cell(100, 4, $this->hospitalPO, 0, 1, 'L');
        
        // Contact details - Right side
        $this->SetY(22);
        $this->SetFont('Arial', 'B', 9);
        $this->SetX(-85);
        $this->Cell(75, 4, $this->hospitalPhone, 0, 1, 'R');
        $this->SetFont('Arial', '', 8);
        $this->SetX(-85);
        $this->Cell(75, 4, $this->hospitalEmail, 0, 1, 'R');
        $this->SetX(-85);
        $this->Cell(75, 4, $this->hospitalWebsite, 0, 1, 'R');
        
        $this->Ln(2);
    }
    
    function PatientInfo($patientData) {
        $startY = $this->GetY();
        
        // Draw horizontal lines for the form
        $this->SetDrawColor(0, 0, 0);
        $lineY = $startY + 8;
        
        // First row - Name, Age, Date
        $this->SetXY(10, $startY);
        $this->SetFont('Arial', 'B', 10);
        $this->Cell(140, 8, 'NAME', 0, 0, 'L');
        $this->Cell(70, 8, 'AGE', 0, 0, 'C');
        $this->Cell(67, 8, 'DATE', 0, 1, 'C');
        
        // Draw the line
        $this->Line(10, $lineY, 150, $lineY);
        $this->Line(150, $lineY, 220, $lineY);
        $this->Line(220, $lineY, 287, $lineY);
        
        $this->SetXY(10, $lineY);
        $this->SetFont('Arial', '', 10);
        $this->Cell(140, 6, strtoupper($patientData['patient_name']), 0, 0, 'L');
        $this->Cell(70, 6, $patientData['age'], 0, 0, 'C');
        $this->Cell(67, 6, $patientData['test_date'], 0, 1, 'C');
        
        $this->Ln(2);
        
        // Second row - Phone, Examiner
        $lineY2 = $this->GetY() + 8;
        $this->SetFont('Arial', 'B', 10);
        $this->Cell(140, 8, 'PHONE NUMBER', 0, 0, 'L');
        $this->Cell(137, 8, 'EXAMINER', 0, 1, 'C');
        
        $this->Line(10, $lineY2, 150, $lineY2);
        $this->Line(150, $lineY2, 287, $lineY2);
        
        $this->SetY($lineY2);
        $this->SetFont('Arial', '', 10);
        $this->Cell(140, 6, $patientData['phone_number'], 0, 0, 'L');
        $this->Cell(137, 6, strtoupper($patientData['examiner']), 0, 1, 'C');
        
        $this->Ln(5);
    }
    
    function TuningForkTests($rightRinne, $leftRinne, $weber) {
        $startY = $this->GetY();
        $centerX = $this->w / 2;
        
        // Right Rinne
        $this->SetXY(50, $startY);
        $this->SetFont('Arial', 'B', 9);
        $this->Cell(20, 5, 'Rinne', 0, 1, 'C');
        $this->SetXY(50, $startY + 5);
        $this->SetFont('Arial', '', 8);
        $this->Cell(10, 5, '+', 1, 0, 'C');
        $this->Cell(10, 5, '-', 1, 0, 'C');
        
        // Mark right rinne result
        if ($rightRinne === 'POSITIVE') {
            $this->SetXY(50, $startY + 10);
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(10, 5, 'X', 0, 0, 'C');
        } elseif ($rightRinne === 'NEGATIVE') {
            $this->SetXY(60, $startY + 10);
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(10, 5, 'X', 0, 0, 'C');
        }
        
        // Weber 500 Hz - Centered
        $this->SetXY($centerX - 15, $startY);
        $this->SetFont('Arial', 'B', 9);
        $this->Cell(30, 5, 'Weber 500 Hz', 0, 1, 'C');
        $this->SetXY($centerX - 15, $startY + 5);
        $this->SetFont('Arial', '', 8);
        $this->Cell(10, 5, 're.', 1, 0, 'C');
        $this->Cell(10, 5, 'med.', 1, 0, 'C');
        $this->Cell(10, 5, 'li.', 1, 0, 'C');
        
        // Mark weber result
        if ($weber === 'LATERALIZE_RIGHT') {
            $this->SetXY($centerX - 15, $startY + 10);
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(10, 5, 'X', 0, 0, 'C');
        } elseif ($weber === 'MIDLINE') {
            $this->SetXY($centerX - 5, $startY + 10);
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(10, 5, 'X', 0, 0, 'C');
        } elseif ($weber === 'LATERALIZE_LEFT') {
            $this->SetXY($centerX + 5, $startY + 10);
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(10, 5, 'X', 0, 0, 'C');
        }
        
        // Left Rinne
        $this->SetXY(227, $startY);
        $this->SetFont('Arial', 'B', 9);
        $this->Cell(20, 5, 'Rinne', 0, 1, 'C');
        $this->SetXY(227, $startY + 5);
        $this->SetFont('Arial', '', 8);
        $this->Cell(10, 5, '+', 1, 0, 'C');
        $this->Cell(10, 5, '-', 1, 0, 'C');
        
        // Mark left rinne result
        if ($leftRinne === 'POSITIVE') {
            $this->SetXY(227, $startY + 10);
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(10, 5, 'X', 0, 0, 'C');
        } elseif ($leftRinne === 'NEGATIVE') {
            $this->SetXY(237, $startY + 10);
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(10, 5, 'X', 0, 0, 'C');
        }
        
        $this->SetY($startY + 18);
    }
    
    function DrawBothAudiograms($rightEarPoints, $leftEarPoints, $startY) {
        // Fixed positions for side-by-side audiograms with proper spacing
        $rightStartX = 15;
        $leftStartX = 165;
        $width = 110;  // Width stays at 110mm
        $height = 90;  // ✅ Reduced from 100 to 90mm to compress graphs vertically
        
        // Draw Right Ear
        $this->DrawAudiogram('right', $rightEarPoints, $rightStartX, $startY, $width, $height);
        
        // Draw Left Ear (same Y position)
        $this->DrawAudiogram('left', $leftEarPoints, $leftStartX, $startY, $width, $height);
        
        // Draw masking scale in the center
        $this->MaskingSection($startY, $width, $height);
        
        // ✅ Increased gap from 8 to 15 to push comments/recommendations down
        return $startY + $height + 15;
    }
    
    function DrawAudiogram($ear, $points, $startX, $startY, $width, $height) {
        // Title - positioned higher above the chart
        $this->SetXY($startX, $startY);
        $this->SetFont('Arial', 'BI', 10);
        $earLabel = $ear === 'right' ? 'Right Ear' : 'Left Ear';
        $this->Cell($width, 5, $earLabel . ' Frequency (kHz)', 0, 1, 'C');
        
        // ✅ Increased gap from 6 to 10 to move frequency labels UP
        $chartStartY = $startY + 10;
        
        // Draw chart border
        $this->SetDrawColor(0, 0, 0);
        $this->Rect($startX, $chartStartY, $width, $height);
        
        // Draw grid lines and frequency labels
        $this->SetFont('Arial', '', 7);
        $freqCount = count($this->frequencies);
        
        for ($i = 0; $i < $freqCount; $i++) {
            $x = $startX + ($width / ($freqCount - 1)) * $i;
            
            // Vertical grid line
            $this->SetDrawColor(220, 220, 220);
            $this->Line($x, $chartStartY, $x, $chartStartY + $height);
            $this->SetDrawColor(0, 0, 0);
            
            // Frequency label - template format: 0.125, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8 kHz
            $freq = $this->frequencies[$i];
            if ($freq >= 1000) {
                $freqLabel = ($freq == 1500) ? '1.5' : (string)($freq / 1000);
            } else {
                $khz = $freq / 1000;
                $freqLabel = ($freq == 125 || $freq == 250) ? number_format($khz, 3) : number_format($khz, 2);
            }
            
            // ✅ Moved label further UP from -5 to -7
            $this->SetXY($x - 6, $chartStartY - 7);
            $this->Cell(12, 4, $freqLabel, 0, 0, 'C');
        }
        
        // Draw horizontal grid lines and dB labels
        $dbCount = count($this->dbRange);
        for ($i = 0; $i < $dbCount; $i++) {
            $y = $chartStartY + ($height / ($dbCount - 1)) * $i;
            
            // Horizontal grid line
            $this->SetDrawColor(220, 220, 220);
            $this->Line($startX, $y, $startX + $width, $y);
            $this->SetDrawColor(0, 0, 0);
            
            // dB label
            $this->SetXY($startX - 12, $y - 2);
            $this->Cell(10, 4, $this->dbRange[$i], 0, 0, 'R');
        }
        
        // Y-axis label (vertical text) - Better spacing to avoid overlap
        $this->SetFont('Arial', 'B', 7);
        $labelX = $startX - 16;
        $labelY = $chartStartY + $height/2;
        
        // Draw vertical text letter by letter with better spacing
        $label = 'Hearing Level (dB)';
        $letters = str_split($label);
        $currentY = $labelY - (count($letters) * 2.5);
        
        foreach ($letters as $letter) {
            $this->SetXY($labelX, $currentY);
            $this->Cell(5, 3, $letter, 0, 0, 'C');
            $currentY += 2.5;
        }
        
        // Plot points
        $this->PlotPoints($points, $startX, $chartStartY, $width, $height, $ear);
    }
    
    function PlotPoints($points, $startX, $startY, $width, $height, $ear) {
        if (empty($points)) return;
        
        $freqCount = count($this->frequencies);
        $dbCount = count($this->dbRange);
        
        // Group points by type for drawing lines
        $pointsByType = [];
        foreach ($points as $point) {
            $type = $point['type'];
            if (!isset($pointsByType[$type])) {
                $pointsByType[$type] = [];
            }
            $pointsByType[$type][] = $point;
        }
        
        // Set color based on ear
        $color = $ear === 'right' ? [220, 53, 69] : [13, 110, 253];
        $this->SetDrawColor($color[0], $color[1], $color[2]);
        $this->SetTextColor($color[0], $color[1], $color[2]);
        
        // Draw connecting lines for AC types
        foreach ($pointsByType as $type => $typePoints) {
            if (in_array($type, ['AC', 'AC_MASKED'])) {
                usort($typePoints, function($a, $b) {
                    return $a['frequency'] - $b['frequency'];
                });
                
                $prevX = null;
                $prevY = null;
                
                foreach ($typePoints as $point) {
                    $x = $this->getXPosition($point['frequency'], $startX, $width, $freqCount);
                    $y = $this->getYPosition($point['db'], $startY, $height, $dbCount);
                    
                    if ($prevX !== null && $prevY !== null) {
                        $this->Line($prevX, $prevY, $x, $y);
                    }
                    
                    $prevX = $x;
                    $prevY = $y;
                }
            }
        }
        
        // Draw symbols
        $this->SetFont('Arial', 'B', 12);
        foreach ($points as $point) {
            $x = $this->getXPosition($point['frequency'], $startX, $width, $freqCount);
            $y = $this->getYPosition($point['db'], $startY, $height, $dbCount);
            
            $this->drawSymbol($point['tool'], $x, $y, $ear);
        }
        
        // Reset colors
        $this->SetDrawColor(0, 0, 0);
        $this->SetTextColor(0, 0, 0);
    }
    
    function getXPosition($frequency, $startX, $width, $freqCount) {
        $index = array_search($frequency, $this->frequencies);
        if ($index === false) return $startX;
        return $startX + ($width / ($freqCount - 1)) * $index;
    }
    
    function getYPosition($db, $startY, $height, $dbCount) {
        $index = array_search($db, $this->dbRange);
        if ($index === false) return $startY;
        return $startY + ($height / ($dbCount - 1)) * $index;
    }
    
    function drawSymbol($tool, $x, $y, $ear) {
        $size = 2.5;
        
        switch($tool) {
            case 'right_ac': // O
                $this->Circle($x, $y, $size, 'D');
                break;
            case 'right_ac_masked': // Triangle
                $this->Triangle($x, $y, $size);
                break;
            case 'right_bc': // <
                $this->SetXY($x - 3, $y - 2);
                $this->Cell(0, 0, '<', 0, 0, 'L');
                break;
            case 'right_bc_masked': // [
                $this->SetXY($x - 3, $y - 2);
                $this->Cell(0, 0, '[', 0, 0, 'L');
                break;
            case 'left_ac': // X
                $this->Line($x - $size, $y - $size, $x + $size, $y + $size);
                $this->Line($x + $size, $y - $size, $x - $size, $y + $size);
                break;
            case 'left_ac_masked': // Square
                $this->Rect($x - $size, $y - $size, $size * 2, $size * 2, 'D');
                break;
            case 'left_bc': // >
                $this->SetXY($x - 3, $y - 2);
                $this->Cell(0, 0, '>', 0, 0, 'L');
                break;
            case 'left_bc_masked': // ]
                $this->SetXY($x - 3, $y - 2);
                $this->Cell(0, 0, ']', 0, 0, 'L');
                break;
        }
    }
    
    function Circle($x, $y, $r, $style = 'D') {
        $this->Ellipse($x, $y, $r, $r, $style);
    }
    
    function Ellipse($x, $y, $rx, $ry, $style = 'D') {
        if ($style == 'F') {
            $op = 'f';
        } elseif ($style == 'FD' || $style == 'DF') {
            $op = 'B';
        } else {
            $op = 'S';
        }
        
        $lx = 4/3 * (M_SQRT2 - 1) * $rx;
        $ly = 4/3 * (M_SQRT2 - 1) * $ry;
        
        $this->_out(sprintf('%.2F %.2F m %.2F %.2F %.2F %.2F %.2F %.2F c',
            ($x + $rx) * $this->k, ($this->h - $y) * $this->k,
            ($x + $rx) * $this->k, ($this->h - ($y - $ly)) * $this->k,
            ($x + $lx) * $this->k, ($this->h - ($y - $ry)) * $this->k,
            $x * $this->k, ($this->h - ($y - $ry)) * $this->k));
        
        $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c',
            ($x - $lx) * $this->k, ($this->h - ($y - $ry)) * $this->k,
            ($x - $rx) * $this->k, ($this->h - ($y - $ly)) * $this->k,
            ($x - $rx) * $this->k, ($this->h - $y) * $this->k));
        
        $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c',
            ($x - $rx) * $this->k, ($this->h - ($y + $ly)) * $this->k,
            ($x - $lx) * $this->k, ($this->h - ($y + $ry)) * $this->k,
            $x * $this->k, ($this->h - ($y + $ry)) * $this->k));
        
        $this->_out(sprintf('%.2F %.2F %.2F %.2F %.2F %.2F c %s',
            ($x + $lx) * $this->k, ($this->h - ($y + $ry)) * $this->k,
            ($x + $rx) * $this->k, ($this->h - ($y + $ly)) * $this->k,
            ($x + $rx) * $this->k, ($this->h - $y) * $this->k,
            $op));
    }
    
    function Triangle($x, $y, $size) {
        $height = $size * 1.732;
        $this->Line($x, $y - $height/2, $x - $size, $y + $height/2);
        $this->Line($x - $size, $y + $height/2, $x + $size, $y + $height/2);
        $this->Line($x + $size, $y + $height/2, $x, $y - $height/2);
    }
    
    function MaskingSection($startY, $width, $height) {
        $centerX = $this->w / 2;  // Center of page (148.5mm for A4 landscape)
        // ✅ Match the new chartStartY position (startY + 10)
        $chartStartY = $startY + 10;
        
        // Title above the masking box - positioned higher
        $this->SetXY($centerX - 12, $chartStartY - 8);
        $this->SetFont('Arial', 'BI', 9);
        $this->Cell(24, 5, 'Masking', 0, 1, 'C');
        
        // Draw masking scale
        $this->SetFont('Arial', '', 7);
        $scale = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90];
        
        $boxWidth = 18;
        $boxHeight = $height / count($scale);
        $boxX = $centerX - ($boxWidth / 2);
        $boxY = $chartStartY;
        
        // Draw box border
        $this->SetDrawColor(0, 0, 0);
        $this->Rect($boxX, $boxY, $boxWidth, $height);
        
        // Draw scale values
        foreach ($scale as $i => $value) {
            $y = $boxY + ($i * $boxHeight);
            // Horizontal line
            $this->Line($boxX, $y, $boxX + $boxWidth, $y);
            // Value centered in box
            $this->SetXY($boxX, $y + 0.5);
            $this->Cell($boxWidth, $boxHeight - 1, $value, 0, 0, 'C');
        }
    }
    
    function SISISection() {
        $this->SetFont('Arial', 'B', 9);
        $this->Cell(0, 6, 'SISI 1 dB (%) (dB)', 0, 1, 'C');
        $this->Ln(1);
    }
    
    function CommentsAndRecommendations($comments, $recommendations, $rightPTA, $leftPTA) {
        // ✅ Increased spacing from 2 to 5 to push section down further
        $this->Ln(5);
        $currentY = $this->GetY();
        
        // Ensure we're not too close to the bottom
        if ($currentY > 170) {
            $currentY = 170;
            $this->SetY($currentY);
        }
        
        // Comments section - Left
        $this->SetXY(10, $currentY);
        $this->SetFont('Arial', 'B', 9);
        $this->Cell(135, 5, 'Comments:', 0, 1, 'L');
        
        // Draw underline for comments
        $lineY = $this->GetY();
        $this->Line(10, $lineY, 145, $lineY);
        
        $this->SetXY(10, $lineY + 1);
        $this->SetFont('Arial', '', 8);
        
        $commentsText = '';
        
        // Add PTA to comments if available
        if ($rightPTA !== null || $leftPTA !== null) {
            $ptaLine = "PTA - Right: " . ($rightPTA !== null ? number_format($rightPTA, 1) . " dB HL" : "N/A");
            $ptaLine .= " | Left: " . ($leftPTA !== null ? number_format($leftPTA, 1) . " dB HL" : "N/A");
            $commentsText = $ptaLine;
        }
        
        if (!empty($comments)) {
            $commentsText .= ($commentsText ? "\n" : '') . $comments;
        }
        
        if (empty($commentsText)) {
            $commentsText = 'No additional comments';
        }
        
        $this->MultiCell(135, 4, $commentsText, 0, 'L');
        
        // Recommendations section - Right
        $this->SetXY(152, $currentY);
        $this->SetFont('Arial', 'B', 9);
        $this->Cell(135, 5, 'Recommendations:', 0, 1, 'L');
        
        // Draw underline for recommendations
        $this->Line(152, $lineY, 287, $lineY);
        
        $this->SetXY(152, $lineY + 1);
        $this->SetFont('Arial', '', 8);
        $this->MultiCell(135, 4, $recommendations ?: 'Follow standard care protocols', 0, 'L');
    }
}
?>