<?php
// Client Portal Functions

function getClientName($pdo, $clientId) {
    $stmt = $pdo->prepare("SELECT clientName FROM tblclient WHERE clientId=?");
    $stmt->execute([$clientId]);
    return $stmt->fetchColumn();
}

function getClientEmail($pdo, $clientId) {
    $stmt = $pdo->prepare("SELECT email FROM tblclient WHERE clientId=?");
    $stmt->execute([$clientId]);
    return $stmt->fetchColumn();
}

function generateNumericOTP($length = 6) {
    $otp = '';
    for ($i = 0; $i < $length; $i++) {
        $otp .= rand(0, 9);
    }
    return $otp;
}

function getUserInititals($pdo, $clientId) {
    $stmt = $pdo->prepare("SELECT clientName FROM tblclient WHERE clientId=?");
    $stmt->execute([$clientId]);
    $clientDetails = $stmt->fetch();
    return implode('', array_map(function($part) { 
        return strtoupper(substr($part, 0, 1)); 
    }, explode(' ', $clientDetails['clientName']))); 
}

function getProvince($pdo, $column, $key, $value) {
    $stmt = $pdo->prepare("SELECT $column FROM tblprovince WHERE $key=?");
    $stmt->execute([$value]);
    return $stmt->fetchColumn();
}

function hasPermission($pdo, $clientId, $module) {
    try {
        $stmt = $pdo->prepare("SELECT userRole, permissions FROM tblclient WHERE clientId = ?");
        $stmt->execute([$clientId]);
        $user = $stmt->fetch();
        
        // If columns don't exist yet, grant all permissions for backward compatibility
        if(!isset($user['userRole']) || $user['userRole'] === null) {
            return true;
        }
        
        // Admin has all permissions
        if($user['userRole'] === 'admin') {
            return true;
        }
        
        // Check specific permission
        $permissions = json_decode($user['permissions'] ?? '{}', true);
        return !empty($permissions[$module]);
    } catch(PDOException $e) {
        // If columns don't exist, grant all permissions for backward compatibility
        return true;
    }
}

function requirePermission($pdo, $clientId, $module) {
    if(!hasPermission($pdo, $clientId, $module)) {
        $dashboardPath = (strpos($_SERVER['PHP_SELF'], '/de/') !== false || 
                         strpos($_SERVER['PHP_SELF'], '/pharmacy/') !== false || 
                         strpos($_SERVER['PHP_SELF'], '/reimbursement/') !== false) 
                         ? '../dashboard.php' : 'dashboard.php';
        header("Location: $dashboardPath?error=access_denied");
        exit();
    }
}
?>
