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

// Create a weekly availability slot for a coach.
// Auth required. Coach can create their own slots; admin can create for any coach (coach_id in payload).

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

$input = hw_input_json();
$weekday = isset($input['weekday']) ? (int)$input['weekday'] : -1; // 0..6
$start = hw_sanitize_string($input['start_time'] ?? ''); // HH:MM or HH:MM:SS
$end = hw_sanitize_string($input['end_time'] ?? '');
$tz = hw_sanitize_string($input['timezone'] ?? 'UTC');
$targetCoachId = isset($input['coach_id']) ? (int)$input['coach_id'] : null;

if ($weekday < 0 || $weekday > 6) hw_json(['message' => 'weekday must be between 0 (Sun) and 6 (Sat)'], 422);

// Normalize time to HH:MM:SS
$normTime = function(string $t): ?string {
    if ($t === '') return null;
    if (preg_match('/^\d{2}:\d{2}$/', $t)) return $t . ':00';
    if (preg_match('/^\d{2}:\d{2}:\d{2}$/', $t)) return $t;
    return null;
};
$startNorm = $normTime($start);
$endNorm = $normTime($end);
if (!$startNorm || !$endNorm) hw_json(['message' => 'start_time and end_time must be HH:MM or HH:MM:SS'], 422);
if ($startNorm >= $endNorm) hw_json(['message' => 'end_time must be after start_time'], 422);

try {
    $pdo = hw_db();

    // Roles
    $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());
    $isAdmin = in_array('admin', $roles, true);
    $isCoach = in_array('coach', $roles, true);
    if (!$isAdmin && !$isCoach) hw_json(['message' => 'Forbidden'], 403);

    // Resolve coach_id
    $coachId = $targetCoachId;
    if ($coachId !== null) {
        if (!$isAdmin) hw_json(['message' => 'Only admin can specify coach_id'], 403);
        // Validate coach exists
        $stmt = $pdo->prepare('SELECT id FROM coaches WHERE id = ? LIMIT 1');
        $stmt->execute([$coachId]);
        if (!$stmt->fetch()) hw_json(['message' => 'Coach not found'], 404);
    } else {
        // Find coach profile for current user; create minimal if not exists and user is coach
        $stmt = $pdo->prepare('SELECT id FROM coaches WHERE user_id = ? LIMIT 1');
        $stmt->execute([(int)$auth['sub']]);
        $row = $stmt->fetch();
        if ($row) {
            $coachId = (int)$row['id'];
        } else {
            if (!$isCoach) hw_json(['message' => 'Coach profile not found'], 404);
            // Create minimal coach profile
            $stmt = $pdo->prepare('SELECT first_name, last_name FROM users WHERE id = ? LIMIT 1');
            $stmt->execute([(int)$auth['sub']]);
            $u = $stmt->fetch();
            $display = trim(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? '')) ?: 'Coach';
            $stmt = $pdo->prepare('INSERT INTO coaches (user_id, display_name, bio, certifications, expertise) VALUES (?, ?, NULL, NULL, NULL)');
            $stmt->execute([(int)$auth['sub'], $display]);
            $coachId = (int)$pdo->lastInsertId();
        }
    }

    // Overlap check: any slot on same weekday overlapping interval?
    $stmt = $pdo->prepare('SELECT COUNT(1) AS cnt FROM coach_availability WHERE coach_id = ? AND weekday = ? AND NOT (end_time <= ? OR start_time >= ?)');
    $stmt->execute([$coachId, $weekday, $startNorm, $endNorm]);
    $cnt = (int)($stmt->fetch()['cnt'] ?? 0);
    if ($cnt > 0) hw_json(['message' => 'Availability overlaps with existing slot'], 409);

    // Insert slot
    $stmt = $pdo->prepare('INSERT INTO coach_availability (coach_id, weekday, start_time, end_time, timezone) VALUES (?, ?, ?, ?, ?)');
    $stmt->execute([$coachId, $weekday, $startNorm, $endNorm, $tz ?: 'UTC']);
    $id = (int)$pdo->lastInsertId();

    // Audit
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("coach_id", ?, "weekday", ?, "start", ?, "end", ?, "tz", ?))')
        ->execute([(int)$auth['sub'], 'coach_availability_create', $coachId, $weekday, $startNorm, $endNorm, $tz ?: 'UTC']);

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