#!/usr/bin/php-cgi -dcgi.force_redirect=0
<?php
# encoding: utf-8
# api: cgi
# type: config
# category: admin
# title: Skin editor
# description: Edit current skin parts all at once
# version: 0.7
# state: beta
# depends: php:sqlite
# config: -
# access: admin
#
# Combines header/footer/css/js + th1-setup/default-csp editing.
# Updates current=draft1 directly, backs up into draft9.
#
# · Permits any user listed in 'draft1-users' setting.
# · Stores th1-setup+etc into backup.sql and as draftX-config entries.
# · [Save & Apply] button duplicated for convenience, do the same thing.
#



#-- init
include("./fossil_common.php");
header("Content-Type: text/html; inline");
ini_set("display_errors", 1);
if (empty($_SERVER["FOSSIL_USER"]) || !is_admin() && !in_array($_SERVER["FOSSIL_USER"], allowed_users())) {
    die("Admin or skin editors only");
}
$FIELDS = ['header', 'footer', 'css', 'js', 'th1-setup', 'default-csp', 'details'];


# REPLACE list (SQL blob) from current skin parts
function sql_backup($s="") {
    $db = db();
    foreach (db("SELECT * FROM config WHERE name IN ('header', 'footer', 'css', 'js', 'details', 'default-csp', 'th1-setup')") as $r) {
        $s .= "REPLACE INTO config (name,mtime,value) VALUES ('$r[name]', $r[mtime], {$db->quote($r['value'])});\n";
    }
    return $s;
}


#-- backup download
if (isset($_GET["backup"])) {
    header("Content-Type: text/sql");
    header("Content-Disposition: attachment; filename=fossil-skin-backup-current.txt");
    die(sql_backup());
}
#-- update
elseif (isset($_POST["save"])) {

    # insert skin:Backup*
    if ($_POST["save_bk"]) {
        db("INSERT INTO config (name,mtime,value) VALUES (?, ?, ?)", ["skin:Backup on ".strftime("%Y-%m-%d %H:%M:%S"), time(), sql_backup()]);
    }
    
    # update individual config skin parts
    foreach ($FIELDS AS $field) {
        $old = db("SELECT value FROM config WHERE name=?", [$field]) and $old = $old[0]["value"];
        if ($_POST["save_d9"]) {
            db("REPLACE INTO config (name,mtime,value) VALUES (?, ?, ?)", ["draft9-$field", time(), $old]);
        }
        if ($_POST["save_d1"]) {
            db("REPLACE INTO config (name,mtime,value) VALUES (?, ?, ?)", ["draft1-$field", time(), $_POST[$field]]);
        }
        if (TRUE) {
            db("REPLACE INTO config (name,mtime,value) VALUES (?, ?, ?)", ["$field", time(), $_POST[$field]]);
        }
    }
    print "<div class='fossil-doc' data-title='skin saved'> 🟩 Saved.";

}
#-- display form
else {

    ?>
    <div class='fossil-doc' data-title='skin editor'>
    <style>
     .skin-editor { display: block; width: 800pt; }
     .skin-editor input[type=submit] { margin: 10pt 2pt; }
     /*.skin-editor table td { border: 2pt; }*/
     .skin-editor table tr { background: none !important; }
     .skin-block { display: inline-block; /*background: #eee; border-radius: 10pt;*/ padding: 5pt; }
     .skin-block b { display: block; width: 80pt; background: #ddd; padding: 2pt 8pt; border-radius: 4pt 4pt 0 0; }
     .skin-block textarea { resize: both; border-radius: 0 0 4pt 4pt; }
     .skin-block.inline { display: inline-block; width:500pt; }
    </style>
    <form method=POST enctype="multipart/form-data" class=skin-editor>
    <h3>Skin Editor</h3>
    <input type=submit name=save value='Save &amp; Apply'>
    <br>
    <table cols=2 style="resize:both">
    <colgroup><col width=50%><col width=50%></colgroup>
    <?php

    $stack = ["default-csp", "details"];
    $h = "htmlentities";
    $rows = 15;
    foreach ($FIELDS as $i=>$field) {
        $value = db("SELECT name,value FROM config WHERE name = ?", [$field]);
        $value = $value ? $value[0]["value"] : "";
        #-- table blocks
        if (in_array($field, $stack)) {
            $rows = 3;
            if ($field=="default-csp") { print "<td>"; }
        }
        else {
            if (!$i%2) {
                print "<tr>";
            }
            print "<td>";
        }
        #-- textarea
        print <<<EOF
        <label class="skin-block $field">
           <b>{$field}</b>
           <textarea cols=75 rows=$rows name={$field}>{$h($value)}</textarea>
        </label>   
EOF;
        if ($i%2 and !in_array($field, $stack)) { print "</tr>"; }
    }
    
    ?>
    </tr>
    </table>
    <br>
    <input type=submit name=save value='Save &amp; Apply'>
    <br>
    This will update <b>current</b> skin parts (= directly published).<br>
    <input name=save_d1 value=1 type=checkbox checked> Overwrite <b>draft1</b> with current parts too.<br>
    <input name=save_d9 value=1 type=checkbox checked> Save the previous version to <a href="<?=$_SERVER["FOSSIL_URI"]?>/draft9/home">draft9</a><br>
    <input name=save_bk value=1 type=checkbox checked> But also create a skin:Backup entry<br>
    </form>
    <br><b>Other options</b>
    <ul>
    <li> <a href="<?=$_SERVER["PHP_SELF"]?>?backup=current.txt">backup.sql</a> of current skin
    <li> <a href="<?=$_SERVER["FOSSIL_URI"]?>/setup_skin_admin">skin archive/admin</a>
    <li> <a href="<?=$_SERVER["FOSSIL_URI"]?>/setup_skin">setup_skin</a>
    <li> <a href="<?=$_SERVER["FOSSIL_URI"]?>/setup_skinedit?w=2&sk=1">edit draft1</a>
    <li> Publish to remote repo: <code>fossil config push skin</code>
    </ul>
    <?php
}

?>
</div>
