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

hw_require_auth(['client']);

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

$authUser = hw_get_auth_user();
$input = hw_input_json();

try {
    $db = hw_db();
    
    // Validate and sanitize input
    $blood_pressure = $input['blood_pressure'] ?? null;
    $heart_rate = isset($input['heart_rate']) ? (int)$input['heart_rate'] : null;
    $sleep_hours = isset($input['sleep_hours']) ? (float)$input['sleep_hours'] : null;
    $weight = isset($input['weight']) ? (float)$input['weight'] : null;
    $session_notes = $input['session_notes'] ?? null;
    
    // Validate heart_rate if provided
    if ($heart_rate !== null && ($heart_rate < 30 || $heart_rate > 220)) {
        hw_json(['success' => false, 'error' => 'Heart rate must be between 30 and 220 bpm'], 400);
    }
    
    // Validate sleep_hours if provided
    if ($sleep_hours !== null && ($sleep_hours < 0 || $sleep_hours > 24)) {
        hw_json(['success' => false, 'error' => 'Sleep hours must be between 0 and 24'], 400);
    }
    
    // Validate weight if provided
    if ($weight !== null && ($weight < 20 || $weight > 500)) {
        hw_json(['success' => false, 'error' => 'Weight must be between 20 and 500 kg'], 400);
    }
    
    // At least one field must be provided
    if (!$blood_pressure && !$heart_rate && !$sleep_hours && !$weight && !$session_notes) {
        hw_json(['success' => false, 'error' => 'At least one health metric is required'], 400);
    }
    
    // Create health_metrics table if it doesn't exist
    $db->exec("
        CREATE TABLE IF NOT EXISTS health_metrics (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            blood_pressure VARCHAR(20),
            heart_rate INT,
            sleep_hours DECIMAL(3,1),
            weight DECIMAL(5,1),
            session_notes LONGTEXT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            KEY (user_id, created_at)
        )
    ");
    
    // Insert health data
    $stmt = $db->prepare("
        INSERT INTO health_metrics (user_id, blood_pressure, heart_rate, sleep_hours, weight, session_notes)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    
    $stmt->execute([
        $authUser['id'],
        $blood_pressure,
        $heart_rate,
        $sleep_hours,
        $weight,
        $session_notes
    ]);
    
    hw_json([
        'success' => true,
        'message' => 'Health data saved successfully',
        'id' => $db->lastInsertId()
    ]);
    
} catch (PDOException $e) {
    error_log('Health data save error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Database error'], 500);
} catch (Exception $e) {
    error_log('Health data error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Server error'], 500);
}
