<?php
require_once __DIR__ . '/checklogin.php';
if (!in_array($_SESSION['editor_type'] ?? '', ['admin', 'superadmin'], true)) {
    http_response_code(403);
    exit('Access denied. Settings are restricted to administrators.');
}
require_once('../config.php');

// Check if the PDO connection was established
if (!$pdo) {
    error_log('Error: Could not establish a database connection.', 0);
    die('Error: Could not establish a database connection.');
}

// Function to sanitize user input and prevent XSS
function sanitize_input($input) {
    return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
}

// Function to get a setting from the database using PDO
function settingGet($key) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("SELECT value FROM sm_settings WHERE var = :key");
        $stmt->bindParam(':key', $key, PDO::PARAM_STR);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row['value'] ?? null;
    } catch (PDOException $e) {
        error_log('Error: Could not fetch setting from the database. ' . $e->getMessage(), 0);
        return null;
    }
}

// Function to update the setting in the database using PDO
function settingSet($key, $value) {
    global $pdo;
    try {
        $stmt = $pdo->prepare("UPDATE sm_settings SET value = :value WHERE var = :key");
        $stmt->bindParam(':value', $value, PDO::PARAM_STR);
        $stmt->bindParam(':key', $key, PDO::PARAM_STR);
        $stmt->execute();
        if ($stmt->rowCount() > 0) {
            error_log("Successfully updated setting: $key with value: $value");
        } else {
            error_log("Warning: Setting '$key' may not have been updated.");
        }
    } catch (PDOException $e) {
        error_log('Error: Could not update setting in the database. ' . $e->getMessage(), 0);
    }
}

