<?php
session_start();
include_once('../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Get POST data
$settingKey = isset($_POST['setting_key']) ? mysqli_real_escape_string($con, $_POST['setting_key']) : '';
$settingValue = isset($_POST['setting_value']) ? mysqli_real_escape_string($con, $_POST['setting_value']) : '';
$userId = $_SESSION['uid'];

if (empty($settingKey)) {
    echo json_encode(['success' => false, 'message' => 'Setting key is required']);
    exit();
}

// Insert or update setting
$query = "INSERT INTO tblpos_settings (SettingKey, SettingValue, UpdatedBy) 
          VALUES ('$settingKey', '$settingValue', $userId)
          ON DUPLICATE KEY UPDATE 
          SettingValue = '$settingValue',
          UpdatedBy = $userId,
          UpdatedAt = CURRENT_TIMESTAMP";

if (mysqli_query($con, $query)) {
    echo json_encode([
        'success' => true,
        'message' => 'Setting saved successfully',
        'setting_key' => $settingKey,
        'setting_value' => $settingValue
    ]);
} else {
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save setting: ' . mysqli_error($con)
    ]);
}
?>
