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

// ✅ CRITICAL: Suppress PHP warnings that break JSON response
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

// Set JSON header
header('Content-Type: application/json');

// Log function for debugging
function logError($message, $data = []) {
    $logFile = __DIR__ . '/../logs/audiometry_errors.log';
    $logDir = dirname($logFile);
    
    if (!file_exists($logDir)) {
        @mkdir($logDir, 0755, true);
    }
    
    $logMessage = date('[Y-m-d H:i:s] ') . $message;
    if (!empty($data)) {
        $logMessage .= ' | Data: ' . json_encode($data);
    }
    $logMessage .= PHP_EOL;
    
    @file_put_contents($logFile, $logMessage, FILE_APPEND);
}

try {
    // Validate request method
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }
    
    // Validate required parameters
    $order_test_id = isset($_POST['order_test_id']) ? intval($_POST['order_test_id']) : 0;
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    
    if ($order_test_id == 0) {
        throw new Exception('Invalid test ID');
    }
    
    if (!in_array($action, ['save_progress', 'complete'])) {
        throw new Exception('Invalid action: ' . htmlspecialchars($action));
    }
    
    logError("Processing audiometry test", [
        'order_test_id' => $order_test_id,
        'action' => $action,
        'user_id' => $_SESSION['user_id']
    ]);
    
    // Get test details with proper joins
    $query = "SELECT lot.*, lo.order_number, lo.patient_id, lo.visit_id,
                     p.patient_number, u.full_name as patient_name,
                     u.date_of_birth, u.gender, u.phone_primary as phone_number,
                     ett.test_name, ett.test_code,
                     TIMESTAMPDIFF(YEAR, u.date_of_birth, CURDATE()) as age
              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
              WHERE lot.order_test_id = ?";
    
    $stmt = mysqli_prepare($conn, $query);
    if (!$stmt) {
        throw new Exception('Failed to prepare statement: ' . mysqli_error($conn));
    }
    
    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)) {
        throw new Exception('Test not found with ID: ' . $order_test_id);
    }
    
    // Get examiner details
    $examiner_query = "SELECT full_name FROM users WHERE user_id = ?";
    $examiner_stmt = mysqli_prepare($conn, $examiner_query);
    mysqli_stmt_bind_param($examiner_stmt, "i", $_SESSION['user_id']);
    mysqli_stmt_execute($examiner_stmt);
    $examiner_result = mysqli_stmt_get_result($examiner_stmt);
    $examiner = mysqli_fetch_assoc($examiner_result);
    
    if (!$examiner) {
        throw new Exception('Examiner not found');
    }
    
    // Decode and validate audiogram data
    if (!isset($_POST['audiogram_data']) || empty($_POST['audiogram_data'])) {
        throw new Exception('Audiogram data is missing');
    }
    
    $audiogram_data = json_decode($_POST['audiogram_data'], true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid audiogram data format: ' . json_last_error_msg());
    }
    
    // Validate we have at least some points
    $totalPoints = 0;
    if (isset($audiogram_data['right_ear_points']) && is_array($audiogram_data['right_ear_points'])) {
        $totalPoints += count($audiogram_data['right_ear_points']);
    }
    if (isset($audiogram_data['left_ear_points']) && is_array($audiogram_data['left_ear_points'])) {
        $totalPoints += count($audiogram_data['left_ear_points']);
    }
    
    if ($totalPoints === 0 && $action === 'complete') {
        throw new Exception('Cannot complete test without any audiogram data');
    }
    
    // Validate equipment
    $equipment_id = isset($_POST['equipment_id']) ? intval($_POST['equipment_id']) : 0;
    if ($equipment_id == 0) {
        throw new Exception('Equipment selection is required');
    }
    
    // Get equipment details
    $eq_query = "SELECT equipment_name, equipment_code FROM lab_equipment WHERE equipment_id = ? AND is_active = 1";
    $eq_stmt = mysqli_prepare($conn, $eq_query);
    mysqli_stmt_bind_param($eq_stmt, "i", $equipment_id);
    mysqli_stmt_execute($eq_stmt);
    $eq_result = mysqli_stmt_get_result($eq_stmt);
    $equipment = mysqli_fetch_assoc($eq_result);
    
    if (!$equipment) {
        throw new Exception('Invalid or inactive equipment selected');
    }
    
    // Start transaction
    mysqli_begin_transaction($conn);
    
    try {
        // Get form data
        $test_environment = isset($_POST['test_environment']) ? $_POST['test_environment'] : 'STANDARD';
        $weber_result = isset($_POST['weber_result']) && !empty($_POST['weber_result']) ? $_POST['weber_result'] : null;
        $rinne_right = isset($_POST['rinne_right']) && !empty($_POST['rinne_right']) ? $_POST['rinne_right'] : null;
        $rinne_left = isset($_POST['rinne_left']) && !empty($_POST['rinne_left']) ? $_POST['rinne_left'] : null;
        $comments = isset($_POST['comments']) ? trim($_POST['comments']) : null;
        $recommendations = isset($_POST['recommendations']) ? trim($_POST['recommendations']) : null;
        
        // ✅ CRITICAL: Store everything in result_files JSON (align with database schema)
        $result_files_data = [
            'audiogram_data' => $audiogram_data,
            'test_environment' => $test_environment,
            'weber_result' => $weber_result,
            'rinne_right' => $rinne_right,
            'rinne_left' => $rinne_left,
            'equipment_id' => $equipment_id,
            'equipment_name' => $equipment['equipment_name'],
            'equipment_code' => $equipment['equipment_code'],
            'examiner' => $examiner['full_name'],
            'examiner_id' => $_SESSION['user_id'],
            'recommendations' => $recommendations, // Store recommendations in JSON
            'total_points' => $totalPoints,
            'test_date' => date('Y-m-d H:i:s')
        ];
        
        $result_files_json = json_encode($result_files_data);
        
        // ✅ Use interpretation column for clinical comments (align with schema)
        $interpretation = $comments;
        
        // Create enhanced summary for result_value field
        $right_pta = isset($audiogram_data['right_pta']) ? $audiogram_data['right_pta'] : null;
        $left_pta = isset($audiogram_data['left_pta']) ? $audiogram_data['left_pta'] : null;
        $right_pta_label = isset($audiogram_data['right_pta_label']) ? $audiogram_data['right_pta_label'] : '';
        $left_pta_label = isset($audiogram_data['left_pta_label']) ? $audiogram_data['left_pta_label'] : '';
        
        $result_value = sprintf(
            "Right: %s (%s) | Left: %s (%s)",
            $right_pta !== null ? number_format($right_pta, 1) . ' dB' : 'N/A',
            $right_pta_label ?: 'No data',
            $left_pta !== null ? number_format($left_pta, 1) . ' dB' : 'N/A',
            $left_pta_label ?: 'No data'
        );
        
        if ($action === 'save_progress') {
            // ✅ Save as IN_PROGRESS - ALIGN WITH SCHEMA (no comments, recommendations, equipment_id columns)
            $update_query = "UPDATE lab_order_tests 
                           SET status = 'IN_PROGRESS',
                               result_files = ?,
                               result_value = ?,
                               interpretation = ?,
                               updated_at = NOW()
                           WHERE order_test_id = ?";
            
            $update_stmt = mysqli_prepare($conn, $update_query);
            if (!$update_stmt) {
                throw new Exception('Failed to prepare update statement: ' . mysqli_error($conn));
            }
            
            mysqli_stmt_bind_param($update_stmt, "sssi", 
                $result_files_json,
                $result_value,
                $interpretation,
                $order_test_id
            );
            
            if (!mysqli_stmt_execute($update_stmt)) {
                throw new Exception('Failed to save progress: ' . mysqli_stmt_error($update_stmt));
            }
            
            // Log activity
            $activity_query = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, created_at)
                             VALUES (?, 'UPDATE', 'LAB_TEST', ?, ?, ?, NOW())";
            $activity_stmt = mysqli_prepare($conn, $activity_query);
            $activity_desc = "Saved audiometry progress for patient " . $test['patient_name'];
            $ip_address = $_SERVER['REMOTE_ADDR'];
            mysqli_stmt_bind_param($activity_stmt, "iiss", $_SESSION['user_id'], $order_test_id, $activity_desc, $ip_address);
            mysqli_stmt_execute($activity_stmt);
            
            mysqli_commit($conn);
            
            logError("Successfully saved progress", ['order_test_id' => $order_test_id]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Progress saved successfully',
                'test_id' => $order_test_id
            ]);
            
        } else { // complete
            // Check if AudiometryReport class exists
            $report_class_path = __DIR__ . '/audiometry_report_class.php';
            $class_exists = file_exists($report_class_path);
            
            if ($class_exists) {
                require_once $report_class_path;
            }
            
            // Generate report filename
            $safe_patient_number = preg_replace('/[^A-Za-z0-9_-]/', '_', $test['patient_number']);
            $report_filename = 'audiometry_' . $safe_patient_number . '_' . date('Ymd_His') . '.pdf';
            $reports_dir = '../reports/audiometry/';
            
            // Ensure directory exists
            if (!file_exists($reports_dir)) {
                if (!mkdir($reports_dir, 0755, true)) {
                    logError("Failed to create reports directory", ['dir' => $reports_dir]);
                    throw new Exception('Failed to create reports directory');
                }
            }
            
            $report_path = $reports_dir . $report_filename;
            $report_url = null;
            
            // Only generate PDF if class exists
            if ($class_exists && class_exists('AudiometryReport')) {
                try {
                    // Get frequencies from system settings
                    $freq_query = "SELECT setting_value FROM system_settings 
                                  WHERE category = 'audiology' 
                                  AND setting_key = 'audiometry_frequencies_hz' 
                                  LIMIT 1";
                    $freq_result = mysqli_query($conn, $freq_query);
                    $frequencies = [125, 250, 500, 750, 1000, 1500, 2000, 3000, 4000, 6000, 8000];
                    
                    if ($freq_row = mysqli_fetch_assoc($freq_result)) {
                        $parsed = array_map('intval', array_filter(array_map('trim', explode(',', $freq_row['setting_value']))));
                        if (count($parsed) >= 2) {
                            $frequencies = $parsed;
                        }
                    }
                    
                    // Fetch hospital settings
                    $settings = [];
                    $settings_q = mysqli_query($conn, "SELECT setting_key, setting_value FROM system_settings 
                        WHERE setting_key IN ('hospital_name','hospital_address','hospital_phone','hospital_email','hospital_website')");
                    if ($settings_q) {
                        while ($r = mysqli_fetch_assoc($settings_q)) {
                            $settings[$r['setting_key']] = $r['setting_value'];
                        }
                    }
                    
                    // Create PDF
                    $pdf = new AudiometryReport($frequencies, $settings);
                    $pdf->AddPage();
                    
                    // Patient info
                    $patientData = [
                        'patient_name' => $test['patient_name'],
                        'patient_number' => $test['patient_number'],
                        'age' => $test['age'],
                        'gender' => $test['gender'],
                        'phone_number' => $test['phone_number'],
                        'test_date' => date('d/m/Y'),
                        'examiner' => $examiner['full_name']
                    ];
                    $pdf->PatientInfo($patientData);
                    
                    // Tuning fork tests
                    $pdf->TuningForkTests($rinne_right, $rinne_left, $weber_result);
                    
                    // Draw audiograms
                    $rightEarPoints = isset($audiogram_data['right_ear_points']) ? $audiogram_data['right_ear_points'] : [];
                    $leftEarPoints = isset($audiogram_data['left_ear_points']) ? $audiogram_data['left_ear_points'] : [];
                    
                    if (method_exists($pdf, 'DrawBothAudiograms')) {
                        $endY = $pdf->DrawBothAudiograms($rightEarPoints, $leftEarPoints, $pdf->GetY());
                        $pdf->SetY($endY);
                    }
                    
                    // SISI section
                    if (method_exists($pdf, 'SISISection')) {
                        $pdf->SISISection();
                    }
                    
                    // Comments and recommendations
                    if (method_exists($pdf, 'CommentsAndRecommendations')) {
                        $pdf->CommentsAndRecommendations(
                            $comments,
                            $recommendations,
                            $right_pta,
                            $left_pta
                        );
                    }
                    
                    // Save PDF
                    $pdf->Output('F', $report_path);
                    
                    // Verify file was created
                    if (!file_exists($report_path)) {
                        throw new Exception('PDF file was not created successfully');
                    }
                    
                    $report_url = 'reports/audiometry/' . $report_filename;
                    $result_files_data['report_filename'] = $report_filename;
                    $result_files_json = json_encode($result_files_data);
                    
                    logError("PDF generated successfully", ['filename' => $report_filename]);
                    
                } catch (Exception $pdf_error) {
                    logError("PDF generation failed", [
                        'error' => $pdf_error->getMessage(),
                        'line' => $pdf_error->getLine()
                    ]);
                    
                    // Continue without PDF if generation fails
                    $result_files_data['pdf_generation_error'] = $pdf_error->getMessage();
                    $result_files_data['report_filename'] = null;
                    $result_files_json = json_encode($result_files_data);
                }
            } else {
                logError("PDF generation skipped - class not found", ['path' => $report_class_path]);
                $result_files_data['pdf_generation_skipped'] = true;
                $result_files_data['pdf_skip_reason'] = 'AudiometryReport class not found';
                $result_files_json = json_encode($result_files_data);
            }
            
            $completed_at = date('Y-m-d H:i:s');
            
            // ✅ ALIGN WITH DATABASE SCHEMA - no comments, recommendations, equipment_id columns
            $update_query = "UPDATE lab_order_tests 
                           SET status = 'COMPLETED',
                               result_files = ?,
                               result_value = ?,
                               interpretation = ?,
                               completed_at = ?,
                               tested_by = ?,
                               updated_at = NOW()
                           WHERE order_test_id = ?";
            
            $update_stmt = mysqli_prepare($conn, $update_query);
            if (!$update_stmt) {
                throw new Exception('Failed to prepare update statement: ' . mysqli_error($conn));
            }
            
            mysqli_stmt_bind_param($update_stmt, "ssssii", 
                $result_files_json,
                $result_value,
                $interpretation,
                $completed_at,
                $_SESSION['user_id'],
                $order_test_id
            );
            
            if (!mysqli_stmt_execute($update_stmt)) {
                throw new Exception('Failed to update test status: ' . mysqli_stmt_error($update_stmt));
            }
            
            // Check if all tests in order are completed
            $check_query = "SELECT COUNT(*) as total, 
                                  SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completed
                           FROM lab_order_tests 
                           WHERE order_id = (SELECT order_id FROM lab_order_tests WHERE order_test_id = ?)";
            $check_stmt = mysqli_prepare($conn, $check_query);
            mysqli_stmt_bind_param($check_stmt, "i", $order_test_id);
            mysqli_stmt_execute($check_stmt);
            $check_result = mysqli_stmt_get_result($check_stmt);
            $check_data = mysqli_fetch_assoc($check_result);
            
            if ($check_data['total'] == $check_data['completed']) {
                $order_update = "UPDATE lab_orders 
                               SET status = 'COMPLETED',
                                   completed_at = NOW()
                               WHERE order_id = (SELECT order_id FROM lab_order_tests WHERE order_test_id = ?)";
                $order_stmt = mysqli_prepare($conn, $order_update);
                mysqli_stmt_bind_param($order_stmt, "i", $order_test_id);
                mysqli_stmt_execute($order_stmt);
            }
            
            // Log activity
            $activity_query = "INSERT INTO activity_logs (user_id, action, entity_type, entity_id, description, ip_address, created_at)
                             VALUES (?, 'COMPLETE', 'LAB_TEST', ?, ?, ?, NOW())";
            $activity_stmt = mysqli_prepare($conn, $activity_query);
            $activity_desc = "Completed audiometry test for patient " . $test['patient_name'];
            if ($report_url) {
                $activity_desc .= " - Report: " . $report_filename;
            }
            $ip_address = $_SERVER['REMOTE_ADDR'];
            mysqli_stmt_bind_param($activity_stmt, "iiss", $_SESSION['user_id'], $order_test_id, $activity_desc, $ip_address);
            mysqli_stmt_execute($activity_stmt);
            
            mysqli_commit($conn);
            
            logError("Test completed successfully", [
                'order_test_id' => $order_test_id,
                'report_generated' => $report_url !== null
            ]);
            
            $response = [
                'success' => true,
                'message' => 'Test completed successfully',
                'test_id' => $order_test_id
            ];
            
            if ($report_url) {
                $response['report_url'] = $report_url;
            } else {
                $response['message'] .= ' (PDF report could not be generated)';
            }
            
            echo json_encode($response);
        }
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        logError("Transaction failed", [
            'error' => $e->getMessage(),
            'line' => $e->getLine(),
            'file' => basename($e->getFile())
        ]);
        throw $e;
    }
    
} catch (Exception $e) {
    http_response_code(400);
    
    logError("Request failed", [
        'error' => $e->getMessage(),
        'line' => $e->getLine(),
        'file' => basename($e->getFile())
    ]);
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage(),
        'line' => $e->getLine(),
        'file' => basename($e->getFile()),
        'debug' => [
            'post_data_keys' => array_keys($_POST),
            'session_user' => isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 'not set'
        ]
    ]);
}
?>