<?php
/**
 * TutorKita - Global Helper Functions
 * Reusable functions across the application
 */

/**
 * Adjust color brightness
 * @param string $hex Hex color code
 * @param int $steps Brightness adjustment (-255 to 255)
 * @return string Adjusted hex color
 */
function adjustBrightness($hex, $steps) {
    // Remove # if present
    $hex = str_replace('#', '', $hex);
    
    // Convert to RGB
    $r = hexdec(substr($hex, 0, 2));
    $g = hexdec(substr($hex, 2, 2));
    $b = hexdec(substr($hex, 4, 2));
    
    // Adjust
    $r = max(0, min(255, $r + $steps));
    $g = max(0, min(255, $g + $steps));
    $b = max(0, min(255, $b + $steps));
    
    // Convert back to hex
    return '#' . str_pad(dechex($r), 2, '0', STR_PAD_LEFT)
               . str_pad(dechex($g), 2, '0', STR_PAD_LEFT)
               . str_pad(dechex($b), 2, '0', STR_PAD_LEFT);
}

/**
 * Generate unique username from name
 * @param string $name Full name
 * @return string Generated username
 */
function generateUsername($name) {
    // Remove spaces and special characters
    $cleanName = preg_replace('/[^a-zA-Z0-9]/', '', strtolower($name));
    $cleanName = substr($cleanName, 0, 8);
    
    // Add random number
    $random = rand(100, 999);
    
    return $cleanName . $random;
}

/**
 * Format date in Bahasa Melayu or English
 * @param string $date Date string
 * @param string $lang Language (ms/en)
 * @return string Formatted date
 */
function formatDate($date, $lang = 'ms') {
    if (empty($date) || $date === '0000-00-00' || $date === '0000-00-00 00:00:00') {
        return '-';
    }
    
    $timestamp = strtotime($date);
    
    if ($lang === 'ms') {
        $days = ['Ahad', 'Isnin', 'Selasa', 'Rabu', 'Khamis', 'Jumaat', 'Sabtu'];
        $months = ['Januari', 'Februari', 'Mac', 'April', 'Mei', 'Jun', 
                   'Julai', 'Ogos', 'September', 'Oktober', 'November', 'Disember'];
    } else {
        $days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
        $months = ['January', 'February', 'March', 'April', 'May', 'June',
                   'July', 'August', 'September', 'October', 'November', 'December'];
    }
    
    $dayName = $days[date('w', $timestamp)];
    $day = date('d', $timestamp);
    $month = $months[date('n', $timestamp) - 1];
    $year = date('Y', $timestamp);
    
    return "$dayName, $day $month $year";
}

/**
 * Format time
 * @param string $time Time string
 * @return string Formatted time
 */
function formatTime($time) {
    if (empty($time)) return '-';
    return date('H:i', strtotime($time));
}

/**
 * Sanitize input data
 * @param mixed $data Input data
 * @return mixed Sanitized data
 */
function sanitizeInput($data) {
    if (is_array($data)) {
        return array_map('sanitizeInput', $data);
    }
    
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    
    return $data;
}

/**
 * Validate email
 * @param string $email Email address
 * @return bool Valid or not
 */
function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

/**
 * Validate phone number (Malaysian format)
 * @param string $phone Phone number
 * @return bool Valid or not
 */
function validatePhone($phone) {
    // Remove spaces and dashes
    $phone = preg_replace('/[\s\-]/', '', $phone);
    
    // Check if it's 10-12 digits
    return preg_match('/^[0-9]{10,12}$/', $phone);
}

/**
 * Generate random password
 * @param int $length Password length
 * @return string Generated password
 */
function generatePassword($length = 8) {
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    $password = '';
    
    for ($i = 0; $i < $length; $i++) {
        $password .= $chars[rand(0, strlen($chars) - 1)];
    }
    
    return $password;
}

/**
 * Get time ago string
 * @param string $datetime Datetime string
 * @param string $lang Language (ms/en)
 * @return string Time ago string
 */
function timeAgo($datetime, $lang = 'ms') {
    $timestamp = strtotime($datetime);
    $diff = time() - $timestamp;
    
    if ($lang === 'ms') {
        if ($diff < 60) return 'Baru sahaja';
        if ($diff < 3600) return floor($diff / 60) . ' minit lalu';
        if ($diff < 86400) return floor($diff / 3600) . ' jam lalu';
        if ($diff < 604800) return floor($diff / 86400) . ' hari lalu';
        if ($diff < 2592000) return floor($diff / 604800) . ' minggu lalu';
        return floor($diff / 2592000) . ' bulan lalu';
    } else {
        if ($diff < 60) return 'Just now';
        if ($diff < 3600) return floor($diff / 60) . ' minutes ago';
        if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
        if ($diff < 604800) return floor($diff / 86400) . ' days ago';
        if ($diff < 2592000) return floor($diff / 604800) . ' weeks ago';
        return floor($diff / 2592000) . ' months ago';
    }
}

/**
 * Get file size in human readable format
 * @param int $bytes File size in bytes
 * @return string Formatted file size
 */
function formatFileSize($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}

/**
 * Truncate text
 * @param string $text Text to truncate
 * @param int $length Maximum length
 * @param string $suffix Suffix to add
 * @return string Truncated text
 */
function truncateText($text, $length = 100, $suffix = '...') {
    if (strlen($text) <= $length) {
        return $text;
    }
    
    return substr($text, 0, $length) . $suffix;
}

/**
 * Get subject icon/emoji
 * @param string $subject Subject name
 * @return string Emoji icon
 */
