<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

$venueModuleBoot = 'venue_module_boot';
$validateVenuePayload = 'validate_venue_payload';
$findVenueOrAbort = 'find_venue_or_abort';
$venueHasDependencies = 'venue_has_dependencies';

$venueModuleBoot();

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

require_valid_csrf();

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

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

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

    db_query(
        'INSERT INTO venues (name, location, capacity, pitch_type, status, created_at)
         VALUES (:name, :location, :capacity, :pitch_type, :status, NOW())',
        $payload
    );

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

if ($action === 'update') {
    $venueId = (int) ($_POST['id'] ?? 0);
    $existingVenue = $findVenueOrAbort($venueId);
    remember_old_input($_POST);
    $errors = [];
    $payload = $validateVenuePayload($_POST, $errors, $venueId);

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

    db_query(
        'UPDATE venues
         SET name = :name,
             location = :location,
             capacity = :capacity,
             pitch_type = :pitch_type,
             status = :status
         WHERE id = :id',
        $payload + ['id' => $venueId]
    );

    audit_log('update_venue', 'venues', $venueId, $existingVenue, $payload);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Venue updated successfully.']);
    redirect('app/modules/venues/view.php?id=' . $venueId);
}

if ($action === 'delete') {
    $venueId = (int) ($_POST['id'] ?? 0);
    $existingVenue = $findVenueOrAbort($venueId);

    if ($venueHasDependencies($venueId)) {
        flash('error', ['type' => 'danger', 'message' => 'This venue cannot be deleted while fixtures are still linked to it.']);
        redirect('app/modules/venues/delete.php?id=' . $venueId);
    }

    db_query('DELETE FROM venues WHERE id = :id', ['id' => $venueId]);
    audit_log('delete_venue', 'venues', $venueId, $existingVenue, null);
    flash('success', ['type' => 'success', 'message' => 'Venue deleted successfully.']);
    redirect('app/modules/venues/index.php');
}

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