<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';

$financeModuleBoot = 'finance_module_boot';
$validateFinancePaymentPayload = 'validate_finance_payment_payload';
$validateFinanceRecordPayload = 'validate_finance_record_payload';
$findFinancePaymentOrAbort = 'find_finance_payment_or_abort';
$canManageFinance = 'can_manage_finance';
$canRecordPayments = 'can_record_payments';

$financeModuleBoot();

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

require_valid_csrf();

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

if ($action === 'create') {
    if (!$canManageFinance()) {
        abort_request(403, 'Access denied', 'You do not have permission to create payment records.');
    }

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

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

    db_query(
        'INSERT INTO club_payments (
            club_id, season_id, payment_type, amount, amount_paid,
            payment_status, payment_reference, payment_date, created_at
         ) VALUES (
            :club_id, :season_id, :payment_type, :amount, :amount_paid,
            :payment_status, :payment_reference, :payment_date, NOW()
         )',
        $payload
    );

    $paymentId = (int) db()->lastInsertId();
    audit_log('create_payment', 'club_payments', $paymentId, null, $payload);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Payment record created successfully.']);
    redirect('app/modules/finance/view.php?id=' . $paymentId);
}

if ($action === 'update') {
    if (!$canManageFinance()) {
        abort_request(403, 'Access denied', 'You do not have permission to update payment records.');
    }

    $paymentId = (int) ($_POST['id'] ?? 0);
    $existingPayment = $findFinancePaymentOrAbort($paymentId);
    remember_old_input($_POST);
    $errors = [];
    $payload = $validateFinancePaymentPayload($_POST, $errors, $paymentId);

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

    db_query(
        'UPDATE club_payments
         SET club_id = :club_id,
             season_id = :season_id,
             payment_type = :payment_type,
             amount = :amount,
             amount_paid = :amount_paid,
             payment_status = :payment_status,
             payment_reference = :payment_reference,
             payment_date = :payment_date
         WHERE id = :id',
        $payload + ['id' => $paymentId]
    );

    audit_log('update_payment', 'club_payments', $paymentId, $existingPayment, $payload);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'Payment record updated successfully.']);
    redirect('app/modules/finance/view.php?id=' . $paymentId);
}

if ($action === 'record') {
    if (!$canRecordPayments()) {
        abort_request(403, 'Access denied', 'You do not have permission to record payments.');
    }

    $paymentId = (int) ($_POST['id'] ?? 0);
    $existingPayment = $findFinancePaymentOrAbort($paymentId);
    $errors = [];
    $payload = $validateFinanceRecordPayload($_POST, $existingPayment, $errors);

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

    db_query(
        'UPDATE club_payments
         SET amount_paid = :amount_paid,
             payment_status = :payment_status,
             payment_date = :payment_date
         WHERE id = :id',
        $payload + ['id' => $paymentId]
    );

    audit_log('record_payment', 'club_payments', $paymentId, $existingPayment, $payload);
    flash('success', ['type' => 'success', 'message' => 'Payment recorded successfully.']);
    redirect('app/modules/finance/view.php?id=' . $paymentId);
}

if ($action === 'delete') {
    if (!$canManageFinance()) {
        abort_request(403, 'Access denied', 'You do not have permission to delete payment records.');
    }

    $paymentId = (int) ($_POST['id'] ?? 0);
    $existingPayment = $findFinancePaymentOrAbort($paymentId);
    db_query('DELETE FROM club_payments WHERE id = :id', ['id' => $paymentId]);
    audit_log('delete_payment', 'club_payments', $paymentId, $existingPayment, null);
    flash('success', ['type' => 'success', 'message' => 'Payment record deleted successfully.']);
    redirect('app/modules/finance/index.php');
}

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