<?php
// Require an authenticated administrator before touching any settings.
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (empty($_SESSION['editor_is_logged']) || (int)($_SESSION['editor_id'] ?? 0) < 1
    || !in_array($_SESSION['editor_type'] ?? '', ['admin', 'superadmin'], true)) {
    http_response_code(403);
    exit('Access denied.');
}

// Include the configuration file for database credentials
require_once dirname(__DIR__) . '/config.php';

// Backward compatibility for PHP 5.6 and later versions for error reporting
if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
    error_reporting(E_ALL & ~E_DEPRECATED & ~E_STRICT);
} else {
    error_reporting(E_ALL & ~E_NOTICE);
}

// Validate if database constants are defined in config.php
if (!defined('DBHOST') || !defined('DBUSER') || !defined('DBPASS') || !defined('DBNAME')) {
    die('Database configuration missing.');
}

// Database connection using mysqli with error handling
$connect = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);

// Check the connection
if (!$connect) {
    die('Connection failed: ' . mysqli_connect_error());
}

if (isset($_REQUEST['value']) && isset($_REQUEST['id'])) {
    // Use prepared statements to avoid SQL injection
    $stmt = $connect->prepare("UPDATE sm_settings SET value = ? WHERE id = ?");
    
    // Sanitize and bind input parameters
    $value = htmlspecialchars($_REQUEST['value'], ENT_QUOTES, 'UTF-8');
    $id = intval($_REQUEST['id']); // Ensure the ID is treated as an integer

    // Bind the parameters to the prepared statement
    $stmt->bind_param('si', $value, $id);  // 'si' means string, integer

    // Execute the query
    if ($stmt->execute()) {
        // Output the result with XSS protection
        if ($value === 'no') {
            echo "<span style='background: #ff0000; padding: 5px 15px; color: #fff'>" . htmlspecialchars($value, ENT_QUOTES, 'UTF-8') . "</span>";
        } else {
            echo "<span style='background: #5fba7d; padding: 5px 15px; color: #fff'>" . htmlspecialchars($value, ENT_QUOTES, 'UTF-8') . "</span>";
        }
    } else {
        // Error handling in case the query fails
        echo "<span style='color: #ff0000;'>Error updating value.</span>";
    }

    // Close the prepared statement
    $stmt->close();
} else {
    echo "Invalid request.";
}

// Close the database connection
mysqli_close($connect);
?>