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

hw_require_auth(['client']);

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    hw_json(['success' => false, 'error' => 'Method not allowed'], 405);
}

$authUser = hw_get_auth_user();

try {
    $db = hw_db();
    
    // Create wellness_scores table if it doesn't exist
    $db->exec("
        CREATE TABLE IF NOT EXISTS wellness_scores (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            overall_score INT,
            sleep_score INT,
            activity_score INT,
            health_score INT,
            stress_score INT,
            appointment_score INT,
            wellness_engagement_score INT,
            score_breakdown JSON,
            calculated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            KEY (user_id, calculated_at)
        )
    ");
    
    $days = (int)($_GET['days'] ?? 30);
    
    // Get wellness score history
    $stmt = $db->prepare("
        SELECT 
            id,
            overall_score,
            sleep_score,
            activity_score,
            health_score,
            stress_score,
            appointment_score,
            wellness_engagement_score,
            score_breakdown,
            calculated_at
        FROM wellness_scores
        WHERE user_id = ? AND calculated_at > DATE_SUB(NOW(), INTERVAL ? DAY)
        ORDER BY calculated_at DESC
        LIMIT 100
    ");
    $stmt->execute([$authUser['id'], $days]);
    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Parse JSON breakdown for each score
    foreach ($history as &$score) {
        $score['score_breakdown'] = json_decode($score['score_breakdown'], true);
    }
    
    if (empty($history)) {
        // Suggest calculating a new score
        hw_json([
            'success' => true,
            'current_score' => null,
            'history' => [],
            'message' => 'No wellness scores yet. Visit /api/wellness/calculate.php to generate your first score.'
        ]);
        return;
    }
    
    $currentScore = $history[0];
    
    // Calculate trends
    $trends = [];
    if (count($history) > 1) {
        $previous = $history[1];
        $trends = [
            'overall_change' => $currentScore['overall_score'] - $previous['overall_score'],
            'sleep_change' => $currentScore['sleep_score'] - $previous['sleep_score'],
            'activity_change' => $currentScore['activity_score'] - $previous['activity_score'],
            'health_change' => $currentScore['health_score'] - $previous['health_score'],
            'stress_change' => $currentScore['stress_score'] - $previous['stress_score'],
            'appointment_change' => $currentScore['appointment_score'] - $previous['appointment_score'],
            'engagement_change' => $currentScore['wellness_engagement_score'] - $previous['wellness_engagement_score']
        ];
    }
    
    hw_json([
        'success' => true,
        'current_score' => [
            'overall' => $currentScore['overall_score'],
            'breakdown' => $currentScore['score_breakdown'],
            'calculated_at' => $currentScore['calculated_at']
        ],
        'trends' => $trends,
        'history' => array_map(function($score) {
            return [
                'overall' => $score['overall_score'],
                'calculated_at' => $score['calculated_at'],
                'breakdown' => [
                    'sleep' => $score['sleep_score'],
                    'activity' => $score['activity_score'],
                    'health' => $score['health_score'],
                    'stress' => $score['stress_score'],
                    'appointments' => $score['appointment_score'],
                    'engagement' => $score['wellness_engagement_score']
                ]
            ];
        }, $history),
        'total_records' => count($history)
    ]);
    
} catch (PDOException $e) {
    error_log('Wellness score fetch error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Database error'], 500);
} catch (Exception $e) {
    error_log('Wellness score error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Server error'], 500);
}
