<?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_name', 'site_logo', 'site_logo_position', 'site_primary_color', 'site_accent_color', 'privacy_text', 'legal_text', 'contact_enabled', 'copyright'];
$data = array_fill_keys($keys, '');
$query = db()->prepare('SELECT setting_key, setting_value FROM ' . table('settings') . ' WHERE setting_key IN (' . implode(',', array_fill(0, count($keys), '?')) . ')');
$query->execute($keys);
foreach ($query->fetchAll() as $row) { $data[(string)$row['setting_key']] = (string)$row['setting_value']; }
 $error = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verify_csrf();
    $oldLogo = (string)$data['site_logo'];
    $deleteLogo = isset($_POST['delete_site_logo']);
    $logo = $deleteLogo ? '' : $oldLogo;
    if (!empty($_FILES['site_logo']['tmp_name'])) {
        if ((int)$_FILES['site_logo']['size'] > 5 * 1024 * 1024) {
            $error = t('website_footer.logo_error_size');
        } else {
            $image = @getimagesize($_FILES['site_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['site_logo']['tmp_name'], __DIR__ . '/' . $newLogo)) {
                        $error = t('website_footer.logo_error_save');
                    } else {
                        if ($oldLogo !== '' && str_starts_with($oldLogo, 'uploads/site-logo/')) { @unlink(__DIR__ . '/' . $oldLogo); }
                        $logo = $newLogo;
                    }
                }
            }
        }
    }
    if ($error === null) {
    if ($deleteLogo && empty($_FILES['site_logo']['tmp_name']) && $oldLogo !== '' && str_starts_with($oldLogo, 'uploads/site-logo/')) { @unlink(__DIR__ . '/' . $oldLogo); }
    $save = db()->prepare('INSERT INTO ' . table('settings') . ' (setting_key, setting_value) VALUES (:key, :value) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)');
    $values = ['site_name'=>trim((string)($_POST['site_name'] ?? '')), 'site_primary_color'=>triptale_theme_color((string)($_POST['site_primary_color'] ?? ''), '#126e82'), 'site_accent_color'=>triptale_theme_color((string)($_POST['site_accent_color'] ?? ''), '#e3ebee'), 'privacy_text'=>(string)($_POST['privacy_text'] ?? ''), 'legal_text'=>(string)($_POST['legal_text'] ?? ''), 'contact_enabled'=>isset($_POST['contact_enabled']) ? '1' : '0', 'copyright'=>trim((string)($_POST['copyright'] ?? '') )];
    foreach ($values as $key => $value) { $save->execute([':key'=>$key, ':value'=>$value]); }
    header('Location: /website-footer-settings.php?saved=1'); exit;
    }
}
$toolbar = static function (string $editorId): string {
    ob_start(); ?>
    <div class="editor-toolbar" data-editor-toolbar="<?= htmlspecialchars($editorId, ENT_QUOTES, 'UTF-8') ?>">
        <button type="button" data-command="bold"><b><?= htmlspecialchars(t('editor.bold'), ENT_QUOTES, 'UTF-8') ?></b></button>
        <button type="button" data-command="italic"><i><?= htmlspecialchars(t('editor.italic'), ENT_QUOTES, 'UTF-8') ?></i></button>
        <button type="button" data-command="insertUnorderedList"><?= htmlspecialchars(t('editor.list'), ENT_QUOTES, 'UTF-8') ?></button>
        <button type="button" data-command="insertOrderedList"><?= htmlspecialchars(t('editor.numbered_list'), ENT_QUOTES, 'UTF-8') ?></button>
        <button type="button" data-command="createLink"><?= htmlspecialchars(t('editor.link'), ENT_QUOTES, 'UTF-8') ?></button>
        <select data-style-select><option value=""><?= htmlspecialchars(t('editor.style'), ENT_QUOTES, 'UTF-8') ?></option><option value="p"><?= htmlspecialchars(t('editor.normal'), ENT_QUOTES, 'UTF-8') ?></option><option value="h2"><?= htmlspecialchars(t('editor.heading'), ENT_QUOTES, 'UTF-8') ?></option><option value="h3"><?= htmlspecialchars(t('editor.small_heading'), ENT_QUOTES, 'UTF-8') ?></option></select>
    </div>
    <?php return (string)ob_get_clean();
};
?><!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('website_footer.title'), ENT_QUOTES, 'UTF-8') ?></title><style>
body{font-family:system-ui,sans-serif;background:#f4f6f8;margin:0;padding:32px;color:#17202a}main{max-width:720px;margin:auto;background:#fff;padding:28px;border-radius:14px}.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;margin-bottom:12px}label{display:block;margin-top:16px;font-weight:700}input,select{box-sizing:border-box;width:100%;padding:10px;margin-top:6px}small{display:block;margin-top:5px;color:#59636d}.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}.logo-preview{display:block;width:100%;max-height:180px;object-fit:contain!important;border-radius:14px;clip-path:inset(0 round 14px);background:#f4f6f8;margin:14px 0}.delete{background:#9d2d2d;margin-top:8px}.error{background:#ffe6e3;padding:10px;border-radius:7px}.editor-toolbar{display:flex;flex-wrap:wrap;gap:5px;margin-top:6px;padding:7px;border:1px solid #b9c1c8;border-bottom:0;border-radius:7px 7px 0 0;background:#edf2f3}.editor-toolbar button,.editor-toolbar select{margin:0;padding:6px 9px;background:#fff;color:#17202a;border:1px solid #b9c1c8;border-radius:4px;font:inherit}.rich-editor{min-height:150px;padding:11px;border:1px solid #b9c1c8;border-radius:0 0 7px 7px;font-weight:400}.rich-editor:focus{outline:2px solid #75aeb9;outline-offset:-2px}.rich-editor p:first-child{margin-top:0}.rich-editor p:last-child{margin-bottom:0}.ok{background:#e6f5e9;padding:10px;border-radius:7px}.save{margin-top:22px}@media(max-width:600px){body{padding:12px}main{padding:16px}.back{display:inline-block;width:auto;max-width:100%;text-align:left}.file-picker{display:block;text-align:center}}
</style><style>.theme-color{width:74px!important;height:44px!important;padding:3px!important}.settings-tabs{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 18px}.settings-tab{background:#e3ebee!important;color:#126e82!important;border:1px solid #c5d8dd!important}.settings-tab.active{background:#126e82!important;color:#fff!important;border-color:#126e82!important}</style></head><body><main>
<a class="button back" href="/dashboard.php"><?= htmlspecialchars(t('settings.back'), ENT_QUOTES, 'UTF-8') ?></a><h1><?= htmlspecialchars(t('settings.title'), ENT_QUOTES, 'UTF-8') ?></h1><nav class="settings-tabs"><a class="button settings-tab" href="/settings.php"><?= htmlspecialchars(t('settings.mail'), ENT_QUOTES, 'UTF-8') ?></a><a class="button settings-tab active" href="/website-footer-settings.php"><?= htmlspecialchars(t('settings.website_footer'), ENT_QUOTES, 'UTF-8') ?></a></nav>
<?php if (isset($_GET['saved'])): ?><p class="ok"><?= htmlspecialchars(t('website_footer.saved'), ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?><?php if ($error !== null): ?><p class="error"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></p><?php endif; ?>
<form method="post" enctype="multipart/form-data" id="website-footer-form"><input type="hidden" name="csrf_token" value="<?= htmlspecialchars(csrf_token(), ENT_QUOTES, 'UTF-8') ?>"><input type="hidden" name="privacy_text" id="privacy-text"><input type="hidden" name="legal_text" id="legal-text">
<label><?= htmlspecialchars(t('website_footer.site_name'), ENT_QUOTES, 'UTF-8') ?><input name="site_name" value="<?= htmlspecialchars((string)$data['site_name'], ENT_QUOTES, 'UTF-8') ?>"></label><small><?= htmlspecialchars(t('website_footer.site_name_hint'), ENT_QUOTES, 'UTF-8') ?></small>
<label><?= htmlspecialchars(t('website_footer.primary_color'), ENT_QUOTES, 'UTF-8') ?><input class="theme-color" type="color" name="site_primary_color" value="<?= htmlspecialchars(triptale_theme_color((string)$data['site_primary_color'], '#126e82'), ENT_QUOTES, 'UTF-8') ?>"></label><small><?= htmlspecialchars(t('website_footer.primary_color_hint'), ENT_QUOTES, 'UTF-8') ?></small>
<label><?= htmlspecialchars(t('website_footer.accent_color'), ENT_QUOTES, 'UTF-8') ?><input class="theme-color" type="color" name="site_accent_color" value="<?= htmlspecialchars(triptale_theme_color((string)$data['site_accent_color'], '#e3ebee'), ENT_QUOTES, 'UTF-8') ?>"></label><small><?= htmlspecialchars(t('website_footer.accent_color_hint'), ENT_QUOTES, 'UTF-8') ?></small>
<a class="button" href="/logo-upload.php"><?= htmlspecialchars(t('website_footer.logo_edit'), ENT_QUOTES, 'UTF-8') ?></a>
<label><?= htmlspecialchars(t('website_footer.privacy'), ENT_QUOTES, 'UTF-8') ?></label><?= $toolbar('privacy-editor') ?><div class="rich-editor" id="privacy-editor" contenteditable="true"><?= render_rich_text((string)$data['privacy_text']) ?></div>
<label><?= htmlspecialchars(t('website_footer.legal'), ENT_QUOTES, 'UTF-8') ?></label><?= $toolbar('legal-editor') ?><div class="rich-editor" id="legal-editor" contenteditable="true"><?= render_rich_text((string)$data['legal_text']) ?></div>
<label><input style="width:auto" type="checkbox" name="contact_enabled"<?= $data['contact_enabled'] === '1' ? ' checked' : '' ?>> <?= htmlspecialchars(t('website_footer.contact_enabled'), ENT_QUOTES, 'UTF-8') ?></label><label><?= htmlspecialchars(t('website_footer.copyright'), ENT_QUOTES, 'UTF-8') ?><input name="copyright" value="<?= htmlspecialchars((string)$data['copyright'], ENT_QUOTES, 'UTF-8') ?>"></label><button class="save" type="submit"><?= htmlspecialchars(t('website_footer.save'), ENT_QUOTES, 'UTF-8') ?></button></form>
</main><script>
document.querySelectorAll('[data-editor-toolbar]').forEach(function(toolbar){var editor=document.getElementById(toolbar.dataset.editorToolbar);toolbar.querySelectorAll('button[data-command]').forEach(function(button){button.addEventListener('click',function(){editor.focus();var command=button.dataset.command;if(command==='createLink'){var url=window.prompt('https://');if(url){document.execCommand('createLink',false,url);}}else{document.execCommand(command,false,null);}});});toolbar.querySelector('[data-style-select]').addEventListener('change',function(){if(this.value){editor.focus();document.execCommand('formatBlock',false,'<'+this.value+'>');this.value='';}});});var logoInput=document.getElementById('site-logo-input'),logoName=document.getElementById('site-logo-name');if(logoInput&&logoName){logoInput.addEventListener('change',function(){logoName.textContent=this.files&&this.files[0]?this.files[0].name:<?= json_encode(t('website_footer.logo_empty'), JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;});}document.getElementById('website-footer-form').addEventListener('submit',function(){document.getElementById('privacy-text').value=document.getElementById('privacy-editor').innerHTML;document.getElementById('legal-text').value=document.getElementById('legal-editor').innerHTML;});
</script></body></html>
