<?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)
        )
    ");
    
    // Calculate comprehensive wellness score
    $scores = calculateWellnessScore($db, $authUser['id']);
    
    // Save to database
    $stmt = $db->prepare("
        INSERT INTO wellness_scores 
        (user_id, overall_score, sleep_score, activity_score, health_score, stress_score, 
         appointment_score, wellness_engagement_score, score_breakdown)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $breakdown = json_encode($scores['breakdown']);
    $stmt->execute([
        $authUser['id'],
        $scores['overall'],
        $scores['sleep'],
        $scores['activity'],
        $scores['health'],
        $scores['stress'],
        $scores['appointments'],
        $scores['wellness_engagement'],
        $breakdown
    ]);
    
    hw_json([
        'success' => true,
        'score' => $scores['overall'],
        'breakdown' => $scores['breakdown'],
        'recommendations' => generateRecommendations($scores),
        'calculated_at' => date('Y-m-d H:i:s')
    ]);
    
} catch (Exception $e) {
    error_log('Wellness score calculation error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Server error'], 500);
}

function calculateWellnessScore($db, $userId) {
    $scores = [
        'overall' => 0,
        'sleep' => 0,
        'activity' => 0,
        'health' => 0,
        'stress' => 0,
        'appointments' => 0,
        'wellness_engagement' => 0,
        'breakdown' => []
    ];
    
    // 1. Sleep Score (0-20)
    $sleepScore = calculateSleepScore($db, $userId);
    $scores['sleep'] = $sleepScore['score'];
    $scores['breakdown']['sleep'] = $sleepScore;
    
    // 2. Activity Score (0-20)
    $activityScore = calculateActivityScore($db, $userId);
    $scores['activity'] = $activityScore['score'];
    $scores['breakdown']['activity'] = $activityScore;
    
    // 3. Health Metrics Score (0-20)
    $healthScore = calculateHealthScore($db, $userId);
    $scores['health'] = $healthScore['score'];
    $scores['breakdown']['health'] = $healthScore;
    
    // 4. Stress Management Score (0-20)
    $stressScore = calculateStressScore($db, $userId);
    $scores['stress'] = $stressScore['score'];
    $scores['breakdown']['stress'] = $stressScore;
    
    // 5. Appointment Consistency Score (0-10)
    $appointmentScore = calculateAppointmentScore($db, $userId);
    $scores['appointments'] = $appointmentScore['score'];
    $scores['breakdown']['appointments'] = $appointmentScore;
    
    // 6. Wellness Engagement Score (0-10)
    $engagementScore = calculateEngagementScore($db, $userId);
    $scores['wellness_engagement'] = $engagementScore['score'];
    $scores['breakdown']['wellness_engagement'] = $engagementScore;
    
    // Calculate overall score (total of all categories)
    $scores['overall'] = min(100, 
        $scores['sleep'] + 
        $scores['activity'] + 
        $scores['health'] + 
        $scores['stress'] + 
        $scores['appointments'] + 
        $scores['wellness_engagement']
    );
    
    return $scores;
}

