<?php
session_start();
require_once 'layouts/dbconn.php';
require_once 'layouts/session.php';
require_once 'fpdf/fpdf.php';

// Get order_test_id from URL
$order_test_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($order_test_id == 0) {
    die('Invalid test ID');
}

// Fetch complete test details - STRICTLY using actual schema columns
$query = "SELECT lot.*, lo.order_number, lo.patient_id, lo.visit_id, lo.ordered_at,
                 p.patient_number, u.full_name as patient_name,
                 u.date_of_birth, u.gender, u.phone_primary as phone_number,
                 u.email, u.address,
                 ett.test_name, ett.test_code,
                 TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age,
                 doctor.full_name as doctor_name,
                 tech.full_name as technician_name
          FROM lab_order_tests lot
          JOIN lab_orders lo ON lot.order_id = lo.order_id
          JOIN patients p ON lo.patient_id = p.patient_id
          JOIN users u ON p.user_id = u.user_id
          JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
          LEFT JOIN users doctor ON lo.ordered_by = doctor.user_id
          LEFT JOIN users tech ON lot.tested_by = tech.user_id
          WHERE lot.order_test_id = ?";

$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "i", $order_test_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if (!$test = mysqli_fetch_assoc($result)) {
    die('Test not found');
}

// Parse audiometry data from result_files JSON column
$audiometry_data = json_decode($test['result_files'], true);
if (!$audiometry_data) {
    die('No audiometry data found');
}

// Custom PDF class
class AudiometryPDF extends FPDF {
    private $hospitalName = "ENT Specialist Hospital";
    private $hospitalAddress = "123 Medical Center, Nairobi, Kenya";
    private $hospitalPhone = "+254 700 000 000";
    private $hospitalEmail = "info@enthospital.co.ke";
    
    function Header() {
        // Purple gradient header (simulated with rectangles)
        $this->SetFillColor(102, 126, 234);
        $this->Rect(0, 0, 210, 35, 'F');
        
        // Hospital Logo/Name
        $this->SetTextColor(255, 255, 255);
        $this->SetFont('Arial', 'B', 20);
        $this->SetY(8);
        $this->Cell(0, 10, $this->hospitalName, 0, 1, 'C');
        
        $this->SetFont('Arial', '', 9);
        $this->Cell(0, 4, $this->hospitalAddress, 0, 1, 'C');
        $this->Cell(0, 4, 'Tel: ' . $this->hospitalPhone . ' | Email: ' . $this->hospitalEmail, 0, 1, 'C');
        
        // Reset text color
        $this->SetTextColor(0, 0, 0);
        $this->Ln(5);
    }
    
    function Footer() {
        $this->SetY(-15);
        $this->SetFont('Arial', 'I', 8);
        $this->SetTextColor(128, 128, 128);
        $this->Cell(0, 10, 'Page ' . $this->PageNo() . ' | Generated on ' . date('d M Y H:i'), 0, 0, 'C');
    }
    
    function SectionTitle($title) {
        $this->SetFont('Arial', 'B', 12);
        $this->SetFillColor(102, 126, 234);
        $this->SetTextColor(255, 255, 255);
        $this->Cell(0, 8, $title, 0, 1, 'L', true);
        $this->Ln(2);
        $this->SetTextColor(0, 0, 0);
    }
    
    function InfoRow($label, $value, $width1 = 50, $width2 = 140) {
        $this->SetFont('Arial', 'B', 9);
        $this->Cell($width1, 6, $label . ':', 0, 0);
        $this->SetFont('Arial', '', 9);
        $this->Cell($width2, 6, $value, 0, 1);
    }
    
    function InfoBox($items, $title = '') {
        if ($title) {
            $this->SetFont('Arial', 'B', 10);
            $this->Cell(0, 6, $title, 0, 1);
            $this->Ln(1);
        }
        
        $this->SetFillColor(248, 249, 250);
        $this->Rect($this->GetX(), $this->GetY(), 190, count($items) * 6 + 4, 'F');
        $this->Ln(2);
        
        foreach ($items as $label => $value) {
            $this->InfoRow($label, $value);
        }
        $this->Ln(2);
    }
}

