<?php
require_once '../config.php';
require_once '../lib.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $user_id = getUserIdFromToken($_COOKIE['auth_token'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? null);

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        if (!$user_id) {
            throw new Exception('Authentication required');
        }

        $type = $_GET['type'] ?? 'coaches';
        $limit = $_GET['limit'] ?? 5;
        
        if ($type === 'coaches') {
            // Get coach recommendations
            $recommendations = getCoachRecommendations($pdo, $user_id, $limit);
            
            echo json_encode([
                'success' => true,
                'recommendations' => $recommendations,
                'type' => 'coaches'
            ]);
            
        } elseif ($type === 'products') {
            // Get product recommendations
            $recommendations = getProductRecommendations($pdo, $user_id, $limit);
            
            echo json_encode([
                'success' => true,
                'recommendations' => $recommendations,
                'type' => 'products'
            ]);
            
        } elseif ($type === 'content') {
            // Get content recommendations
            $recommendations = getContentRecommendations($pdo, $user_id, $limit);
            
            echo json_encode([
                'success' => true,
                'recommendations' => $recommendations,
                'type' => 'content'
            ]);
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Track user behavior
        $input = json_decode(file_get_contents('php://input'), true);
        
        $required = ['action_type', 'entity_type', 'entity_id'];
        foreach ($required as $field) {
            if (empty($input[$field])) {
                throw new Exception("$field is required");
            }
        }
        
        $stmt = $pdo->prepare("
            INSERT INTO user_behavior (user_id, action_type, entity_type, entity_id, session_id, duration_seconds, metadata)
            VALUES (?, ?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $user_id,
            $input['action_type'],
            $input['entity_type'],
            $input['entity_id'],
            $input['session_id'] ?? session_id(),
            $input['duration_seconds'] ?? 0,
            json_encode($input['metadata'] ?? [])
        ]);
        
        // Update recommendations asynchronously (simplified)
        updateRecommendations($pdo, $user_id, $input['entity_type']);
        
        echo json_encode([
            'success' => true,
            'message' => 'Behavior tracked successfully'
        ]);
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

// Helper functions
function getCoachRecommendations($pdo, $user_id, $limit) {
    // Get user preferences
    $stmt = $pdo->prepare("SELECT * FROM user_preferences WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $preferences = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Content-based filtering using tags
    $interests = $preferences ? json_decode($preferences['wellness_interests'], true) : [];
    
    if (!empty($interests)) {
        $placeholders = str_repeat('?,', count($interests) - 1) . '?';
        $stmt = $pdo->prepare("
            SELECT 
                c.id,
                c.first_name,
                c.last_name,
                c.specialties,
                c.hourly_rate,
                c.profile_image_url,
                AVG(et.weight) as relevance_score
            FROM coaches c
            JOIN entity_tags et ON et.entity_type = 'coach' AND et.entity_id = c.id
            WHERE et.tag IN ($placeholders)
            AND c.is_active = TRUE
            GROUP BY c.id
            ORDER BY relevance_score DESC, c.total_sessions DESC
            LIMIT ?
        ");
        $stmt->execute(array_merge($interests, [$limit]));
    } else {
        // Fallback to popular coaches
        $stmt = $pdo->prepare("
            SELECT 
                c.id,
                c.first_name,
                c.last_name,
                c.specialties,
                c.hourly_rate,
                c.profile_image_url,
                c.total_sessions as relevance_score
            FROM coaches c
            WHERE c.is_active = TRUE
            ORDER BY c.total_sessions DESC, c.created_at DESC
            LIMIT ?
        ");
        $stmt->execute([$limit]);
    }
    
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getProductRecommendations($pdo, $user_id, $limit) {
    // Get user's recent purchases and views
    $stmt = $pdo->prepare("
        SELECT 
            p.id,
            p.name,
            p.price,
            p.image_url,
            p.category,
            COUNT(ub.id) as interaction_score
        FROM products p
        LEFT JOIN user_behavior ub ON ub.entity_type = 'product' 
            AND ub.entity_id = p.id 
            AND ub.user_id != ?
            AND ub.action_type IN ('view', 'purchase')
        WHERE p.is_active = TRUE
        GROUP BY p.id
        ORDER BY interaction_score DESC, p.created_at DESC
        LIMIT ?
    ");
    $stmt->execute([$user_id, $limit]);
    
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getContentRecommendations($pdo, $user_id, $limit) {
    // Get user preferences for content recommendations
    $stmt = $pdo->prepare("
        SELECT 
            ca.id,
            ca.title,
            ca.excerpt,
            ca.featured_image,
            ca.view_count,
            cc.name as category_name
        FROM content_articles ca
        LEFT JOIN content_categories cc ON ca.category_id = cc.id
        WHERE ca.status = 'published'
        ORDER BY ca.is_featured DESC, ca.view_count DESC, ca.published_at DESC
        LIMIT ?
    ");
    $stmt->execute([$limit]);
    
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function updateRecommendations($pdo, $user_id, $entity_type) {
    // Simplified recommendation update
    // In production, this would be more sophisticated
    
    $stmt = $pdo->prepare("
        INSERT INTO recommendation_scores (user_id, entity_type, entity_id, score, reason, expires_at)
        SELECT 
            ? as user_id,
            ? as entity_type,
            entity_id,
            0.8 as score,
            'Based on recent activity' as reason,
            DATE_ADD(NOW(), INTERVAL 7 DAY) as expires_at
        FROM user_behavior 
        WHERE user_id = ? AND entity_type = ?
        GROUP BY entity_id
        ON DUPLICATE KEY UPDATE 
            score = GREATEST(score, 0.8),
            expires_at = DATE_ADD(NOW(), INTERVAL 7 DAY)
    ");
    
    $stmt->execute([$user_id, $entity_type, $user_id, $entity_type]);
}
?>