<?php
// Check if service is enabled for current user
// Priority: user-specific setting > global setting > default (on)
function checkServiceEnabled($svcKey) {
    global $user;
    if (empty($user['id'])) return; // not logged in, skip
    $db = getDB();

    // 1. Check user-specific override
    try {
        $s = $db->prepare("SELECT is_enabled FROM user_service_access WHERE user_id=? AND service=?");
        $s->execute([$user['id'], $svcKey]);
        $row = $s->fetch();
        if ($row !== false) {
            if (!$row['is_enabled']) {
                header('Location: '.SITE_URL.'/dashboard.php?svc_off=1');
                exit;
            }
            return; // explicitly enabled
        }
    } catch(Exception $e) {}

    // 2. Fall back to global setting
    $val = getSetting('svc_'.$svcKey);
    if ($val !== null && $val !== '' && $val !== '1') {
        header('Location: '.SITE_URL.'/dashboard.php?svc_off=1');
        exit;
    }
}

// Get user's enabled services (for dashboard display)
function getUserServices($userId) {
    $db = getDB();
    $svcs = ['topup','drive','international','cards','manual_drive','mbanking','deposit','bill_pay'];
    $result = [];
    try {
        $rows = $db->prepare("SELECT service, is_enabled FROM user_service_access WHERE user_id=?");
        $rows->execute([$userId]);
        $userOverrides = [];
        foreach($rows->fetchAll() as $r) $userOverrides[$r['service']] = $r['is_enabled'];

        foreach($svcs as $s) {
            if(isset($userOverrides[$s])) {
                $result[$s] = (bool)$userOverrides[$s];
            } else {
                // Global setting
                $val = getSetting('svc_'.$s);
                $result[$s] = ($val === null || $val === '' || $val === '1');
            }
        }
    } catch(Exception $e) {
        foreach($svcs as $s) $result[$s] = true;
    }
    return $result;
}