// Create PDF
$pdf = new AudiometryPDF();
$pdf->SetAutoPageBreak(true, 20);
$pdf->AddPage();

// Report Title
$pdf->SetFont('Arial', 'B', 16);
$pdf->SetTextColor(102, 126, 234);
$pdf->Cell(0, 10, 'AUDIOMETRY TEST REPORT', 0, 1, 'C');
$pdf->SetTextColor(0, 0, 0);
$pdf->Ln(3);

// Patient Information
$pdf->SectionTitle('PATIENT INFORMATION');
$pdf->InfoBox([
    'Patient Name' => $test['patient_name'],
    'Patient Number' => $test['patient_number'],
    'Date of Birth' => date('d M Y', strtotime($test['date_of_birth'])),
    'Age' => $test['age'] . ' years',
    'Gender' => ucfirst(strtolower($test['gender'])),
    'Phone Number' => $test['phone_number'],
    'Email' => $test['email'] ?: 'N/A'
]);

// Test Information
$pdf->SectionTitle('TEST INFORMATION');

// Get equipment info if provided in audiometry_data
$equipment_info = 'N/A';
if (isset($audiometry_data['equipment_name'])) {
    $equipment_info = $audiometry_data['equipment_name'];
    if (isset($audiometry_data['equipment_code'])) {
        $equipment_info .= ' (' . $audiometry_data['equipment_code'] . ')';
    }
}

$pdf->InfoBox([
    'Order Number' => $test['order_number'],
    'Test Name' => $test['test_name'],
    'Test Code' => $test['test_code'],
    'Test Date' => date('d M Y H:i', strtotime($test['completed_at'] ?: $test['ordered_at'])),
    'Ordered By' => $test['doctor_name'] ?: 'N/A',
    'Performed By' => $test['technician_name'] ?: 'N/A',
    'Equipment Used' => $equipment_info
]);

// Test Results - Pure Tone Average
$pdf->SectionTitle('PURE TONE AUDIOMETRY RESULTS');

$right_pta = $audiometry_data['right_pta'] ?? null;
$left_pta = $audiometry_data['left_pta'] ?? null;

// PTA Results Table
$pdf->SetFillColor(220, 53, 69);
$pdf->SetTextColor(255, 255, 255);
$pdf->SetFont('Arial', 'B', 10);
$pdf->Cell(95, 8, 'RIGHT EAR', 1, 0, 'C', true);
$pdf->SetFillColor(13, 110, 253);
$pdf->Cell(95, 8, 'LEFT EAR', 1, 1, 'C', true);

$pdf->SetFillColor(248, 249, 250);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetFont('Arial', 'B', 9);

// PTA Values
$pdf->Cell(47.5, 7, 'Pure Tone Average:', 1, 0, 'L', true);
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(47.5, 7, $right_pta !== null ? number_format($right_pta, 1) . ' dB HL' : 'Not calculated', 1, 0, 'C');

$pdf->SetFont('Arial', 'B', 9);
$pdf->Cell(47.5, 7, 'Pure Tone Average:', 1, 0, 'L', true);
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(47.5, 7, $left_pta !== null ? number_format($left_pta, 1) . ' dB HL' : 'Not calculated', 1, 1, 'C');

// Interpretation
$pdf->SetFont('Arial', 'B', 9);
$pdf->Cell(47.5, 7, 'Interpretation:', 1, 0, 'L', true);
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(47.5, 7, getHearingLossLevel($right_pta), 1, 0, 'C');

$pdf->SetFont('Arial', 'B', 9);
$pdf->Cell(47.5, 7, 'Interpretation:', 1, 0, 'L', true);
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(47.5, 7, getHearingLossLevel($left_pta), 1, 1, 'C');

$pdf->Ln(5);

// Clinical Tests Results
$pdf->SectionTitle('CLINICAL TUNING FORK TESTS');

$weber = $audiometry_data['weber_result'] ?? '';
$rinne_right = $audiometry_data['rinne_right'] ?? '';
$rinne_left = $audiometry_data['rinne_left'] ?? '';

