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

// List availability windows for a given coach. If coach_id is not provided and the
// requester is an authenticated coach, returns their own availability.

hw_require_method(['GET']);

$auth = hw_auth_user();
$coachIdParam = isset($_GET['coach_id']) ? (int)$_GET['coach_id'] : null;

try {
    $pdo = hw_db();

    $coachId = $coachIdParam;
    if ($coachId === null) {
        if (!$auth) {
            hw_json(['message' => 'coach_id is required for public requests'], 400);
        }
        // Determine if requester is a coach and fetch their coach id
        $stmt = $pdo->prepare('SELECT r.name FROM roles r JOIN user_roles ur ON ur.role_id = r.id WHERE ur.user_id = ?');
        $stmt->execute([(int)$auth['sub']]);
        $roles = array_map(fn($r) => $r['name'], $stmt->fetchAll());
        if (!in_array('coach', $roles, true) && !in_array('admin', $roles, true)) {
            hw_json(['message' => 'coach_id is required'], 400);
        }
        // Find or create coach record for this user
        $stmt = $pdo->prepare('SELECT id FROM coaches WHERE user_id = ? LIMIT 1');
        $stmt->execute([(int)$auth['sub']]);
        $row = $stmt->fetch();
        if (!$row) {
            hw_json(['message' => 'Coach profile not found'], 404);
        }
        $coachId = (int)$row['id'];
    }

    $stmt = $pdo->prepare('SELECT id, weekday, start_time, end_time, timezone FROM coach_availability WHERE coach_id = ? ORDER BY weekday, start_time');
    $stmt->execute([$coachId]);
    $rows = $stmt->fetchAll();

    $out = array_map(function($r){
        return [
            'id' => (int)$r['id'],
            'weekday' => (int)$r['weekday'], // 0..6
            'start_time' => $r['start_time'], // HH:MM:SS
            'end_time' => $r['end_time'],
            'timezone' => $r['timezone'],
        ];
    }, $rows);

    hw_json(['coach_id' => $coachId, 'availability' => $out]);
} catch (Throwable $e) {
    hw_json(['message' => 'Server error', 'error' => $e->getMessage()], 500);
}
