<?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 coach_notes table if it doesn't exist
    $db->exec("
        CREATE TABLE IF NOT EXISTS coach_notes (
            id INT AUTO_INCREMENT PRIMARY KEY,
            appointment_id INT NOT NULL,
            coach_id INT NOT NULL,
            user_id INT NOT NULL,
            note_type VARCHAR(50) DEFAULT 'general',
            note LONGTEXT NOT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            FOREIGN KEY (appointment_id) REFERENCES appointments(id) ON DELETE CASCADE,
            FOREIGN KEY (coach_id) REFERENCES coaches(id) ON DELETE CASCADE,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            KEY (user_id, created_at),
            KEY (note_type)
        )
    ");
    
    $limit = (int)($_GET['limit'] ?? 5);
    
    // Get recent coach recommendations
    $stmt = $db->prepare("
        SELECT 
            cn.id,
            cn.note,
            cn.note_type,
            cn.created_at,
            CONCAT(u.first_name, ' ', u.last_name) as coach_name,
            c.display_name
        FROM coach_notes cn
        JOIN coaches c ON cn.coach_id = c.id
        JOIN users u ON c.user_id = u.id
        WHERE cn.user_id = ? AND cn.note_type IN ('recommendation', 'insight')
        ORDER BY cn.created_at DESC
        LIMIT ?
    ");
    
    $stmt->execute([$authUser['id'], $limit]);
    $recommendations = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    hw_json([
        'success' => true,
        'recommendations' => $recommendations,
        'count' => count($recommendations)
    ]);
    
} catch (PDOException $e) {
    error_log('Coach recommendations fetch error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Database error'], 500);
} catch (Exception $e) {
    error_log('Coach recommendations error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Server error'], 500);
}
