// ============================================
// HOMEOPATHIC CASE MANAGEMENT FUNCTIONS
// ============================================

// Generate unique case number
function generateCaseNumber() {
    global $conn;
    $prefix = 'HMC';
    $year = date('Y');
    $month = date('m');
    $result = $conn->query("SELECT COUNT(*) as total FROM hom_cases WHERE YEAR(created_at) = $year");
    $count = $result->fetch_assoc()['total'] + 1;
    return $prefix . $year . $month . str_pad($count, 4, '0', STR_PAD_LEFT);
}

// Get patient cases
function getPatientCases($patient_id, $visible_only = true) {
    global $conn;
    $sql = "SELECT c.*, d.name as doctor_name 
            FROM hom_cases c 
            LEFT JOIN doctors d ON c.doctor_id = d.id 
            WHERE c.patient_id = $patient_id";
    if ($visible_only) {
        $sql .= " AND c.is_visible_to_patient = 1";
    }
    $sql .= " ORDER BY c.id DESC";
    return $conn->query($sql);
}

// Get doctor cases
function getDoctorCases($doctor_id, $status = 'all') {
    global $conn;
    $sql = "SELECT c.*, p.name as patient_name, p.mobile 
            FROM hom_cases c 
            LEFT JOIN opd_patients p ON c.patient_id = p.id 
            WHERE c.doctor_id = $doctor_id";
    if ($status != 'all') {
        $sql .= " AND c.status = '$status'";
    }
    $sql .= " ORDER BY c.id DESC";
    return $conn->query($sql);
}

// Get case followups
function getCaseFollowups($case_id, $visible_only = true) {
    global $conn;
    $sql = "SELECT * FROM hom_followups WHERE case_id = $case_id";
    if ($visible_only) {
        $sql .= " AND is_visible_to_patient = 1";
    }
    $sql .= " ORDER BY followup_date DESC";
    return $conn->query($sql);
}

// AI Analysis function using OpenAI
function analyzeCaseWithAI($case_id) {
    global $conn;
    
    // Get case data
    $case = $conn->query("SELECT * FROM hom_cases WHERE id = $case_id")->fetch_assoc();
    if (!$case) return false;
    
    // Get patient info
    $patient = $conn->query("SELECT name, age, gender FROM opd_patients WHERE id = {$case['patient_id']}")->fetch_assoc();
    
    // Build prompt for OpenAI
    $prompt = "As a expert homeopathic physician, analyze this case and provide:\n";
    $prompt .= "1. Case Summary\n2. Possible Constitutional Remedies\n3. Prescription Recommendation\n4. Prognosis\n\n";
    $prompt .= "PATIENT: " . ($patient['name'] ?? 'Unknown') . ", Age: " . ($patient['age'] ?? '?') . ", Gender: " . ($patient['gender'] ?? '?') . "\n";
    $prompt .= "CHIEF COMPLAINT: " . ($case['chief_complaint'] ?? 'Not specified') . "\n";
    $prompt .= "HISTORY: " . ($case['history_present'] ?? 'Not specified') . "\n";
    $prompt .= "PAST HISTORY: " . ($case['past_history'] ?? 'Not specified') . "\n";
    $prompt .= "MENTAL STATE: " . ($case['mental_state'] ?? 'Not specified') . "\n";
    $prompt .= "PHYSICAL GENERALS: " . ($case['physical_generals'] ?? 'Not specified') . "\n";
    $prompt .= "MODALITIES: " . ($case['modalities'] ?? 'Not specified') . "\n";
    $prompt .= "PARTICULARS: " . ($case['particulars'] ?? 'Not specified') . "\n";
    
    // Get OpenAI API key from settings
    $api_key = getStyle('openai_api_key', '');
    
    if (empty($api_key)) {
        return ['error' => 'OpenAI API key not configured'];
    }
    
    // Call OpenAI API
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $api_key
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            ['role' => 'system', 'content' => 'You are an expert homeopathic physician. Analyze cases professionally.'],
            ['role' => 'user', 'content' => $prompt]
        ],
        'temperature' => 0.7,
        'max_tokens' => 1000
    ]));
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($http_code == 200) {
        $data = json_decode($response, true);
        $ai_response = $data['choices'][0]['message']['content'] ?? '';
        
        // Save to cache
        $conn->query("INSERT INTO hom_ai_analysis (case_id, analysis_type, ai_response) 
                      VALUES ($case_id, 'summary', '" . $conn->real_escape_string($ai_response) . "')");
        
        return ['success' => true, 'analysis' => $ai_response];
    }
    
    return ['error' => 'API call failed: ' . $response];
}