<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

club_module_boot();

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

require_valid_csrf();

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

if ($action === 'create') {
    if (!can_create_club()) {
        abort_request(403, 'Access denied', 'Club Admin users cannot create clubs.');
    }

    remember_old_input($_POST);
    $errors = [];
    $payload = validate_club_payload($_POST, $errors, null, null);

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

    $logoPath = null;
    if (isset($_FILES['logo']) && ($_FILES['logo']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
        try {
            $logoPath = upload_file($_FILES['logo'], ['directory' => 'clubs', 'max_size' => 2 * 1024 * 1024]);
        } catch (RuntimeException $exception) {
            flash('errors', ['logo' => $exception->getMessage()]);
            flash('error', ['type' => 'danger', 'message' => $exception->getMessage()]);
            redirect('app/modules/clubs/create.php');
        }
    }

    db_query(
        'INSERT INTO clubs (name, short_name, logo, founded_year, stadium_name, contact_person, phone, email, license_status, payment_status, status, created_at, updated_at)
         VALUES (:name, :short_name, :logo, :founded_year, :stadium_name, :contact_person, :phone, :email, :license_status, :payment_status, :status, NOW(), NOW())',
        $payload + ['logo' => $logoPath]
    );

    $clubId = (int) db()->lastInsertId();
    audit_log('create_club', 'clubs', $clubId, null, $payload + ['logo' => $logoPath]);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Club created successfully.']);
    redirect('app/modules/clubs/view.php?id=' . $clubId);
}

if ($action === 'update') {
    $clubId = (int) ($_POST['id'] ?? 0);
    $existingClub = find_club_or_abort($clubId);
    remember_old_input($_POST);
    $errors = [];
    $payload = validate_club_payload($_POST, $errors, $clubId, $existingClub);

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

    $logoPath = $existingClub['logo'];
    if (isset($_FILES['logo']) && ($_FILES['logo']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
        try {
            $logoPath = upload_file($_FILES['logo'], ['directory' => 'clubs', 'max_size' => 2 * 1024 * 1024]);
            delete_uploaded_file($existingClub['logo']);
        } catch (RuntimeException $exception) {
            flash('errors', ['logo' => $exception->getMessage()]);
            flash('error', ['type' => 'danger', 'message' => $exception->getMessage()]);
            redirect('app/modules/clubs/edit.php?id=' . $clubId);
        }
    }

    db_query(
        'UPDATE clubs
         SET name = :name,
             short_name = :short_name,
             logo = :logo,
             founded_year = :founded_year,
             stadium_name = :stadium_name,
             contact_person = :contact_person,
             phone = :phone,
             email = :email,
             license_status = :license_status,
             payment_status = :payment_status,
             status = :status,
             updated_at = NOW()
         WHERE id = :id',
        $payload + ['logo' => $logoPath, 'id' => $clubId]
    );

    audit_log('update_club', 'clubs', $clubId, $existingClub, $payload + ['logo' => $logoPath]);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Club updated successfully.']);
    redirect('app/modules/clubs/view.php?id=' . $clubId);
}

if ($action === 'set_license_status') {
    if (!can('approve_clubs') || is_club_admin()) {
        abort_request(403, 'Access denied', 'Only authorized league staff can approve or reject clubs.');
    }

    $clubId = (int) ($_POST['id'] ?? 0);
    $existingClub = find_club_or_abort($clubId);
    $licenseStatus = (string) ($_POST['license_status'] ?? '');

    if (!in_array($licenseStatus, club_license_options(), true)) {
        flash('error', ['type' => 'danger', 'message' => 'Selected license status is invalid.']);
        redirect('app/modules/clubs/view.php?id=' . $clubId);
    }

    db_query('UPDATE clubs SET license_status = :license_status, updated_at = NOW() WHERE id = :id', ['license_status' => $licenseStatus, 'id' => $clubId]);
    audit_log('set_club_license_status', 'clubs', $clubId, ['license_status' => $existingClub['license_status']], ['license_status' => $licenseStatus]);
    flash('success', ['type' => 'success', 'message' => 'Club licensing status updated successfully.']);
    redirect('app/modules/clubs/view.php?id=' . $clubId);
}

if ($action === 'delete') {
    if (is_club_admin()) {
        abort_request(403, 'Access denied', 'Club Admin users cannot delete clubs.');
    }

    $clubId = (int) ($_POST['id'] ?? 0);
    $existingClub = find_club_or_abort($clubId);

    if (club_has_dependencies($clubId)) {
        flash('error', ['type' => 'danger', 'message' => 'This club cannot be deleted while dependent records still exist.']);
        redirect('app/modules/clubs/delete.php?id=' . $clubId);
    }

    db_query('DELETE FROM clubs WHERE id = :id', ['id' => $clubId]);
    delete_uploaded_file($existingClub['logo']);
    audit_log('delete_club', 'clubs', $clubId, $existingClub, null);
    flash('success', ['type' => 'success', 'message' => 'Club deleted successfully.']);
    redirect('app/modules/clubs/index.php');
}

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