<?php
declare(strict_types=1);

$pageTitle = 'Visual';

require_once __DIR__ . '/includes/auth.php';
require_once __DIR__ . '/includes/api_helpers.php';
require_once __DIR__ . '/includes/uploads.php';

gpc_require_login();

$self = basename((string) ($_SERVER['PHP_SELF'] ?? 'appearance.php'));
$self = $self !== '' ? $self : 'appearance.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!gpc_csrf_check($_POST['csrf'] ?? null)) {
        gpc_flash('bad', 'Sessão expirada. Tente novamente.');
        header('Location: ' . $self);
        exit;
    }

    $saved = false;
    $errors = [];

    foreach (['logo' => 'logo_path', 'bg' => 'bg_path'] as $field => $settingKey) {
        if (
            !isset($_FILES[$field]) ||
            !is_array($_FILES[$field]) ||
            !isset($_FILES[$field]['error']) ||
            (int) $_FILES[$field]['error'] === UPLOAD_ERR_NO_FILE
        ) {
            continue;
        }

        if ((int) $_FILES[$field]['error'] !== UPLOAD_ERR_OK) {
            $errors[] = 'Erro ao enviar imagem';
            continue;
        }

        if (
            !isset($_FILES[$field]['tmp_name']) ||
            !is_string($_FILES[$field]['tmp_name']) ||
            $_FILES[$field]['tmp_name'] === '' ||
            !is_uploaded_file($_FILES[$field]['tmp_name'])
        ) {
            $errors[] = 'Arquivo inválido';
            continue;
        }

        $result = gpc_upload_image($_FILES[$field], 'media');

        if (!is_array($result)) {
            $errors[] = 'Erro ao enviar imagem';
            continue;
        }

        $ok = !empty($result['ok']);
        $path = isset($result['path']) ? trim((string) $result['path']) : '';
        $error = isset($result['error']) ? trim((string) $result['error']) : '';

        if ($ok && $path !== '') {
            $old = (string) gpc_setting($settingKey, '');

            gpc_setting_save($settingKey, $path);

            if ($old !== '' && $old !== $path) {
                gpc_upload_delete($old);
            }

            $saved = true;
            continue;
        }

        $errors[] = $error !== '' ? $error : 'Erro ao enviar imagem';
    }

    if ($errors !== []) {
        gpc_flash('bad', $errors[0]);
    } elseif ($saved) {
        gpc_flash('ok', 'Enviado');
    } else {
        gpc_flash('bad', 'Selecione uma imagem');
    }

    header('Location: ' . $self);
    exit;
}

$csrf = gpc_csrf_token();

$logoSetting = (string) gpc_setting('logo_path', '');
$bgSetting = (string) gpc_setting('bg_path', '');

$logoPath = $logoSetting !== '' ? (string) gpc_upload_public_path($logoSetting) : '';
$bgPath = $bgSetting !== '' ? (string) gpc_upload_public_path($bgSetting) : '';

require_once __DIR__ . '/includes/header.php';
?>

<div class="card">
    <div class="card-body">
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="csrf" value="<?= gpc_h((string) $csrf) ?>">

            <div class="form-grid">
                <div class="field">
                    <label for="logo">Logo</label>
                    <input id="logo" type="file" name="logo" accept="image/jpeg,image/png,image/gif,image/webp">
                    <?php if ($logoPath !== ''): ?>
                        <img class="preview-img" src="<?= gpc_h((string) $logoPath) ?>" alt="Logo atual">
                    <?php endif; ?>
                </div>

                <div class="field">
                    <label for="bg">Background</label>
                    <input id="bg" type="file" name="bg" accept="image/jpeg,image/png,image/gif,image/webp">
                    <?php if ($bgPath !== ''): ?>
                        <img class="preview-img" src="<?= gpc_h((string) $bgPath) ?>" alt="Background atual">
                    <?php endif; ?>
                </div>
            </div>

            <div class="form-actions">
                <button type="submit" class="btn">
                    <i data-lucide="upload"></i> Enviar
                </button>
            </div>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/includes/footer.php'; ?>