// Function to generate a CSRF token
function generate_csrf_token() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// Function to validate CSRF token
function validate_csrf_token($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

// Start session safely only if not already started
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Handling form submission for fine settings update
if (isset($_POST['save_fine_settings'])) {
    if (!validate_csrf_token($_POST['csrf_token'])) {
        die('Invalid CSRF token');
    }

    if (isset($_POST['settings']) && is_array($_POST['settings'])) {
        foreach ($_POST['settings'] as $key => $value) {
            $sanitized_value = sanitize_input($value);
            settingSet($key, $sanitized_value);
        }
        $msg = "Fine settings successfully updated.";
    } else {
        $msg = "No settings were updated.";
    }
}

include_once('header.php');
include_once('editors-menu.php');
?>
<h2 class="settings-title">Fine Settings</h2>
<span class="msg" style="display: block; text-align: center; margin: 20px auto; font-size: 18px; color: #4CAF50;"><?php if (isset($msg)) { echo $msg; } ?></span>

<form method="post" class="settings-form">
    <input type="hidden" name="csrf_token" value="<?php echo generate_csrf_token(); ?>">

    <table class="gridtable">
        <tr>
            <th width="250">Option</th>
            <th width="150">Current Value</th>
            <th width="150">Action</th>
        </tr>

        <?php
        // Fetch settings using PDO and exclude specified rows
        $stmt = $pdo->prepare("SELECT * FROM sm_settings WHERE var NOT IN (
            'paypal_email', 
            'submission_fee', 
            'notification_emails', 
            'notification_email_enabled', 
            'site_url', 
            'open_submissions', 
            'show_payment_types', 
            'tos_url', 
            'readertos_url', 
            'allowed_file_types', 
            'max_submissions_per_edition', 
            'accepted_message'
        )");
        $stmt->execute();
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($result as $row) {
            $currentValue = $row['value'] == 'yes' ? 'yes' : 'no';
            $highlightClass = $currentValue == 'yes' ? 'green-highlight' : 'red-highlight';
            $friendlyName = [
                // Reader / volunteer behavior
                'volunteer_readers'           => 'Allow Volunteer Reader Signups',
                'volunteer_reader_in_footer'  => 'Show Reader Signup Link in Footer',
                'reader_notes'                => 'Readers Can View / Leave Private Notes',
                'blind_editor'                => 'Blind Editor Mode (hide submitter identity)',
                'blind_reader_comments'       => 'Hide Submitter Comments from Readers',

                // Slush pile display columns
                'show_payment_types'          => 'Show Payment Type Column on Slush Pile',
                'show_ip_address'             => 'Show IP Address Column on Slush Pile',
                'show_score'                  => 'Show Average Reader Score Column on Slush Pile',

                // Workflow toggles
                'contest_tab'                 => 'Show "Contest Entries" Tab in Editor Menu',
                'paid_only'                   => 'Accept Paid Contest Submissions Only (no free)',
                'final_check'                 => 'Require Contributor Final-Confirmation Step',
                'enable_payments'             => 'Offer Payment-or-Donate Choice to Accepted Poets',
                'show_payment_amount'         => 'Display the Payment Amount in the UI',

                // V7.2 additions
                'allow_downloads'             => 'Allow Users to Download Their Own Submissions',
                'allow_withdraws'             => 'Allow Users to Withdraw Submissions Prior to Acceptance',
                'site_maintenance'            => 'Site Maintenance Mode',
                'user_registration'           => 'Allow User Registration',
                'comment_moderation'          => 'Enable Comment Moderation',
            ];
            $optionLabel = $friendlyName[$row['var']] ?? sanitize_input($row['var']);
        ?>
        <tr>
            <td align="center"><?= $optionLabel ?></td>
            <td align="center">
                <span class="<?= $highlightClass ?>"><?= $currentValue ?></span>
            </td>
            <td align="center">
                <select name="settings[<?= sanitize_input($row['var']) ?>]" class="select-box">
                    <option value="yes" <?= $currentValue == 'yes' ? 'selected' : '' ?>>Yes</option>
                    <option value="no" <?= $currentValue == 'no' ? 'selected' : '' ?>>No</option>
                </select>
            </td>
        </tr>
        <?php
        }
        ?>
    </table>

    <h3 class="settings-subtitle">Submission &amp; Content</h3>
    <table class="gridtable">
        <tr>
            <th width="250">Option</th>
            <th colspan="2">Value</th>
        </tr>
        <tr>
            <td align="center">
                Allowed File Types
                <br /><small>Comma-separated, e.g. <code>.txt, .doc, .docx, .pdf</code></small>
            </td>
            <td colspan="2" align="center">
                <input type="text" name="settings[allowed_file_types]" class="text-setting"
                       value="<?= sanitize_input(settingGet('allowed_file_types') ?? '') ?>" />
            </td>
        </tr>
        <tr>
            <td align="center">
                Reader Signup Terms URL
                <br /><small>Optional link shown on the reader signup page</small>
            </td>
            <td colspan="2" align="center">
                <input type="text" name="settings[readertos_url]" class="text-setting"
                       value="<?= sanitize_input(settingGet('readertos_url') ?? '') ?>" />
            </td>
        </tr>
    </table>

    <br />
    <input type="submit" name="save_fine_settings" value="Save Fine Settings" class="button-primary" />
</form>

<style>
    /* Modern and clean design styles */
    .settings-title {
        font-family: 'Arial', sans-serif;
        font-size: 28px;
        font-weight: bold;
        margin-bottom: 20px;
        text-align: center;
    }

    .settings-form {
        max-width: 800px;
        margin: 0 auto;
        padding: 20px;
        background-color: #f5f5f5;
        border-radius: 8px;
        box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1);
    }

    .gridtable {
        width: 100%;
        border-collapse: collapse;
        margin-top: 20px;
    }

    .gridtable th, .gridtable td {
        padding: 12px 15px;
        text-align: center;
        font-family: 'Arial', sans-serif;
    }

    .gridtable th {
        background-color: #4CAF50;
        color: white;
        font-size: 18px;
    }

    .gridtable tr:nth-child(even) {
        background-color: #f9f9f9;
    }

    .gridtable td {
        font-size: 16px;
    }

    .select-box {
        padding: 6px;
        font-size: 14px;
        border-radius: 4px;
        border: 1px solid #ccc;
    }

    .settings-subtitle {
        font-family: 'Arial', sans-serif;
        font-size: 20px;
        font-weight: bold;
        text-align: center;
        margin: 34px 0 4px;
    }

    .text-setting {
        width: 90%;
        padding: 8px;
        font-size: 14px;
        border-radius: 4px;
        border: 1px solid #ccc;
    }

    .green-highlight {
        background-color: #4CAF50;
        color: #fff;
        padding: 6px 10px;
        border-radius: 4px;
    }

    .red-highlight {
        background-color: #F44336;
        color: #fff;
        padding: 6px 10px;
        border-radius: 4px;
    }

    .button-primary {
        background-color: #4CAF50;
        color: white;
        border: none;
        padding: 10px 20px;
        text-align: center;
        font-size: 16px;
        border-radius: 5px;
        cursor: pointer;
    }

    .button-primary:hover {
        background-color: #45a049;
    }
</style>
<?php
include_once('footer.php');
?>