function getSubjectIcon($subject) {
    $icons = [
        'Matematik' => '🔢',
        'Mathematics' => '🔢',
        'Sains' => '🔬',
        'Science' => '🔬',
        'Bahasa Melayu' => '📖',
        'Malay Language' => '📖',
        'Bahasa Inggeris' => '🗣️',
        'English Language' => '🗣️',
        'Sejarah' => '📜',
        'History' => '📜',
        'Geografi' => '🌍',
        'Geography' => '🌍',
        'Pendidikan Islam' => '☪️',
        'Islamic Education' => '☪️',
        'Pendidikan Moral' => '💡',
        'Moral Education' => '💡',
        'Fizik' => '⚛️',
        'Physics' => '⚛️',
        'Kimia' => '🧪',
        'Chemistry' => '🧪',
        'Biologi' => '🧬',
        'Biology' => '🧬',
        'Ekonomi' => '💰',
        'Economics' => '💰',
        'Perakaunan' => '📊',
        'Accounting' => '📊',
        'Perniagaan' => '💼',
        'Business' => '💼',
        'Seni' => '🎨',
        'Art' => '🎨',
        'Muzik' => '🎵',
        'Music' => '🎵',
        'Pendidikan Jasmani' => '⚽',
        'Physical Education' => '⚽',
        'Teknologi Maklumat' => '💻',
        'Information Technology' => '💻',
    ];
    
    return $icons[$subject] ?? '📚';
}

/**
 * Check if user is logged in
 * @param string $userType Expected user type (admin/teacher/student)
 * @return bool Logged in or not
 */
function isLoggedIn($userType = null) {
    if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_type'])) {
        return false;
    }
    
    if ($userType !== null && $_SESSION['user_type'] !== $userType) {
        return false;
    }
    
    return true;
}

/**
 * Redirect to login if not authenticated
 * @param string $userType Expected user type
 */
function requireAuth($userType = null) {
    if (!isLoggedIn($userType)) {
        header('Location: ../index.php');
        exit;
    }
}

/**
 * Get current user ID
 * @return int|null User ID
 */
function getCurrentUserId() {
    return $_SESSION['user_id'] ?? null;
}

/**
 * Get current user type
 * @return string|null User type
 */
function getCurrentUserType() {
    return $_SESSION['user_type'] ?? null;
}

/**
 * Create notification
 * @param PDO $pdo Database connection
 * @param int $userId User ID
 * @param string $userType User type (admin/teacher/student)
 * @param string $title Notification title
 * @param string $message Notification message
 * @param string $type Notification type (success/error/warning/info)
 * @param string $link Optional action link
 * @return bool Success or failure
 */
function createNotification($pdo, $userId, $userType, $title, $message, $type = 'info', $link = null) {
    try {
        $stmt = $pdo->prepare("INSERT INTO notifications (user_id, user_type, title, message, type, link) VALUES (?, ?, ?, ?, ?, ?)");
        return $stmt->execute([$userId, $userType, $title, $message, $type, $link]);
    } catch (Exception $e) {
        error_log('Notification error: ' . $e->getMessage());
        return false;
    }
}

/**
 * Log activity
 * @param PDO $pdo Database connection
 * @param string $activity Activity description
 * @param string $status Status (Aktif/Maintenance/Selesai)
 * @param string $details Additional details
 * @param int $createdBy User ID who created the log
 * @return bool Success or failure
 */
function logActivity($pdo, $activity, $status = 'Aktif', $details = null, $createdBy = null) {
    try {
        $stmt = $pdo->prepare("INSERT INTO maintenance_logs (activity, status, details, created_by) VALUES (?, ?, ?, ?)");
        return $stmt->execute([$activity, $status, $details, $createdBy]);
    } catch (Exception $e) {
        error_log('Activity log error: ' . $e->getMessage());
        return false;
    }
}

/**
 * Get system language
 * @param PDO $pdo Database connection
 * @return string Language code (ms/en)
 */
function getSystemLanguage($pdo) {
    try {
        $stmt = $pdo->prepare("SELECT language FROM admin WHERE id = 1");
        $stmt->execute();
        $result = $stmt->fetch();
        return $result['language'] ?? 'ms';
    } catch (Exception $e) {
        return 'ms';
    }
}

/**
 * Translate text based on system language
 * @param string $key Translation key
 * @param string $lang Language code
 * @return string Translated text
 */
function translate($key, $lang = 'ms') {
    $translations = [
        'ms' => [
            'success' => 'Berjaya',
            'error' => 'Ralat',
            'warning' => 'Amaran',
            'info' => 'Maklumat',
            'loading' => 'Memuatkan...',
            'no_data' => 'Tiada data',
            'save' => 'Simpan',
            'cancel' => 'Batal',
            'delete' => 'Padam',
            'edit' => 'Edit',
            'view' => 'Lihat',
            'add' => 'Tambah',
            'search' => 'Cari',
            'filter' => 'Tapis',
            'all' => 'Semua',
            'yes' => 'Ya',
            'no' => 'Tidak',
        ],
        'en' => [
            'success' => 'Success',
            'error' => 'Error',
            'warning' => 'Warning',
            'info' => 'Information',
            'loading' => 'Loading...',
            'no_data' => 'No data',
            'save' => 'Save',
            'cancel' => 'Cancel',
            'delete' => 'Delete',
            'edit' => 'Edit',
            'view' => 'View',
            'add' => 'Add',
            'search' => 'Search',
            'filter' => 'Filter',
            'all' => 'All',
            'yes' => 'Yes',
            'no' => 'No',
        ]
    ];
    
    return $translations[$lang][$key] ?? $key;
}