$clinical_tests = [];
if ($weber) {
    $weber_display = str_replace('_', ' ', $weber);
    $weber_display = ucwords(strtolower($weber_display));
    $clinical_tests['Weber Test (512 Hz)'] = $weber_display;
}
if ($rinne_right) {
    $clinical_tests['Rinne Test - Right Ear'] = ucfirst(strtolower($rinne_right));
}
if ($rinne_left) {
    $clinical_tests['Rinne Test - Left Ear'] = ucfirst(strtolower($rinne_left));
}

if (!empty($clinical_tests)) {
    $pdf->InfoBox($clinical_tests);
} else {
    $pdf->SetFont('Arial', 'I', 9);
    $pdf->Cell(0, 6, 'No clinical tuning fork tests recorded', 0, 1);
    $pdf->Ln(3);
}

// Audiogram Images - stored in result_files JSON
if (isset($audiometry_data['images']) && is_array($audiometry_data['images'])) {
    $pdf->AddPage();
    $pdf->SectionTitle('AUDIOGRAM CHARTS');
    
    // Right Ear Audiogram
    if (isset($audiometry_data['images']['right_ear'])) {
        $pdf->SetFont('Arial', 'B', 11);
        $pdf->SetTextColor(220, 53, 69);
        $pdf->Cell(0, 6, 'RIGHT EAR AUDIOGRAM', 0, 1, 'C');
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Ln(2);
        
        $image_path = $audiometry_data['images']['right_ear'];
        if (file_exists($image_path)) {
            $pdf->Image($image_path, 10, $pdf->GetY(), 190);
            $pdf->Ln(100);
        }
    }
    
    // Left Ear Audiogram
    if (isset($audiometry_data['images']['left_ear'])) {
        $pdf->Ln(5);
        $pdf->SetFont('Arial', 'B', 11);
        $pdf->SetTextColor(13, 110, 253);
        $pdf->Cell(0, 6, 'LEFT EAR AUDIOGRAM', 0, 1, 'C');
        $pdf->SetTextColor(0, 0, 0);
        $pdf->Ln(2);
        
        $image_path = $audiometry_data['images']['left_ear'];
        if (file_exists($image_path)) {
            $pdf->Image($image_path, 10, $pdf->GetY(), 190);
            $pdf->Ln(100);
        }
    }
}

// Comments and Recommendations
$pdf->AddPage();

if (!empty($audiometry_data['comments'])) {
    $pdf->SectionTitle('CLINICAL COMMENTS');
    $pdf->SetFont('Arial', '', 9);
    $pdf->MultiCell(0, 5, $audiometry_data['comments']);
    $pdf->Ln(3);
}

if (!empty($audiometry_data['recommendations'])) {
    $pdf->SectionTitle('RECOMMENDATIONS');
    $pdf->SetFont('Arial', '', 9);
    $pdf->MultiCell(0, 5, $audiometry_data['recommendations']);
    $pdf->Ln(3);
}

// Audiometry Data Points (Detailed)
$pdf->SectionTitle('DETAILED AUDIOMETRY DATA');

// Right Ear Data
if (!empty($audiometry_data['right_ear_points'])) {
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetTextColor(220, 53, 69);
    $pdf->Cell(0, 6, 'Right Ear Measurements:', 0, 1);
    $pdf->SetTextColor(0, 0, 0);
    
    // Table header
    $pdf->SetFillColor(248, 249, 250);
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->Cell(30, 6, 'Frequency (Hz)', 1, 0, 'C', true);
    $pdf->Cell(30, 6, 'Threshold (dB)', 1, 0, 'C', true);
    $pdf->Cell(40, 6, 'Type', 1, 0, 'C', true);
    $pdf->Cell(30, 6, 'Masking', 1, 1, 'C', true);
    
    // Sort by frequency
    $right_points = $audiometry_data['right_ear_points'];
    usort($right_points, function($a, $b) {
        return $a['frequency'] - $b['frequency'];
    });
    
    $pdf->SetFont('Arial', '', 8);
    foreach ($right_points as $point) {
        $type = ($point['type'] == 'AC' || $point['type'] == 'AC_MASKED') ? 'Air Conduction' : 'Bone Conduction';
        $masked = (strpos($point['type'], 'MASKED') !== false) ? 'Yes' : 'No';
        
        $pdf->Cell(30, 5, $point['frequency'], 1, 0, 'C');
        $pdf->Cell(30, 5, $point['db'], 1, 0, 'C');
        $pdf->Cell(40, 5, $type, 1, 0, 'C');
        $pdf->Cell(30, 5, $masked, 1, 1, 'C');
    }
    $pdf->Ln(3);
}

