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

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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

try {
    // Validate required fields
    if (!isset($_POST['order_test_id']) || !isset($_POST['action'])) {
        throw new Exception('Missing required parameters');
    }
    
    $order_test_id = intval($_POST['order_test_id']);
    $action = $_POST['action']; // 'save_progress' or 'complete'
    $user_id = $_SESSION['user_id'];
    
    // Validate audiogram data
    if (empty($_POST['audiogram_data'])) {
        throw new Exception('No audiogram data provided');
    }
    
    $audiogram_data = json_decode($_POST['audiogram_data'], true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('Invalid audiogram data format');
    }
    
    // Validate equipment selection
    if (empty($_POST['equipment_id'])) {
        throw new Exception('Please select the equipment used');
    }
    
    $equipment_id = intval($_POST['equipment_id']);
    $test_environment = mysqli_real_escape_string($conn, $_POST['test_environment'] ?? 'STANDARD');
    
    // Get current test status for change tracking
    $status_query = "SELECT status FROM lab_order_tests WHERE order_test_id = ?";
    $stmt = mysqli_prepare($conn, $status_query);
    mysqli_stmt_bind_param($stmt, "i", $order_test_id);
    mysqli_stmt_execute($stmt);
    $status_result = mysqli_stmt_get_result($stmt);
    $current_test = mysqli_fetch_assoc($status_result);
    $previous_status = $current_test['status'] ?? 'PENDING';
    
    // Save audiogram image if provided
    $image_path = null;
    if (!empty($_POST['audiogram_image'])) {
        $image_data = $_POST['audiogram_image'];
        
        // Create uploads directory if it doesn't exist
        $upload_dir = '../uploads/audiograms/' . date('Y/m/');
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }
        
        // Extract base64 image data
        $image_parts = explode(";base64,", $image_data);
        $image_base64 = base64_decode($image_parts[1]);
        
        // Generate unique filename
        $filename = 'audiogram_' . $order_test_id . '_' . time() . '.png';
        $file_path = $upload_dir . $filename;
        
        // Save image
        if (file_put_contents($file_path, $image_base64)) {
            $image_path = $file_path;
            $audiogram_data['audiogram_image_path'] = $image_path;
        }
    }
    
    // Add equipment and environment info to audiogram data
    $audiogram_data['equipment_id'] = $equipment_id;
    $audiogram_data['test_environment'] = $test_environment;
    
    // Add interpretation for each ear
    $right_pta = $audiogram_data['right_pta'] ?? null;
    $left_pta = $audiogram_data['left_pta'] ?? null;
    
    $audiogram_data['right_interpretation'] = interpretPTA($right_pta);
    $audiogram_data['left_interpretation'] = interpretPTA($left_pta);
    $audiogram_data['right_loss_type'] = determineLossType($audiogram_data['points'] ?? [], 'right');
    $audiogram_data['left_loss_type'] = determineLossType($audiogram_data['points'] ?? [], 'left');
    
    // Start transaction
    mysqli_begin_transaction($conn);
    
    // Update test status based on action
    if ($action === 'save_progress') {
        $status = 'IN_PROGRESS';
        $completed_at = null;
        $result_interpretation = 'Test in progress - ' . count($audiogram_data['points'] ?? []) . ' points recorded';
    } else if ($action === 'complete') {
        $status = 'COMPLETED';
        $completed_at = date('Y-m-d H:i:s');
        
        // Generate comprehensive interpretation
        $result_interpretation = generateInterpretation($audiogram_data);
    } else {
        throw new Exception('Invalid action specified');
    }
    
    // Prepare update query
    $update_query = "UPDATE lab_order_tests SET 
                     result_files = ?,
                     interpretation = ?,
                     status = ?,
                     tested_by = ?,
                     completed_at = ?,
                     updated_at = NOW()
                     WHERE order_test_id = ?";
    
    $result_files_json = json_encode($audiogram_data);
    
    $stmt = mysqli_prepare($conn, $update_query);
    mysqli_stmt_bind_param($stmt, "sssisi", 
        $result_files_json,
        $result_interpretation,
        $status,
        $user_id,
        $completed_at,
        $order_test_id
    );
    
    if (!mysqli_stmt_execute($stmt)) {
        throw new Exception('Failed to update test record: ' . mysqli_error($conn));
    }
    
    // Log activity - Using correct activity_logs schema
    $activity_query = "INSERT INTO activity_logs 
                      (user_id, action, entity_type, entity_id, description, ip_address, user_agent, changes, status) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'SUCCESS')";
    
    $log_action = $action === 'complete' ? 'COMPLETE' : 'UPDATE';
    $entity_type = 'LAB_TEST';
    $description = $action === 'complete' 
        ? "Completed audiometry test (Order Test ID: $order_test_id)" 
        : "Saved progress for audiometry test (Order Test ID: $order_test_id)";
    
    $changes_json = json_encode([
        'test_type' => 'AUDIOMETRY',
        'order_test_id' => $order_test_id,
        'previous_status' => $previous_status,
        'new_status' => $status,
        'action_performed' => $action,
        'points_recorded' => count($audiometry_data['points'] ?? []),
        'right_pta' => $audiometry_data['right_pta'] ?? null,
        'left_pta' => $audiometry_data['left_pta'] ?? null
    ]);
    
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $user_agent = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 255); // Limit to 255 chars
    
    $stmt = mysqli_prepare($conn, $activity_query);
    mysqli_stmt_bind_param($stmt, "isssisss", 
        $user_id, 
        $log_action, 
        $entity_type, 
        $order_test_id, 
        $description, 
        $ip_address,
        $user_agent,
        $changes_json
    );
    mysqli_stmt_execute($stmt);
    
    // Commit transaction
    mysqli_commit($conn);
    
    // Prepare response
    $response = [
        'success' => true,
        'message' => $action === 'complete' 
            ? 'Audiometry test completed successfully' 
            : 'Progress saved successfully'
    ];
    
    // If completed, add report URL
    if ($action === 'complete') {
        $response['report_url'] = 'generate_audiometry_report.php?id=' . $order_test_id;
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    // Rollback transaction on error
    mysqli_rollback($conn);
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

mysqli_close($conn);

/**
 * Interpret PTA (Pure Tone Average) value
 */
function interpretPTA($pta) {
    if ($pta === null || $pta === '') {
        return 'NOT_CALCULATED';
    }
    
    $pta = floatval($pta);
    
    if ($pta <= 25) {
        return 'NORMAL';
    } else if ($pta <= 40) {
        return 'MILD_LOSS';
    } else if ($pta <= 55) {
        return 'MODERATE_LOSS';
    } else if ($pta <= 70) {
        return 'MODERATELY_SEVERE_LOSS';
    } else if ($pta <= 90) {
        return 'SEVERE_LOSS';
    } else {
        return 'PROFOUND_LOSS';
    }
}

/**
 * Determine type of hearing loss (Conductive, Sensorineural, Mixed)
 */
function determineLossType($points, $ear) {
    // Get AC and BC points for the specified ear
    $ac_points = array_filter($points, function($p) use ($ear) {
        return $p['ear'] === $ear && $p['type'] === 'AC';
    });
    
    $bc_points = array_filter($points, function($p) use ($ear) {
        return $p['ear'] === $ear && $p['type'] === 'BC';
    });
    
    // If not enough data, return unknown
    if (count($ac_points) < 3 || count($bc_points) < 3) {
        return 'Insufficient data';
    }
    
    // Calculate average AC and BC thresholds
    $ac_avg = array_sum(array_column($ac_points, 'db')) / count($ac_points);
    $bc_avg = array_sum(array_column($bc_points, 'db')) / count($bc_points);
    
    // Calculate air-bone gap
    $air_bone_gap = $ac_avg - $bc_avg;
    
    // Determine loss type
    if ($bc_avg <= 25 && $air_bone_gap >= 10) {
        return 'Conductive';
    } else if ($bc_avg > 25 && $air_bone_gap < 10) {
        return 'Sensorineural';
    } else if ($bc_avg > 25 && $air_bone_gap >= 10) {
        return 'Mixed';
    } else {
        return 'Normal/Unclear';
    }
}

/**
 * Generate comprehensive interpretation
 */
function generateInterpretation($data) {
    $interpretation = [];
    
    // Right ear interpretation
    $right_pta = $data['right_pta'] ?? null;
    if ($right_pta !== null) {
        $right_level = interpretPTA($right_pta);
        $right_loss = $data['right_loss_type'] ?? 'Not specified';
        $interpretation[] = "RIGHT EAR: PTA = " . number_format($right_pta, 1) . " dB HL - " . 
                          str_replace('_', ' ', $right_level) . " (" . $right_loss . " hearing loss)";
    }
    
    // Left ear interpretation
    $left_pta = $data['left_pta'] ?? null;
    if ($left_pta !== null) {
        $left_level = interpretPTA($left_pta);
        $left_loss = $data['left_loss_type'] ?? 'Not specified';
        $interpretation[] = "LEFT EAR: PTA = " . number_format($left_pta, 1) . " dB HL - " . 
                          str_replace('_', ' ', $left_level) . " (" . $left_loss . " hearing loss)";
    }
    
    // Weber test
    if (!empty($data['weber_result'])) {
        $interpretation[] = "Weber Test: " . str_replace('_', ' ', $data['weber_result']);
    }
    
    // Rinne test
    if (!empty($data['rinne_right']) || !empty($data['rinne_left'])) {
        $rinne = "Rinne Test:";
        if (!empty($data['rinne_right'])) {
            $rinne .= " Right - " . $data['rinne_right'];
        }
        if (!empty($data['rinne_left'])) {
            $rinne .= " | Left - " . $data['rinne_left'];
        }
        $interpretation[] = $rinne;
    }
    
    return implode(". ", $interpretation);
}
?>