<?php
/**
 * Simulate Skin Detection
 * محاكاة كشف مشاكل البشرة
 */

header('Content-Type: application/json');
require_once '../config/database.php';

// Initialize database connection
$database = new Database();
$conn = $database->getConnection();

if (!$conn) {
    echo json_encode([
        'success' => false,
        'message' => 'Database connection failed'
    ]);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);

if (!isset($input['session_id'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Session ID is required'
    ]);
    exit;
}

$sessionId = $input['session_id'];

try {
    // Verify session exists
    $stmt = $conn->prepare("SELECT id FROM skin_analysis_sessions WHERE id = ?");
    $stmt->execute([$sessionId]);
    
    if (!$stmt->fetch()) {
        echo json_encode([
            'success' => false,
            'message' => 'Invalid session'
        ]);
        exit;
    }
    
    // Simulate detection - generate random concerns
    $concernTypes = ['moles', 'acne', 'dark_spots', 'redness', 'fine_lines'];
    $severityLevels = ['low', 'medium', 'high'];
    
    // Random number of concerns (1-3)
    $numConcerns = rand(1, 3);
    $detectedConcerns = [];
    
    for ($i = 0; $i < $numConcerns; $i++) {
        $concernType = $concernTypes[array_rand($concernTypes)];
        $count = rand(1, 5);
        $severity = $severityLevels[array_rand($severityLevels)];
        
        // Random position on face (0-100%)
        $posX = rand(20, 80);
        $posY = rand(20, 80);
        
        // Insert concern
        $stmt = $conn->prepare("
            INSERT INTO skin_concerns_detected 
            (session_id, concern_type, concern_count, severity_level, position_x, position_y, confidence_score) 
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        
        $confidence = rand(75, 95) / 100;
        $stmt->execute([$sessionId, $concernType, $count, $severity, $posX, $posY, $confidence]);
        
        $concernId = $conn->lastInsertId();
        
        $detectedConcerns[] = [
            'id' => $concernId,
            'type' => $concernType,
            'count' => $count,
            'severity' => $severity,
            'position_x' => $posX,
            'position_y' => $posY,
            'confidence' => $confidence
        ];
    }
    
    // Update session status
    $stmt = $conn->prepare("UPDATE skin_analysis_sessions SET status = 'detecting', current_step = 2 WHERE id = ?");
    $stmt->execute([$sessionId]);
    
    echo json_encode([
        'success' => true,
        'concerns' => $detectedConcerns,
        'message' => 'Detection completed'
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