// Left Ear Data
if (!empty($audiometry_data['left_ear_points'])) {
    $pdf->SetFont('Arial', 'B', 10);
    $pdf->SetTextColor(13, 110, 253);
    $pdf->Cell(0, 6, 'Left Ear Measurements:', 0, 1);
    $pdf->SetTextColor(0, 0, 0);
    
    // Table header
    $pdf->SetFillColor(248, 249, 250);
    $pdf->SetFont('Arial', 'B', 8);
    $pdf->Cell(30, 6, 'Frequency (Hz)', 1, 0, 'C', true);
    $pdf->Cell(30, 6, 'Threshold (dB)', 1, 0, 'C', true);
    $pdf->Cell(40, 6, 'Type', 1, 0, 'C', true);
    $pdf->Cell(30, 6, 'Masking', 1, 1, 'C', true);
    
    // Sort by frequency
    $left_points = $audiometry_data['left_ear_points'];
    usort($left_points, function($a, $b) {
        return $a['frequency'] - $b['frequency'];
    });
    
    $pdf->SetFont('Arial', '', 8);
    foreach ($left_points as $point) {
        $type = ($point['type'] == 'AC' || $point['type'] == 'AC_MASKED') ? 'Air Conduction' : 'Bone Conduction';
        $masked = (strpos($point['type'], 'MASKED') !== false) ? 'Yes' : 'No';
        
        $pdf->Cell(30, 5, $point['frequency'], 1, 0, 'C');
        $pdf->Cell(30, 5, $point['db'], 1, 0, 'C');
        $pdf->Cell(40, 5, $type, 1, 0, 'C');
        $pdf->Cell(30, 5, $masked, 1, 1, 'C');
    }
    $pdf->Ln(5);
}

// Signature Section
$pdf->Ln(10);
$pdf->SetFont('Arial', 'B', 9);
$pdf->Cell(95, 6, 'Performed By:', 0, 0);
$pdf->Cell(95, 6, 'Verified By:', 0, 1);

$pdf->Ln(15);
$pdf->SetFont('Arial', '', 9);
$pdf->Cell(95, 6, '_________________________', 0, 0);
$pdf->Cell(95, 6, '_________________________', 0, 1);

$pdf->Cell(95, 5, $test['technician_name'] ?: 'Lab Technician', 0, 0);
$pdf->Cell(95, 5, $test['doctor_name'] ?: 'Physician', 0, 1);

$pdf->Cell(95, 5, 'Date: ' . date('d M Y'), 0, 0);
$pdf->Cell(95, 5, 'Date: ' . date('d M Y'), 0, 1);

// Disclaimer
$pdf->Ln(5);
$pdf->SetFont('Arial', 'I', 7);
$pdf->SetTextColor(128, 128, 128);
$pdf->MultiCell(0, 4, 'This report is confidential and intended for the use of the patient and their healthcare provider. The results should be interpreted by a qualified healthcare professional in conjunction with clinical findings and patient history.');

// Output PDF
$filename = 'Audiometry_Report_' . $test['patient_number'] . '_' . date('Ymd') . '.pdf';
$pdf->Output('D', $filename);

// Helper function for hearing loss interpretation
function getHearingLossLevel($pta) {
    if ($pta === null) {
        return 'Not calculated';
    }
    
    if ($pta <= 25) {
        return 'Normal';
    } elseif ($pta <= 40) {
        return 'Mild Loss';
    } elseif ($pta <= 55) {
        return 'Moderate Loss';
    } elseif ($pta <= 70) {
        return 'Moderately Severe Loss';
    } elseif ($pta <= 90) {
        return 'Severe Loss';
    } else {
        return 'Profound Loss';
    }
}
?>