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

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

try {
    $pdo = hw_db();
    
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 20;
    $offset = ($page - 1) * $limit;
    
    // Check if user is a coach
    $coachStmt = $pdo->prepare("SELECT id FROM coaches WHERE user_id = ?");
    $coachStmt->execute([$user['id']]);
    $coach = $coachStmt->fetch();
    
    if ($coach) {
        // Coach view: Get appointments where user is the coach
        $stmt = $pdo->prepare("
            SELECT 
                a.id,
                a.coach_id,
                a.user_id,
                a.starts_at,
                a.duration,
                a.status,
                CONCAT(u.first_name, ' ', u.last_name) as client_name,
                u.email as client_email
            FROM appointments a
            LEFT JOIN users u ON a.user_id = u.id
            WHERE a.coach_id = ? AND a.starts_at > NOW()
            ORDER BY a.starts_at ASC
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([$coach['id'], $limit, $offset]);
        $appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get total count
        $countStmt = $pdo->prepare("
            SELECT COUNT(*) as total FROM appointments 
            WHERE coach_id = ? AND starts_at > NOW()
        ");
        $countStmt->execute([$coach['id']]);
        $total = $countStmt->fetch()['total'];
    } else {
        // User view: Get appointments for this user
        $stmt = $pdo->prepare("
            SELECT 
                a.id,
                a.coach_id,
                a.user_id,
                a.starts_at,
                a.ends_at,
                a.duration,
                a.status,
                a.notes,
                c.display_name as coach_name,
                u.email as coach_email
            FROM appointments a 
            LEFT JOIN coaches c ON a.coach_id = c.id 
            LEFT JOIN users u ON c.user_id = u.id 
            WHERE a.user_id = ?
            ORDER BY a.starts_at DESC
            LIMIT ? OFFSET ?
        ");
        $stmt->execute([$user['id'], $limit, $offset]);
        $appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // Get total count
        $countStmt = $pdo->prepare("
            SELECT COUNT(*) as total FROM appointments 
            WHERE user_id = ?
        ");
        $countStmt->execute([$user['id']]);
        $total = $countStmt->fetch()['total'];
    }
    
    hw_json([
        'success' => true,
        'appointments' => $appointments,
        'pagination' => [
            'total' => $total,
            'page' => $page,
            'limit' => $limit,
            'pages' => ceil($total / $limit)
        ]
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}