<?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 setting key from query parameter
$settingKey = isset($_GET['setting_key']) ? mysqli_real_escape_string($con, $_GET['setting_key']) : '';

if (empty($settingKey)) {
    // If no specific key requested, return all settings
    $query = "SELECT SettingKey, SettingValue FROM tblpos_settings";
    $result = mysqli_query($con, $query);
    
    if ($result) {
        $settings = [];
        while ($row = mysqli_fetch_assoc($result)) {
            $settings[$row['SettingKey']] = $row['SettingValue'];
        }
        
        echo json_encode([
            'success' => true,
            'settings' => $settings
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to retrieve settings: ' . mysqli_error($con)
        ]);
    }
} else {
    // Return specific setting
    $query = "SELECT SettingValue FROM tblpos_settings WHERE SettingKey = '$settingKey'";
    $result = mysqli_query($con, $query);
    
    if ($result && mysqli_num_rows($result) > 0) {
        $row = mysqli_fetch_assoc($result);
        echo json_encode([
            'success' => true,
            'setting_key' => $settingKey,
            'setting_value' => $row['SettingValue']
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Setting not found'
        ]);
    }
}
?>
