<?php
declare(strict_types=1);
require_once __DIR__ . '/../lib.php';

hw_require_method(['GET']);
$user = hw_auth_user();
if (!$user) hw_json(['success' => false, 'message' => 'Unauthorized'], 401);

try {
    $pdo = hw_db();
    
    // Check if user is a coach
    $stmt = $pdo->prepare("SELECT id FROM coaches WHERE user_id = ?");
    $stmt->execute([(int)$user['sub']]);
    $coach = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$coach) {
        hw_json(['success' => false, 'message' => 'Coach access required'], 403);
    }
    
    $coachId = $coach['id'];
    
    // Get commission summary
    $stmt = $pdo->prepare("
        SELECT 
            commission_type,
            COUNT(*) as count,
            SUM(commission_amount) as total_amount,
            SUM(CASE WHEN status = 'paid' THEN commission_amount ELSE 0 END) as paid_amount,
            SUM(CASE WHEN status = 'pending' THEN commission_amount ELSE 0 END) as pending_amount
        FROM coach_commissions 
        WHERE coach_id = ? 
        GROUP BY commission_type
    ");
    $stmt->execute([$coachId]);
    $summary = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Get recent commissions
    $stmt = $pdo->prepare("
        SELECT cc.*, 
               CASE 
                   WHEN cc.appointment_id IS NOT NULL THEN CONCAT('Appointment #', cc.appointment_id)
                   WHEN cc.order_id IS NOT NULL THEN CONCAT('Order #', cc.order_id)
                   ELSE 'Other'
               END as source_description
        FROM coach_commissions cc
        WHERE cc.coach_id = ? 
        ORDER BY cc.created_at DESC 
        LIMIT 20
    ");
    $stmt->execute([$coachId]);
    $recentCommissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Calculate totals
    $totalEarnings = array_sum(array_column($summary, 'total_amount'));
    $paidEarnings = array_sum(array_column($summary, 'paid_amount'));
    $pendingEarnings = array_sum(array_column($summary, 'pending_amount'));
    
    hw_json([
        'success' => true,
        'summary' => [
            'total_earnings' => $totalEarnings,
            'paid_earnings' => $paidEarnings,
            'pending_earnings' => $pendingEarnings,
            'by_type' => $summary
        ],
        'recent_commissions' => $recentCommissions
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}