function calculateSleepScore($db, $userId) {
    // Get last 7 days of sleep data
    $stmt = $db->prepare("
        SELECT AVG(sleep_hours) as avg_sleep, COUNT(*) as count
        FROM health_metrics
        WHERE user_id = ? AND sleep_hours IS NOT NULL
        AND created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
    ");
    $stmt->execute([$userId]);
    $data = $stmt->fetch();
    
    $avgSleep = $data['avg_sleep'] ?? 0;
    $count = $data['count'] ?? 0;
    
    // Scoring logic: 7-9 hours is ideal (20 points), less than 4 or more than 11 = 0 points
    if ($count === 0) {
        return ['score' => 0, 'metric' => 'No sleep data logged', 'entries' => 0];
    }
    
    $score = 0;
    if ($avgSleep >= 7 && $avgSleep <= 9) {
        $score = 20;
    } elseif ($avgSleep >= 6 && $avgSleep < 7) {
        $score = 15;
    } elseif ($avgSleep > 9 && $avgSleep <= 10) {
        $score = 15;
    } elseif ($avgSleep >= 5 && $avgSleep < 6) {
        $score = 10;
    } elseif ($avgSleep > 10 && $avgSleep <= 11) {
        $score = 10;
    } else {
        $score = 5;
    }
    
    return [
        'score' => $score,
        'metric' => round($avgSleep, 1) . ' hours/night average',
        'entries' => $count,
        'recommendation' => $avgSleep < 7 ? 'Try to get 7-9 hours per night' : 'Great sleep habit!'
    ];
}

function calculateActivityScore($db, $userId) {
    // Get last 30 days of activity (appointments + intake exercise data)
    $stmt = $db->prepare("
        SELECT COUNT(*) as completed_sessions
        FROM appointments
        WHERE user_id = ? AND status = 'completed'
        AND starts_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    $stmt->execute([$userId]);
    $appointments = $stmt->fetch()['completed_sessions'] ?? 0;
    
    // Check exercise from intake
    $intakeStmt = $db->prepare("
        SELECT data FROM intake_forms
        WHERE user_id = ? 
        ORDER BY created_at DESC LIMIT 1
    ");
    $intakeStmt->execute([$userId]);
    $intakeData = $intakeStmt->fetch();
    $intake = $intakeData ? json_decode($intakeData['data'], true) : null;
    $exerciseFrequency = $intake['exercise'] ?? '';
    
    // Scoring: 4+ sessions per month = 20 points
    $score = min(20, ($appointments * 5));
    
    // Bonus for exercise in intake
    if (!empty($exerciseFrequency) && stripos($exerciseFrequency, 'daily') !== false) {
        $score = min(20, $score + 5);
    }
    
    return [
        'score' => $score,
        'metric' => $appointments . ' coaching sessions in last 30 days',
        'entries' => $appointments,
        'exercise' => $exerciseFrequency ?: 'Not specified',
        'recommendation' => $appointments < 2 ? 'Consider scheduling more coaching sessions' : 'Good coaching engagement!'
    ];
}

function calculateHealthScore($db, $userId) {
    // Analyze health metrics stability (ideal ranges)
    $stmt = $db->prepare("
        SELECT 
            AVG(CAST(SUBSTRING_INDEX(blood_pressure, '/', 1) AS UNSIGNED)) as avg_systolic,
            AVG(CAST(SUBSTRING_INDEX(blood_pressure, '/', -1) AS UNSIGNED)) as avg_diastolic,
            AVG(heart_rate) as avg_heart_rate,
            AVG(weight) as avg_weight,
            COUNT(*) as count
        FROM health_metrics
        WHERE user_id = ? AND created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    $stmt->execute([$userId]);
    $metrics = $stmt->fetch();
    
    if ($metrics['count'] === 0) {
        return ['score' => 0, 'metric' => 'No health data logged', 'entries' => 0];
    }
    
    $score = 0;
    
    // Blood pressure scoring (ideal: <120/80)
    if ($metrics['avg_systolic']) {
        if ($metrics['avg_systolic'] < 120 && $metrics['avg_diastolic'] < 80) {
            $score += 8;
        } elseif ($metrics['avg_systolic'] < 130 && $metrics['avg_diastolic'] < 90) {
            $score += 5;
        } else {
            $score += 2;
        }
    }
    
    // Heart rate scoring (ideal: 60-100 bpm)
    if ($metrics['avg_heart_rate']) {
        if ($metrics['avg_heart_rate'] >= 60 && $metrics['avg_heart_rate'] <= 100) {
            $score += 8;
        } elseif ($metrics['avg_heart_rate'] >= 50 && $metrics['avg_heart_rate'] <= 110) {
            $score += 5;
        } else {
            $score += 2;
        }
    }
    
    // Weight stability (no major fluctuations)
    if ($metrics['avg_weight']) {
        $score += 4;
    }
    
    return [
        'score' => min(20, $score),
        'metric' => 'Health metrics stable',
        'entries' => (int)$metrics['count'],
        'blood_pressure' => $metrics['avg_systolic'] ? round($metrics['avg_systolic'], 0) . '/' . round($metrics['avg_diastolic'], 0) : 'Not logged',
        'heart_rate' => $metrics['avg_heart_rate'] ? round($metrics['avg_heart_rate'], 0) . ' bpm' : 'Not logged',
        'recommendation' => 'Keep tracking health metrics regularly'
    ];
}

function calculateStressScore($db, $userId) {
    // Get stress level from latest intake
    $intakeStmt = $db->prepare("
        SELECT data FROM intake_forms
        WHERE user_id = ? 
        ORDER BY created_at DESC LIMIT 1
    ");
    $intakeStmt->execute([$userId]);
    $intakeData = $intakeStmt->fetch();
    $intake = $intakeData ? json_decode($intakeData['data'], true) : null;
    
    $stressLevel = $intake['stressLevel'] ?? null;
    
    // Scoring: 1-3 = 20, 4-5 = 15, 6-7 = 10, 8-10 = 5
    $score = 0;
    if ($stressLevel === null) {
        return ['score' => 10, 'metric' => 'Stress level not assessed', 'level' => 'Unknown'];
    } else {
        $stressLevel = (int)$stressLevel;
        if ($stressLevel <= 3) {
            $score = 20;
        } elseif ($stressLevel <= 5) {
            $score = 15;
        } elseif ($stressLevel <= 7) {
            $score = 10;
        } else {
            $score = 5;
        }
    }
    
    return [
        'score' => $score,
        'metric' => 'Stress level: ' . $stressLevel . '/10',
        'level' => $stressLevel,
        'recommendation' => $stressLevel > 7 ? 'Consider meditation or coaching to manage stress' : 'Good stress management!'
    ];
}

function calculateAppointmentScore($db, $userId) {
    // Consistency: have they had appointments in last 30 days?
    $stmt = $db->prepare("
        SELECT COUNT(*) as completed_recent
        FROM appointments
        WHERE user_id = ? AND status = 'completed'
        AND starts_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    $stmt->execute([$userId]);
    $recent = $stmt->fetch()['completed_recent'] ?? 0;
    
    // Check for scheduled appointments (commitment)
    $scheduledStmt = $db->prepare("
        SELECT COUNT(*) as scheduled_upcoming
        FROM appointments
        WHERE user_id = ? AND status = 'scheduled'
        AND starts_at > NOW()
    ");
    $scheduledStmt->execute([$userId]);
    $scheduled = $scheduledStmt->fetch()['scheduled_upcoming'] ?? 0;
    
    $score = 0;
    if ($recent > 0) {
        $score += 6;
    }
    if ($scheduled > 0) {
        $score += 4;
    }
    
    return [
        'score' => $score,
        'metric' => $recent . ' sessions completed (30d), ' . $scheduled . ' scheduled',
        'completed' => $recent,
        'scheduled' => $scheduled,
        'recommendation' => $scheduled === 0 ? 'Schedule an appointment with your coach' : 'Great! You have sessions scheduled'
    ];
}

function calculateEngagementScore($db, $userId) {
    // Engagement: health data logs + product purchases + document uploads
    $healthStmt = $db->prepare("
        SELECT COUNT(*) as health_entries
        FROM health_metrics
        WHERE user_id = ? AND created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    $healthStmt->execute([$userId]);
    $health = $healthStmt->fetch()['health_entries'] ?? 0;
    
    $orderStmt = $db->prepare("
        SELECT COUNT(*) as orders
        FROM orders
        WHERE user_id = ? AND created_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    $orderStmt->execute([$userId]);
    $orders = $orderStmt->fetch()['orders'] ?? 0;
    
    $reportStmt = $db->prepare("
        SELECT COUNT(*) as reports
        FROM medical_reports
        WHERE user_id = ? AND uploaded_at > DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    $reportStmt->execute([$userId]);
    $reports = $reportStmt->fetch()['reports'] ?? 0;
    
    // Scoring: balance all engagement activities
    $score = 0;
    if ($health >= 2) $score += 3;
    elseif ($health >= 1) $score += 2;
    
    if ($orders >= 1) $score += 3;
    if ($reports >= 1) $score += 2;
    
    // Bonus for holistic engagement
    if ($health > 0 && $orders > 0 && $reports > 0) {
        $score += 2;
    }
    
    return [
        'score' => min(10, $score),
        'metric' => 'Health logs: ' . $health . ', Orders: ' . $orders . ', Reports: ' . $reports,
        'health_logs' => $health,
        'orders' => $orders,
        'reports' => $reports,
        'recommendation' => 'Keep engaging with health tracking and wellness products'
    ];
}

function generateRecommendations($scores) {
    $recommendations = [];
    
    foreach ($scores['breakdown'] as $category => $data) {
        if (isset($data['recommendation'])) {
            $recommendations[] = [
                'category' => ucfirst(str_replace('_', ' ', $category)),
                'message' => $data['recommendation'],
                'priority' => $data['score'] < 10 ? 'high' : ($data['score'] < 15 ? 'medium' : 'low')
            ];
        }
    }
    
    return $recommendations;
}
