<?php
include_once '../config/connect.php';
include_once __DIR__ . '/../../../../vendor/autoload.php';

function website_ensure_favicon_column(mysqli $db): bool
{
    $columnQuery = mysqli_query($db, "SHOW COLUMNS FROM tb_settings LIKE 'favicon'");
    if ($columnQuery && mysqli_num_rows($columnQuery) > 0) {
        return true;
    }

    return (bool)mysqli_query($db, "ALTER TABLE tb_settings ADD COLUMN favicon VARCHAR(255) NULL DEFAULT NULL AFTER brand");
}

function website_upload_favicon(): array
{
    if (!isset($_FILES['favicon']) || !is_array($_FILES['favicon'])) {
        return ['ok' => true, 'path' => ''];
    }

    $file = $_FILES['favicon'];
    $error = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);

    if ($error === UPLOAD_ERR_NO_FILE) {
        return ['ok' => true, 'path' => ''];
    }

    if ($error !== UPLOAD_ERR_OK) {
        return ['ok' => false];
    }

    $tmpName = (string)($file['tmp_name'] ?? '');
    $size = (int)($file['size'] ?? 0);
    $originalName = (string)($file['name'] ?? '');
    $extension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
    $allowedExtensions = ['png', 'jpg', 'jpeg', 'gif', 'webp', 'ico'];

    if ($tmpName === '' || $size <= 0 || $size > 2 * 1024 * 1024 || !in_array($extension, $allowedExtensions, true)) {
        return ['ok' => false];
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mime = (string)$finfo->file($tmpName);
    $allowedMimes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp', 'image/x-icon', 'image/vnd.microsoft.icon'];

    if (!in_array($mime, $allowedMimes, true)) {
        return ['ok' => false];
    }

    $uploadDir = __DIR__ . '/../assets/images/uploads';
    if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true)) {
        return ['ok' => false];
    }

    $fileName = 'favicon-' . bin2hex(random_bytes(8)) . '.' . $extension;
    $targetPath = $uploadDir . '/' . $fileName;

    if (!move_uploaded_file($tmpName, $targetPath)) {
        return ['ok' => false];
    }

    return ['ok' => true, 'path' => 'assets/images/uploads/' . $fileName];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['website'])) {
    
    $config = HTMLPurifier_Config::createDefault();
    $purifier = new HTMLPurifier($config);
    
    $brand_namex = $purifier->purify(trim($_POST['brand_name'] ?? ''));
    $min_topupx = $purifier->purify(trim($_POST['min_topup'] ?? ''));
    $min_ratex = str_replace(',', '.', $purifier->purify(trim($_POST['min_rate'] ?? '')));
    $announcementx = $purifier->purify(trim($_POST['announcement'] ?? ''));

    if ($brand_namex === '' || $min_topupx === '' || $min_ratex === '' || $announcementx === '') {
        header('Location: ../index?page=Settings&msg=36');
        exit();
    }
    if (!ctype_digit($min_topupx)) {
        header('Location: ../index?page=Settings&msg=37');
        exit();
    }
    if (!is_numeric($min_ratex) || (float)$min_ratex < 0.0001) {
        header('Location: ../index?page=Settings&msg=77');
        exit();
    }
    $brand_name = mysqli_real_escape_string($call, $brand_namex);
    $min_topup = (int) $min_topupx;
    $minRateNormalized = rtrim(rtrim(number_format((float)$min_ratex, 4, '.', ''), '0'), '.');
    $min_rate = mysqli_real_escape_string($call, $minRateNormalized);
    $announcement = mysqli_real_escape_string($call, $announcementx);
    $faviconUpload = website_upload_favicon();

    if (!$faviconUpload['ok']) {
        header('Location: ../index?page=Settings&msg=75');
        exit();
    }

    $updates = [
        "brand = '$brand_name'",
        "min_topup = '$min_topup'",
        "annountcement = '$announcement'",
        "rate_coin = '$min_rate'",
    ];

    if ((string)$faviconUpload['path'] !== '') {
        if (!website_ensure_favicon_column($call)) {
            header('Location: ../index?page=Settings&msg=13');
            exit();
        }

        $faviconPath = mysqli_real_escape_string($call, (string)$faviconUpload['path']);
        $updates[] = "favicon = '$faviconPath'";
    }

    $query = "UPDATE tb_settings SET " . implode(', ', $updates) . " WHERE id = 1";

    if (mysqli_query($call, $query)) {
        header('Location: ../index?page=Settings&msg=38');
        exit();
    } else {
        header('Location: ../index?page=Settings&msg=13');
        exit();
    }
} else {
        header('Location: ../index?page=Settings&msg=39');
        exit();
}
?>
