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

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

$input = json_decode(file_get_contents('php://input'), true);

$timezone = $input['timezone'] ?? 'America/New_York';
$startTime = $input['start_time'] ?? '09:00';
$endTime = $input['end_time'] ?? '17:00';
$workingDays = $input['working_days'] ?? [];

try {
    $pdo = hw_db();
    
    // Get coach ID for current user
    $coachStmt = $pdo->prepare('SELECT id FROM coaches WHERE user_id = ?');
    $coachStmt->execute([(int)$user['sub']]);
    $coach = $coachStmt->fetch();
    
    if (!$coach) {
        hw_json(['success' => false, 'message' => 'Coach profile not found'], 404);
    }
    
    $coachId = $coach['id'];
    
    // Clear existing availability
    $deleteStmt = $pdo->prepare('DELETE FROM coach_availability WHERE coach_id = ?');
    $deleteStmt->execute([$coachId]);
    
    // Insert new availability for each working day
    $insertStmt = $pdo->prepare('
        INSERT INTO coach_availability (coach_id, weekday, start_time, end_time, timezone)
        VALUES (?, ?, ?, ?, ?)
    ');
    
    // Map day names to weekday numbers (0=Sunday, 1=Monday, ..., 6=Saturday)
    $dayMap = [
        'Sunday' => 0,
        'Monday' => 1,
        'Tuesday' => 2,
        'Wednesday' => 3,
        'Thursday' => 4,
        'Friday' => 5,
        'Saturday' => 6
    ];
    
    foreach ($workingDays as $day) {
        if (isset($dayMap[$day])) {
            $insertStmt->execute([
                $coachId,
                $dayMap[$day],
                $startTime,
                $endTime,
                $timezone
            ]);
        }
    }

    hw_json([
        'success' => true,
        'message' => 'Availability updated successfully'
    ]);
} catch (Throwable $e) {
    hw_json(['success' => false, 'message' => 'Server error', 'error' => $e->getMessage()], 500);
}
