<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

$disciplineModuleBoot = 'discipline_module_boot';
$findSuspensionOrAbort = 'find_suspension_or_abort';
$findDisciplinaryCaseOrAbort = 'find_disciplinary_case_or_abort';
$validateSuspensionPayload = 'validate_suspension_payload';
$validateDisciplinaryCasePayload = 'validate_disciplinary_case_payload';
$canManageDisciplineSuspensions = 'can_manage_discipline_suspensions';
$canManageDisciplineCases = 'can_manage_discipline_cases';

$disciplineModuleBoot();

if (!is_post()) {
    redirect('app/modules/discipline/index.php');
}

require_valid_csrf();

$action = (string) ($_POST['action'] ?? '');

if ($action === 'update_suspension') {
    if (!$canManageDisciplineSuspensions()) {
        abort_request(403, 'Access denied', 'You do not have permission to manage suspensions.');
    }

    $suspensionId = (int) ($_POST['id'] ?? 0);
    $suspension = $findSuspensionOrAbort($suspensionId);
    $errors = [];
    $payload = $validateSuspensionPayload($_POST, $errors);

    if ($errors !== []) {
        flash('error', ['type' => 'danger', 'message' => reset($errors) ?: 'Please correct the suspension form errors.']);
        redirect('app/modules/discipline/suspension.php?id=' . $suspensionId);
    }

    db_query(
        'UPDATE suspensions
         SET matches_served = :matches_served,
             status = :status
         WHERE id = :id',
        $payload + ['id' => $suspensionId]
    );

    audit_log('update_suspension', 'suspensions', $suspensionId, $suspension, $payload);
    flash('success', ['type' => 'success', 'message' => 'Suspension updated successfully.']);
    redirect('app/modules/discipline/suspension.php?id=' . $suspensionId);
}

if ($action === 'update_case') {
    if (!$canManageDisciplineCases()) {
        abort_request(403, 'Access denied', 'You do not have permission to manage disciplinary cases.');
    }

    $caseId = (int) ($_POST['id'] ?? 0);
    $case = $findDisciplinaryCaseOrAbort($caseId);
    $errors = [];
    $payload = $validateDisciplinaryCasePayload($_POST, $errors);

    if ($errors !== []) {
        flash('error', ['type' => 'danger', 'message' => reset($errors) ?: 'Please correct the disciplinary case form errors.']);
        redirect('app/modules/discipline/case.php?id=' . $caseId);
    }

    db_query(
        'UPDATE disciplinary_cases
         SET decision = :decision,
             fine_amount = :fine_amount,
             status = :status
         WHERE id = :id',
        $payload + ['id' => $caseId]
    );

    audit_log('update_disciplinary_case', 'disciplinary_cases', $caseId, $case, $payload);
    flash('success', ['type' => 'success', 'message' => 'Disciplinary case updated successfully.']);
    redirect('app/modules/discipline/case.php?id=' . $caseId);
}

redirect('app/modules/discipline/index.php');
