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

// Delete a weekly availability slot.
// Method: DELETE (accepts id via query string ?id= or JSON body {"id": number})
// Auth: coach can delete own slots; admin can delete any.

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

// Read id from query or JSON body
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) {
    $payload = hw_input_json();
    $id = (int)($payload['id'] ?? 0);
}
if ($id <= 0) hw_json(['message' => 'Valid id is required'], 422);

try {
    $pdo = hw_db();

    // Load slot with owning user id
    $stmt = $pdo->prepare('SELECT ca.id, ca.coach_id, c.user_id FROM coach_availability ca JOIN coaches c ON c.id = ca.coach_id WHERE ca.id = ? LIMIT 1');
    $stmt->execute([$id]);
    $slot = $stmt->fetch();
    if (!$slot) hw_json(['message' => 'Availability slot not found'], 404);

    // Roles of current user
    $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) {
        if (!$isCoach) hw_json(['message' => 'Forbidden'], 403);
        if ((int)$slot['user_id'] !== (int)$auth['sub']) hw_json(['message' => 'You do not own this slot'], 403);
    }

    // Delete
    $stmt = $pdo->prepare('DELETE FROM coach_availability WHERE id = ?');
    $stmt->execute([$id]);

    // Audit
    $pdo->prepare('INSERT INTO audit_logs (user_id, action, meta) VALUES (?, ?, JSON_OBJECT("slot_id", ?, "coach_id", ?))')
        ->execute([(int)$auth['sub'], 'coach_availability_delete', (int)$slot['id'], (int)$slot['coach_id']]);

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