<?php

declare(strict_types=1);

require_once __DIR__ . '/helpers.php';
require_once dirname(__DIR__, 2) . '/core/upload.php';

$settingsModuleBoot = 'settings_module_boot';
$validateSettingsPayload = 'validate_settings_payload';

$settingsModuleBoot();

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

require_valid_csrf();

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

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

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

    $existing = settings_form_values();

    if (isset($_FILES['league_logo']) && (int) ($_FILES['league_logo']['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_NO_FILE) {
        try {
            $payload['league_logo'] = upload_file($_FILES['league_logo'], ['directory' => 'branding']);
        } catch (RuntimeException $exception) {
            flash('errors', ['league_logo' => $exception->getMessage()]);
            flash('error', ['type' => 'danger', 'message' => 'Please correct the settings form errors.']);
            redirect('app/modules/settings/index.php');
        }
    }

    foreach ($payload as $key => $value) {
        db_query(
            'INSERT INTO system_settings (setting_key, setting_value)
             VALUES (:setting_key, :setting_value)
             ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)',
            ['setting_key' => $key, 'setting_value' => $value]
        );
    }

    if (!empty($payload['league_logo']) && ($existing['league_logo'] ?? '') !== '' && ($existing['league_logo'] ?? '') !== $payload['league_logo']) {
        delete_uploaded_file((string) $existing['league_logo']);
    }

    audit_log('update_settings', 'system_settings', null, $existing, $payload);
    clear_old_input();
    flash('success', ['type' => 'success', 'message' => 'System settings updated successfully.']);
}

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