<?php
// دوال مساعدة للنظام

function getDashboardStats($conn) {
    $stats = [];
    
    try {
        // إجمالي المرضى
        $stmt = $conn->prepare("SELECT COUNT(*) as total FROM patients");
        $stmt->execute();
        $stats['total_patients'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // المضادات الحيوية النشطة
        $stmt = $conn->prepare("SELECT COUNT(*) as total FROM antibiotics WHERE is_active = 1");
        $stmt->execute();
        $stats['active_antibiotics'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // التقارير هذا الشهر
        $stmt = $conn->prepare("SELECT COUNT(*) as total FROM antibiotic_reports WHERE MONTH(created_at) = MONTH(CURRENT_DATE()) AND YEAR(created_at) = YEAR(CURRENT_DATE())");
        $stmt->execute();
        $stats['monthly_reports'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
        // الأحداث المعلقة
        $stmt = $conn->prepare("SELECT COUNT(*) as total FROM antibiotic_reports WHERE status = 'pending'");
        $stmt->execute();
        $stats['pending_events'] = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
        
    } catch(PDOException $e) {
        error_log("Error getting dashboard stats: " . $e->getMessage());
        $stats = [
            'total_patients' => 0,
            'active_antibiotics' => 0,
            'monthly_reports' => 0,
            'pending_events' => 0
        ];
    }
    
    return $stats;
}

function getRecentReports($conn, $limit = 10) {
    try {
        $stmt = $conn->prepare("
            SELECT 
                ar.id,
                ar.report_date,
                ar.status,
                ar.created_at,
                p.patient_name,
                p.mrn,
                u.unit_name as unit,
                COALESCE(a.antibiotic_name, ar.other_medication_name, 'غير محدد') as antibiotic
            FROM antibiotic_reports ar
            JOIN patients p ON ar.patient_id = p.id
            JOIN units u ON ar.unit_id = u.id
            LEFT JOIN antibiotics a ON ar.antibiotic_id = a.id
            ORDER BY ar.created_at DESC
            LIMIT :limit
        ");
        $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();
        
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    } catch(PDOException $e) {
        error_log("Error getting recent reports: " . $e->getMessage());
        return [];
    }
}

function getChartData($conn, $type = 'monthly') {
    try {
        switch($type) {
            case 'monthly':
                $stmt = $conn->prepare("
                    SELECT 
                        DATE_FORMAT(report_date, '%Y-%m') as month,
                        COUNT(*) as count
                    FROM antibiotic_reports 
                    WHERE report_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 12 MONTH)
                    GROUP BY DATE_FORMAT(report_date, '%Y-%m')
                    ORDER BY month
                ");
                break;
                
            case 'units':
                $stmt = $conn->prepare("
                    SELECT 
                        u.unit_name,
                        COUNT(ar.id) as count
                    FROM units u
                    LEFT JOIN antibiotic_reports ar ON u.id = ar.unit_id
                    WHERE u.is_active = 1
                    GROUP BY u.id, u.unit_name
                    ORDER BY count DESC
                ");
                break;
                
            case 'antibiotics':
                $stmt = $conn->prepare("
                    SELECT 
                        a.antibiotic_name,
                        COUNT(ar.id) as count
                    FROM antibiotics a
                    LEFT JOIN antibiotic_reports ar ON a.id = ar.antibiotic_id
                    WHERE a.is_active = 1
                    GROUP BY a.id, a.antibiotic_name
                    ORDER BY count DESC
                    LIMIT 10
                ");
                break;
        }
        
        $stmt->execute();
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
        
    } catch(PDOException $e) {
        error_log("Error getting chart data: " . $e->getMessage());
        return [];
    }
}

function sanitizeInput($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

function validateMRN($mrn) {
    // التحقق من صحة رقم الملف الطبي
    return preg_match('/^[0-9]{4,10}$/', $mrn);
}

function logActivity($conn, $user_id, $action, $table_name = null, $record_id = null, $old_values = null, $new_values = null) {
    try {
        // Verify user exists before inserting to avoid FK constraint violation
        if ($user_id) {
            $check = $conn->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
            $check->execute([$user_id]);
            if ($check->rowCount() === 0) {
                error_log("logActivity: user_id $user_id not found in users table, skipping log.");
                return;
            }
        }

        $stmt = $conn->prepare("
            INSERT INTO activity_log (user_id, action, table_name, record_id, old_values, new_values, ip_address, user_agent)
            VALUES (:user_id, :action, :table_name, :record_id, :old_values, :new_values, :ip_address, :user_agent)
        ");
        
        $stmt->execute([
            ':user_id' => $user_id,
            ':action' => $action,
            ':table_name' => $table_name,
            ':record_id' => $record_id,
            ':old_values' => $old_values ? json_encode($old_values) : null,
            ':new_values' => $new_values ? json_encode($new_values) : null,
            ':ip_address' => $_SERVER['REMOTE_ADDR'] ?? null,
            ':user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? null
        ]);
        
    } catch(PDOException $e) {
        error_log("Error logging activity: " . $e->getMessage());
    }
}

function checkPermission($required_role, $user_role) {
    $roles_hierarchy = [
        'admin' => 4,
        'doctor' => 3,
        'pharmacist' => 2,
        'nurse' => 1
    ];
    
    return $roles_hierarchy[$user_role] >= $roles_hierarchy[$required_role];
}

function formatDate($date, $format = 'Y-m-d H:i:s') {
    return date($format, strtotime($date));
}

function generateReportNumber() {
    return 'RPT-' . date('Ymd') . '-' . str_pad(rand(1, 9999), 4, '0', STR_PAD_LEFT);
}

function uploadFile($file, $allowed_types = ['pdf', 'jpg', 'jpeg', 'png', 'doc', 'docx']) {
    $upload_dir = 'uploads/';
    
    if (!file_exists($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }
    
    $file_extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    
    if (!in_array($file_extension, $allowed_types)) {
        return ['success' => false, 'message' => 'نوع الملف غير مسموح'];
    }
    
    if ($file['size'] > MAX_FILE_SIZE) {
        return ['success' => false, 'message' => 'حجم الملف كبير جداً'];
    }
    
    $new_filename = uniqid() . '.' . $file_extension;
    $upload_path = $upload_dir . $new_filename;
    
    if (move_uploaded_file($file['tmp_name'], $upload_path)) {
        return [
            'success' => true,
            'filename' => $new_filename,
            'path' => $upload_path,
            'size' => $file['size']
        ];
    } else {
        return ['success' => false, 'message' => 'فشل في رفع الملف'];
    }
}

function sendNotification($conn, $user_id, $title, $message, $type = 'info') {
    try {
        $stmt = $conn->prepare("
            INSERT INTO notifications (user_id, title, message, type, created_at)
            VALUES (:user_id, :title, :message, :type, NOW())
        ");
        
        $stmt->execute([
            ':user_id' => $user_id,
            ':title' => $title,
            ':message' => $message,
            ':type' => $type
        ]);
        
        return true;
    } catch(PDOException $e) {
        error_log("Error sending notification: " . $e->getMessage());
        return false;
    }
}

function formatFileSize($bytes) {
    if ($bytes >= 1073741824) {
        $bytes = number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        $bytes = number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        $bytes = number_format($bytes / 1024, 2) . ' KB';
    } elseif ($bytes > 1) {
        $bytes = $bytes . ' bytes';
    } elseif ($bytes == 1) {
        $bytes = $bytes . ' byte';
    } else {
        $bytes = '0 bytes';
    }

    return $bytes;
}

function formatTimeAgo($datetime) {
    $time = time() - strtotime($datetime);
    
    if ($time < 60) {
        return 'منذ ' . $time . ' ثانية';
    } elseif ($time < 3600) {
        return 'منذ ' . round($time / 60) . ' دقيقة';
    } elseif ($time < 86400) {
        return 'منذ ' . round($time / 3600) . ' ساعة';
    } elseif ($time < 2592000) {
        return 'منذ ' . round($time / 86400) . ' يوم';
    } elseif ($time < 31104000) {
        return 'منذ ' . round($time / 2592000) . ' شهر';
    } else {
        return 'منذ ' . round($time / 31104000) . ' سنة';
    }
}

function createNotification($conn, $user_id, $title, $message, $type = 'info') {
    try {
        $stmt = $conn->prepare("
            INSERT INTO notifications (user_id, title, message, type) 
            VALUES (?, ?, ?, ?)
        ");
        $stmt->execute([$user_id, $title, $message, $type]);
        return true;
    } catch (Exception $e) {
        error_log("Error creating notification: " . $e->getMessage());
        return false;
    }
}

function getUnreadNotificationsCount($conn, $user_id) {
    try {
        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = 0");
        $stmt->execute([$user_id]);
        return $stmt->fetch(PDO::FETCH_ASSOC)['count'];
    } catch (Exception $e) {
        return 0;
    }
}

function translateProblemAuthority($authority) {
    $translations = [
        'physicians' => 'الأطباء',
        'nurses' => 'الممرضات',
        'pharmacist' => 'الصيدلي',
        'other' => 'أخرى'
    ];
    
    return $translations[$authority] ?? $authority;
}

function formatArabicDate($date) {
    $months = [
        1 => 'يناير', 2 => 'فبراير', 3 => 'مارس', 4 => 'أبريل',
        5 => 'مايو', 6 => 'يونيو', 7 => 'يوليو', 8 => 'أغسطس',
        9 => 'سبتمبر', 10 => 'أكتوبر', 11 => 'نوفمبر', 12 => 'ديسمبر'
    ];
    
    $timestamp = strtotime($date);
    $day = date('d', $timestamp);
    $month = $months[(int)date('m', $timestamp)];
    $year = date('Y', $timestamp);
    
    return "$day $month $year";
}

function getHospitalInfo() {
    return [
        'name' => 'مستشفى الملك فهد',
        'name_en' => 'King Fahd Hospital',
        'logo_path' => 'assets/images/hospital_logo.svg',
        'address' => 'المملكة العربية السعودية',
        'phone' => '+966-XX-XXXXXXX',
        'email' => 'info@kfh.med.sa'
    ];
}
?>
<?php

/**
 * Check if user has permission to access a page
 * @param string $page_key The permission key to check
 * @return bool True if user has permission, false otherwise
 */
function hasPermission($page_key) {
    // Admin always has all permissions
    if (isset($_SESSION['role']) && $_SESSION['role'] === 'admin') {
        return true;
    }
    
    // Load permissions from file
    $permissions_file = __DIR__ . '/../config/permissions.json';
    
    if (!file_exists($permissions_file)) {
        // If no permissions file exists, use default permissions
        return checkDefaultPermission($page_key, $_SESSION['role'] ?? 'pharmacist');
    }
    
    $permissions = json_decode(file_get_contents($permissions_file), true);
    $user_role = $_SESSION['role'] ?? 'pharmacist';
    
    if (!isset($permissions[$user_role])) {
        return checkDefaultPermission($page_key, $user_role);
    }
    
    return in_array($page_key, $permissions[$user_role]);
}

/**
 * Check default permissions for a role
 * @param string $page_key The permission key to check
 * @param string $role The user role
 * @return bool True if user has permission by default
 */
function checkDefaultPermission($page_key, $role) {
    $default_permissions = [
        'admin' => ['dashboard', 'patients', 'antibiotics', 'reports', 'icu', 'pharmacy', 'kpi', 'users', 'search', 'activity', 'database', 'export'],
        'pharmacist' => ['dashboard', 'patients', 'antibiotics', 'reports', 'pharmacy', 'kpi', 'search', 'export'],
        'doctor' => ['dashboard', 'patients', 'reports', 'icu', 'kpi', 'search'],
        'nurse' => ['dashboard', 'patients', 'reports', 'icu', 'search']
    ];
    
    return in_array($page_key, $default_permissions[$role] ?? []);
}

/**
 * Redirect to access denied page if user doesn't have permission
 * @param string $page_key The permission key to check
 */
function requirePermission($page_key) {
    if (!hasPermission($page_key)) {
        header('Location: access_denied.php');
        exit();
    }
}

/**
 * Get user's permissions list
 * @return array List of permission keys the user has
 */
function getUserPermissions() {
    $user_role = $_SESSION['role'] ?? 'pharmacist';
    
    // Admin always has all permissions
    if ($user_role === 'admin') {
        return ['dashboard', 'patients', 'antibiotics', 'reports', 'icu', 'pharmacy', 'kpi', 'users', 'search', 'activity', 'database', 'export'];
    }
    
    $permissions_file = __DIR__ . '/../config/permissions.json';
    
    if (!file_exists($permissions_file)) {
        // Return default permissions for the role
        $default_permissions = [
            'pharmacist' => ['dashboard', 'patients', 'antibiotics', 'reports', 'pharmacy', 'kpi', 'search', 'export'],
            'doctor' => ['dashboard', 'patients', 'reports', 'icu', 'kpi', 'search'],
            'nurse' => ['dashboard', 'patients', 'reports', 'icu', 'search']
        ];
        return $default_permissions[$user_role] ?? [];
    }
    
    $permissions = json_decode(file_get_contents($permissions_file), true);
    
    return $permissions[$user_role] ?? [];
}

/**
 * Advanced Permissions System
 * Check if user has specific action permission
 * @param string $module The module name (e.g., 'patients', 'antibiotics')
 * @param string $action The action (view, add, edit, delete, export, print)
 * @return bool True if user has permission
 */
function hasActionPermission($module, $action) {
    // Admin always has all permissions
    if (isset($_SESSION['role']) && $_SESSION['role'] === 'admin') {
        return true;
    }
    
    // Load advanced permissions from file
    $permissions_file = __DIR__ . '/../config/advanced_permissions.json';
    
    if (!file_exists($permissions_file)) {
        // If no file exists, use default advanced permissions
        return checkDefaultActionPermission($module, $action, $_SESSION['role'] ?? 'pharmacist');
    }
    
    $permissions = json_decode(file_get_contents($permissions_file), true);
    $user_role = $_SESSION['role'] ?? 'pharmacist';
    
    if (!isset($permissions[$user_role][$module])) {
        return checkDefaultActionPermission($module, $action, $user_role);
    }
    
    return in_array($action, $permissions[$user_role][$module] ?? []);
}

/**
 * Check default action permissions for a role
 * @param string $module The module name
 * @param string $action The action
 * @param string $role The user role
 * @return bool True if user has permission by default
 */
function checkDefaultActionPermission($module, $action, $role) {
    $default_permissions = [
        'admin' => [
            'patients' => ['view', 'add', 'edit', 'delete', 'export', 'print'],
            'antibiotics' => ['view', 'add', 'edit', 'delete', 'export', 'print'],
            'reports' => ['view', 'add', 'edit', 'delete', 'export', 'print'],
            'icu' => ['view', 'add', 'edit', 'delete', 'export', 'print'],
            'nursery' => ['view', 'add', 'edit', 'delete', 'export', 'print'],
            'operations' => ['view', 'add', 'edit', 'delete', 'export', 'print'],
            'pharmacy' => ['view', 'add', 'edit', 'delete', 'export', 'print'],
            'monitoring' => ['view', 'add', 'edit', 'export', 'print'],
            'users' => ['view', 'add', 'edit', 'delete']
        ],
        'pharmacist' => [
            'patients' => ['view', 'add', 'edit', 'export', 'print'],
            'antibiotics' => ['view', 'add', 'edit', 'export', 'print'],
            'reports' => ['view', 'add', 'edit', 'export', 'print'],
            'pharmacy' => ['view', 'add', 'edit', 'export', 'print'],
            'monitoring' => ['view', 'add', 'edit', 'export', 'print']
        ],
        'doctor' => [
            'patients' => ['view', 'add', 'edit', 'print'],
            'reports' => ['view', 'add', 'edit', 'print'],
            'icu' => ['view', 'add', 'edit', 'print'],
            'nursery' => ['view', 'add', 'edit', 'print'],
            'operations' => ['view', 'add', 'edit', 'print'],
            'monitoring' => ['view', 'print']
        ],
        'nurse' => [
            'patients' => ['view', 'print'],
            'reports' => ['view', 'add', 'print'],
            'icu' => ['view', 'add', 'print'],
            'nursery' => ['view', 'add', 'print'],
            'monitoring' => ['view', 'print']
        ]
    ];
    
    return in_array($action, $default_permissions[$role][$module] ?? []);
}

/**
 * Get all action permissions for a module
 * @param string $module The module name
 * @return array List of allowed actions
 */
function getModulePermissions($module) {
    $user_role = $_SESSION['role'] ?? 'pharmacist';
    
    if ($user_role === 'admin') {
        return ['view', 'add', 'edit', 'delete', 'export', 'print'];
    }
    
    $permissions_file = __DIR__ . '/../config/advanced_permissions.json';
    
    if (!file_exists($permissions_file)) {
        $default_permissions = [
            'pharmacist' => [
                'patients' => ['view', 'add', 'edit', 'export', 'print'],
                'antibiotics' => ['view', 'add', 'edit', 'export', 'print']
            ],
            'doctor' => [
                'patients' => ['view', 'add', 'edit', 'print']
            ],
            'nurse' => [
                'patients' => ['view', 'print']
            ]
        ];
        return $default_permissions[$user_role][$module] ?? [];
    }
    
    $permissions = json_decode(file_get_contents($permissions_file), true);
    return $permissions[$user_role][$module] ?? [];
}

/**
 * Check if user can view module
 */
function canView($module) {
    return hasActionPermission($module, 'view');
}

/**
 * Check if user can add to module
 */
function canAdd($module) {
    return hasActionPermission($module, 'add');
}

/**
 * Check if user can edit module
 */
function canEdit($module) {
    return hasActionPermission($module, 'edit');
}

/**
 * Check if user can delete from module
 */
function canDelete($module) {
    return hasActionPermission($module, 'delete');
}

/**
 * Check if user can export from module
 */
function canExport($module) {
    return hasActionPermission($module, 'export');
}

/**
 * Check if user can print from module
 */
function canPrint($module) {
    return hasActionPermission($module, 'print');
}
?>
