<?php
/**
 * API: Save Case
 * Endpoint for mobile app to save new cases
 * Method: POST
 * Authentication: API Key or JWT Token
 */

require_once '../../config/config.php';
require_once '../../includes/functions.php';
require_once '../../includes/repertory-engine.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-API-Key');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit;
}

// ============================================
// AUTHENTICATION
// ============================================

function authenticateAPI() {
    $headers = getallheaders();
    $apiKey = $headers['X-API-Key'] ?? $_SERVER['HTTP_X_API_KEY'] ?? '';
    
    if (empty($apiKey)) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'API key required']);
        exit;
    }
    
    $pdo = getDB();
    $stmt = $pdo->prepare("SELECT id FROM users WHERE api_key = ? AND role = 'doctor' AND is_active = 1");
    $stmt->execute([$apiKey]);
    $user = $stmt->fetch();
    
    if (!$user) {
        http_response_code(401);
        echo json_encode(['success' => false, 'error' => 'Invalid API key']);
        exit;
    }
    
    return $user['id'];
}

// ============================================
// VALIDATION FUNCTIONS
// ============================================

function validateCaseData($data) {
    $errors = [];
    
    if (empty($data['patient_name'])) {
        $errors[] = "patient_name is required";
    }
    
    if (empty($data['patient_mobile'])) {
        $errors[] = "patient_mobile is required";
    }
    
    if (empty($data['chief_complaint'])) {
        $errors[] = "chief_complaint is required";
    }
    
    return $errors;
}

// ============================================
// MAIN PROCESSING
// ============================================

if ($_SERVER['REQUEST_METHOD'] != 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

// Authenticate user
$userId = authenticateAPI();

// Get input data
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) {
    $input = $_POST;
}

// Validate required fields
$errors = validateCaseData($input);
if (!empty($errors)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'errors' => $errors]);
    exit;
}

$pdo = getDB();

// Process data
$patientName = trim($input['patient_name']);
$patientMobile = trim($input['patient_mobile']);
$patientAge = isset($input['patient_age']) ? (int)$input['patient_age'] : null;
$patientGender = $input['patient_gender'] ?? null;
$chiefComplaint = trim($input['chief_complaint']);
$caseHistory = trim($input['case_history'] ?? '');
$physicalGenerals = trim($input['physical_generals'] ?? '');
$mentalEmotional = trim($input['mental_emotional'] ?? '');
$modalities = trim($input['modalities'] ?? '');
$selectedRubrics = $input['selected_rubrics'] ?? [];

// Perform repertorization if rubrics provided
$repertorizationResult = null;
if (!empty($selectedRubrics)) {
    $rubricsWithWeights = [];
    foreach ($selectedRubrics as $rubricId) {
        $rubricsWithWeights[$rubricId] = ['weight' => 1];
    }
    $scores = repertorize($rubricsWithWeights);
    
    $repertorizationResult = [];
    $count = 0;
    foreach ($scores as $remedyId => $data) {
        if ($count++ >= 20) break;
        $repertorizationResult[] = [
            'remedy_id' => $remedyId,
            'remedy_name' => $data['name'],
            'score' => $data['score']
        ];
    }
}

// Insert case
$stmt = $pdo->prepare("INSERT INTO cases (user_id, patient_name, patient_mobile, patient_age, patient_gender, 
                      chief_complaint, case_history, physical_generals, mental_emotional, modalities, 
                      selected_rubrics, repertorization_result, status, created_at) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', NOW())");

$result = $stmt->execute([
    $userId, $patientName, $patientMobile, $patientAge, $patientGender,
    $chiefComplaint, $caseHistory, $physicalGenerals, $mentalEmotional, $modalities,
    json_encode($selectedRubrics), json_encode($repertorizationResult)
]);

if ($result) {
    $caseId = $pdo->lastInsertId();
    
    echo json_encode([
        'success' => true,
        'message' => 'Case saved successfully',
        'case_id' => $caseId,
        'repertorization' => $repertorizationResult
    ]);
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Failed to save case']);
}
?>