<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

$awardsModuleBoot = 'awards_module_boot';
$validateAwardPayload = 'validate_award_payload';
$findAwardOrAbort = 'find_award_or_abort';

$awardsModuleBoot();

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

require_valid_csrf();

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

if ($action === 'create') {
    remember_old_input($_POST);
    $errors = [];
    $payload = $validateAwardPayload($_POST, $errors);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the award form errors.']);
        redirect('app/modules/awards/create.php');
    }

    db_query(
        'INSERT INTO awards (
            season_id, competition_id, award_type, club_id, player_id, title, description, created_at
         ) VALUES (
            :season_id, :competition_id, :award_type, :club_id, :player_id, :title, :description, NOW()
         )',
        $payload
    );

    $awardId = (int) db()->lastInsertId();
    audit_log('create_award', 'awards', $awardId, null, $payload);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Award created successfully.']);
    redirect('app/modules/awards/view.php?id=' . $awardId);
}

if ($action === 'update') {
    $awardId = (int) ($_POST['id'] ?? 0);
    $existingAward = $findAwardOrAbort($awardId);
    remember_old_input($_POST);
    $errors = [];
    $payload = $validateAwardPayload($_POST, $errors, $awardId);

    if ($errors !== []) {
        flash('errors', $errors);
        flash('error', ['type' => 'danger', 'message' => 'Please correct the award form errors.']);
        redirect('app/modules/awards/edit.php?id=' . $awardId);
    }

    db_query(
        'UPDATE awards
         SET season_id = :season_id,
             competition_id = :competition_id,
             award_type = :award_type,
             club_id = :club_id,
             player_id = :player_id,
             title = :title,
             description = :description
         WHERE id = :id',
        $payload + ['id' => $awardId]
    );

    audit_log('update_award', 'awards', $awardId, $existingAward, $payload);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Award updated successfully.']);
    redirect('app/modules/awards/view.php?id=' . $awardId);
}

if ($action === 'delete') {
    $awardId = (int) ($_POST['id'] ?? 0);
    $existingAward = $findAwardOrAbort($awardId);
    db_query('DELETE FROM awards WHERE id = :id', ['id' => $awardId]);
    audit_log('delete_award', 'awards', $awardId, $existingAward, null);
    flash('success', ['type' => 'success', 'message' => 'Award deleted successfully.']);
    redirect('app/modules/awards/index.php');
}

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