<?php
require_once "config.php";

function getSetting($setting_key, $default_value = null) {
    global $conn;
    
    try {
        $stmt = $conn->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->bind_param("s", $setting_key);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            return $row['setting_value'];
        }
    } catch (Exception $e) {
        error_log("Error getting setting {$setting_key}: " . $e->getMessage());
    }
    
    return $default_value;
}

function isEmailEnabled($setting_key) {
    global $conn;
    
    try {
        $stmt = $conn->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->bind_param("s", $setting_key);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            return (bool)$row['setting_value'];
        }
    } catch (Exception $e) {
        error_log("Error checking email setting {$setting_key}: " . $e->getMessage());
    }
    
    $defaults = [
        'emails_enabled' => true,
        'email_admin_new_ride' => true,
        'email_admin_ride_modified' => true,
        'email_komitent_approved' => true,
        'email_komitent_rejected' => true,
        'email_driver_daily_reminder' => true,
    ];
    
    return isset($defaults[$setting_key]) ? $defaults[$setting_key] : true;
}

function shouldSendEmail($setting_key) {
    if (!isEmailEnabled('emails_enabled')) {
        return false;
    }
    
    return isEmailEnabled($setting_key);
}

function getItemsPerPage() {
    $value = getSetting('items_per_page', '25');
    $valid_values = ['10', '25', '50', '100'];
    return in_array($value, $valid_values) ? (int)$value : 25;
}

function isCompactView() {
    return (bool)getSetting('compact_view', '0');
}

function getDefaultRideStatus() {
    $value = getSetting('default_ride_status', 'Na čekanju');
    $valid_statuses = ['Na čekanju', 'Nerasporedjeno'];
    return in_array($value, $valid_statuses) ? $value : 'Na čekanju';
}
?>


