<?php
/**
 * CLEAR (Delete) assignment for a match: Chrono, Stats, Equipment check, or States.
 * POST: match_id, type (chrono, stats, equipment_check, states)
 */
require_once __DIR__ . '/../config/cors.php';
header('Content-Type: application/json');
require_once __DIR__ . '/../config/db.php';

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

$matchId = (int) ($data['match_id'] ?? 0);
$type = $data['type'] ?? '';

if ($matchId < 1 || empty($type)) {
    echo json_encode(['status' => 'error', 'message' => 'match_id and type are required']);
    exit;
}

$allowedTypes = ['chrono', 'stats', 'equipment_check', 'states', 'quarter_master', 'range_master'];
$stmtRef = $pdo->query("SELECT name FROM reference_match_assignments");
while ($row = $stmtRef->fetchColumn()) {
    $allowedTypes[] = strtolower(str_replace(' ', '_', trim($row)));
}

if (!in_index($type, $allowedTypes)) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid assignment type']);
    exit;
}

function in_index($needle, $haystack)
{
    return in_array($needle, $haystack);
}

$table = 'match_' . $type . '_assignments';

try {
    $userId = (int) ($data['user_id'] ?? 0);
    $stmt = $pdo->prepare("DELETE FROM `$table` WHERE match_id = ? AND submitted_by = ?");
    $stmt->execute([$matchId, $userId]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Draft cleared successfully'
    ]);
} catch (PDOException $e) {
    echo json_encode([
        'status' => 'error',
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>