<?php
declare(strict_types=1);

require_once __DIR__ . '/app/Helpers/bootstrap.php';

$user = require_login();
if ($user['role'] !== 'main_admin') { http_response_code(403); exit('Access denied.'); }

$keys = ['site_logo', 'site_logo_position'];
$data = array_fill_keys($keys, '');
$query = db()->prepare('SELECT setting_key, setting_value FROM ' . table('settings') . ' WHERE setting_key IN (?, ?)');
$query->execute($keys);
foreach ($query->fetchAll() as $row) { $data[(string)$row['setting_key']] = (string)$row['setting_value']; }
$error = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_logo'])) {
    verify_csrf();
    $old = (string)$data['site_logo'];
    if ($old !== '' && str_starts_with($old, 'uploads/site-logo/')) { @unlink(__DIR__ . '/' . $old); }
    $save = db()->prepare('INSERT INTO ' . table('settings') . ' (setting_key, setting_value) VALUES (:key, :value) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)');
    $save->execute([':key' => 'site_logo', ':value' => '']);
    header('Location: /website-footer-settings.php?logo=deleted'); exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $position = (($_POST['site_logo_position'] ?? '') === 'right') ? 'right' : 'left';
    $logo = (string)$data['site_logo'];
    if (!empty($_FILES['logo']['tmp_name'])) {
        if ((int)$_FILES['logo']['size'] > 5 * 1024 * 1024) {
            $error = t('website_footer.logo_error_size');
        } else {
            $image = @getimagesize($_FILES['logo']['tmp_name']);
            $extensions = [IMAGETYPE_JPEG => 'jpg', IMAGETYPE_PNG => 'png', IMAGETYPE_WEBP => 'webp'];
            if (!$image || !isset($extensions[$image[2]])) {
                $error = t('website_footer.logo_error_type');
            } else {
                $directory = __DIR__ . '/uploads/site-logo';
                if (!is_dir($directory) && !mkdir($directory, 0755, true)) {
                    $error = t('website_footer.logo_error_directory');
                } else {
                    $newLogo = 'uploads/site-logo/logo-' . bin2hex(random_bytes(10)) . '.' . $extensions[$image[2]];
                    if (!move_uploaded_file($_FILES['logo']['tmp_name'], __DIR__ . '/' . $newLogo)) {
                        $error = t('website_footer.logo_error_save');
                    } else {
                        if ($logo !== '' && str_starts_with($logo, 'uploads/site-logo/')) { @unlink(__DIR__ . '/' . $logo); }
                        $logo = $newLogo;
                    }
                }
            }
        }
    } elseif ($logo === '') {
        $error = t('logo.error_choose');
    }
    if ($error === null) {
        $save = db()->prepare('INSERT INTO ' . table('settings') . ' (setting_key, setting_value) VALUES (:key, :value) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)');
        $save->execute([':key' => 'site_logo', ':value' => $logo]);
        $save->execute([':key' => 'site_logo_position', ':value' => $position]);
        header('Location: /website-footer-settings.php?logo=changed'); exit;
    }
}
?>
<!doctype html><html lang="<?= htmlspecialchars(language(), ENT_QUOTES, 'UTF-8') ?>"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?= htmlspecialchars(t('logo.title'), ENT_QUOTES, 'UTF-8') ?></title>
<style>
body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:24px;color:#17202a}main{max-width:620px;margin:auto;background:#fff;padding:24px;border-radius:14px;box-shadow:0 4px 18px #0001}.button,button{display:inline-block;padding:10px 13px;background:#126e82;color:#fff;border:0;border-radius:7px;text-decoration:none;font:inherit;font-weight:700;cursor:pointer}.back{background:#e3ebee;color:#126e82}.back+h1{margin-top:26px}.delete{background:#9d2d2d}.error{background:#ffe6e3;padding:12px;border-radius:7px}.preview{display:block;width:100%;max-height:320px;object-fit:contain!important;border-radius:14px;clip-path:inset(0 round 14px);background:#f4f6f8;margin:14px 0}.file-area{margin-top:20px;padding:16px;background:#edf5f6;border-left:4px solid #75aeb9;border-radius:10px}.file-area h2{font-size:1.05rem;margin:0 0 6px}.file-hint{margin:0 0 12px;color:#59636d;font-size:.92rem}.file-picker{display:inline-block;padding:10px 13px;background:#126e82;color:#fff;border-radius:7px;font-weight:700;cursor:pointer}.file-picker input{position:absolute;width:1px;height:1px;opacity:0;overflow:hidden}.file-name{display:block;margin-top:10px;color:#59636d;font-size:.92rem;overflow-wrap:anywhere}.position{display:block;margin-top:16px;font-weight:700}.position select{box-sizing:border-box;width:100%;padding:10px;margin-top:6px;border:1px solid #b9c1c8;border-radius:7px;background:#fff;font:inherit}.save{margin-top:16px}.delete-form{margin-top:8px}*{box-sizing:border-box}@media(max-width:600px){body{padding:12px}main{padding:16px}.button:not(.back),button{width:100%;text-align:center}.back{display:inline-block!important;width:auto!important;max-width:100%;white-space:normal}.back+h1{margin-top:22px}.file-picker{display:block;text-align:center}.save{width:100%}}
</style><link rel="stylesheet" href="/assets/triptale-ui.css?v=19"></head><body><main>
<a class="button back" href="/website-footer-settings.php"><?= htmlspecialchars(t('logo.back'), ENT_QUOTES, 'UTF-8') ?></a>
<h1><?= htmlspecialchars(t('logo.title'), ENT_QUOTES, 'UTF-8') ?></h1>
<?php if ($data['site_logo'] !== ''): ?><img class="preview" src="/<?= htmlspecialchars((string)$data['site_logo'], ENT_QUOTES, 'UTF-8') ?>" alt=""><?php endif; ?>
<?php if ($error): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>
<form method="post" enctype="multipart/form-data"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><section class="file-area"><h2><?= htmlspecialchars(t('website_footer.logo_choose'), ENT_QUOTES, 'UTF-8') ?></h2><p class="file-hint"><?= htmlspecialchars(t('website_footer.logo_hint'), ENT_QUOTES, 'UTF-8') ?></p><label class="file-picker"><?= htmlspecialchars(t('website_footer.logo_select_file'), ENT_QUOTES, 'UTF-8') ?><input id="logo-file" name="logo" type="file" accept="image/jpeg,image/png,image/webp"></label><span class="file-name" id="file-name"><?= htmlspecialchars(t('website_footer.logo_empty'), ENT_QUOTES, 'UTF-8') ?></span></section><label class="position"><?= htmlspecialchars(t('website_footer.logo_position'), ENT_QUOTES, 'UTF-8') ?><select name="site_logo_position"><option value="left"<?= $data['site_logo_position'] !== 'right' ? ' selected' : '' ?>><?= htmlspecialchars(t('website_footer.logo_left'), ENT_QUOTES, 'UTF-8') ?></option><option value="right"<?= $data['site_logo_position'] === 'right' ? ' selected' : '' ?>><?= htmlspecialchars(t('website_footer.logo_right'), ENT_QUOTES, 'UTF-8') ?></option></select></label><button class="save" type="submit"><?= htmlspecialchars(t('logo.save'), ENT_QUOTES, 'UTF-8') ?></button></form>
<?php if ($data['site_logo'] !== ''): ?><form class="delete-form" method="post" onsubmit="return confirm(<?= json_encode(t('website_footer.logo_confirm_delete'), JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>)"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><button name="delete_logo" class="delete" type="submit"><?= htmlspecialchars(t('website_footer.logo_delete'), ENT_QUOTES, 'UTF-8') ?></button></form><?php endif; ?>
</main><script>const fileInput=document.getElementById('logo-file');const fileName=document.getElementById('file-name');fileInput?.addEventListener('change',()=>{fileName.textContent=fileInput.files.length?fileInput.files[0].name:<?= json_encode(t('website_footer.logo_empty'), JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;});</script></body></html>
