<?php
/**
 * Enterprise HRM ERP System - Notification Helper Functions
 */

if (!defined('HRM_ACCESS')) {
    die('Direct access not allowed');
}

/**
 * Create a notification for a user
 */
function createNotification($userId, $title, $message, $type = 'info', $relatedModule = null, $relatedId = null) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            INSERT INTO notifications (user_id, title, message, type, related_module, related_id)
            VALUES (?, ?, ?, ?, ?, ?)
        ");
        $stmt->execute([$userId, $title, $message, $type, $relatedModule, $relatedId]);
        return $db->lastInsertId();
    } catch (Exception $e) {
        error_log("Error creating notification: " . $e->getMessage());
        return false;
    }
}

/**
 * Get unread notifications count for a user
 */
function getUnreadNotificationsCount($userId) {
    try {
        $db = getDB();
        $stmt = $db->prepare("SELECT COUNT(*) FROM notifications WHERE user_id = ? AND is_read = 0");
        $stmt->execute([$userId]);
        return (int)$stmt->fetchColumn();
    } catch (Exception $e) {
        error_log("Error getting notification count: " . $e->getMessage());
        return 0;
    }
}

/**
 * Get notifications for a user
 */
function getNotifications($userId, $limit = 10, $unreadOnly = false) {
    try {
        $db = getDB();
        $where = "user_id = ?";
        $params = [$userId];
        
        if ($unreadOnly) {
            $where .= " AND is_read = 0";
        }
        
        $stmt = $db->prepare("
            SELECT * FROM notifications 
            WHERE {$where}
            ORDER BY created_at DESC
            LIMIT ?
        ");
        $params[] = $limit;
        $stmt->execute($params);
        return $stmt->fetchAll();
    } catch (Exception $e) {
        error_log("Error getting notifications: " . $e->getMessage());
        return [];
    }
}

/**
 * Mark notification as read
 */
function markNotificationAsRead($notificationId, $userId) {
    try {
        $db = getDB();
        $stmt = $db->prepare("
            UPDATE notifications 
            SET is_read = 1, read_at = NOW()
            WHERE notification_id = ? AND user_id = ?
        ");
        $stmt->execute([$notificationId, $userId]);
        return true;
    } catch (Exception $e) {
        error_log("Error marking notification as read: " . $e->getMessage());
        return false;
    }
}

/**
 * Send leave application notification to HR
 */
function notifyHRForLeaveApplication($employeeId, $leaveApplicationId) {
    try {
        $db = getDB();
        
        // Get employee details
        $stmt = $db->prepare("
            SELECT e.employee_id, e.employee_code, 
                   CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name,
                   e.created_by as hr_id,
                   la.start_date, la.end_date, la.total_days,
                   lt.leave_type_name
            FROM employees e
            INNER JOIN leave_applications la ON e.employee_id = la.employee_id
            LEFT JOIN leave_types lt ON la.leave_type_id = lt.leave_type_id
            WHERE e.employee_id = ? AND la.leave_application_id = ?
        ");
        $stmt->execute([$employeeId, $leaveApplicationId]);
        $data = $stmt->fetch();
        
        if (!$data || !$data['hr_id']) {
            return false;
        }
        
        // Create notification for HR
        $title = "New Leave Application";
        $message = sprintf(
            "Employee %s (%s) has applied for %s leave from %s to %s (%s days).",
            $data['employee_name'],
            $data['employee_code'],
            $data['leave_type_name'] ?? 'leave',
            date('d-M-Y', strtotime($data['start_date'])),
            date('d-M-Y', strtotime($data['end_date'])),
            $data['total_days']
        );
        
        return createNotification(
            $data['hr_id'],
            $title,
            $message,
            'leave',
            'leave',
            $leaveApplicationId
        );
    } catch (Exception $e) {
        error_log("Error sending HR notification: " . $e->getMessage());
        return false;
    }
}

/**
 * Send leave application notification to all Admin and HR users of a branch
 * This is called when a new leave application is submitted
 */
function notifyBranchAdminHRForLeave($siteId, $employeeId, $leaveApplicationId, $leaveTypeId, $startDate, $endDate, $totalDays) {
    try {
        $db = getDB();
        
        // Get employee details
        $stmt = $db->prepare("
            SELECT e.employee_code, 
                   CONCAT(e.first_name, ' ', COALESCE(e.middle_name, ''), ' ', e.last_name) as employee_name
            FROM employees e
            WHERE e.employee_id = ?
        ");
        $stmt->execute([$employeeId]);
        $employee = $stmt->fetch();
        
        if (!$employee) {
            return false;
        }
        
        // Get leave type name
        $stmt = $db->prepare("SELECT leave_type_name FROM leave_types WHERE leave_type_id = ?");
        $stmt->execute([$leaveTypeId]);
        $leaveType = $stmt->fetch();
        $leaveTypeName = $leaveType ? $leaveType['leave_type_name'] : 'leave';
        
        // Get site name
        $stmt = $db->prepare("SELECT site_name FROM sites WHERE site_id = ?");
        $stmt->execute([$siteId]);
        $site = $stmt->fetch();
        $siteName = $site ? $site['site_name'] : 'Branch';
        
        // Get all Admin and HR Admin users who have access to this site
        $stmt = $db->prepare("
            SELECT DISTINCT u.user_id, u.full_name, r.role_code
            FROM users u
            INNER JOIN roles r ON u.role_id = r.role_id
            LEFT JOIN user_sites us ON u.user_id = us.user_id
            WHERE u.is_active = 1
            AND (
                r.role_code = 'super_admin' 
                OR (r.role_code = 'hr_admin' AND us.site_id = ?)
            )
        ");
        $stmt->execute([$siteId]);
        $adminUsers = $stmt->fetchAll();
        
        if (empty($adminUsers)) {
            error_log("No admin/HR users found for site_id: " . $siteId);
            return false;
        }
        
        // Prepare notification message
        $title = "🔔 New Leave Application - Requires Approval";
        $message = sprintf(
            "Employee %s (%s) from %s has applied for %s leave.\n\nDuration: %s to %s (%d days)\n\nPlease review and approve/reject this application.",
            $employee['employee_name'],
            $employee['employee_code'],
            $siteName,
            $leaveTypeName,
            date('d-M-Y', strtotime($startDate)),
            date('d-M-Y', strtotime($endDate)),
            $totalDays
        );
        
        $notificationCount = 0;
        
        // Send notification to each admin/HR user
        foreach ($adminUsers as $user) {
            $result = createNotification(
                $user['user_id'],
                $title,
                $message,
                'leave',
                'leave',
                $leaveApplicationId
            );
            
            if ($result) {
                $notificationCount++;
                error_log("Leave notification sent to user_id: {$user['user_id']} ({$user['full_name']}) for leave_application_id: {$leaveApplicationId}");
            }
        }
        
        return $notificationCount > 0;
        
    } catch (Exception $e) {
        error_log("Error sending branch admin/HR leave notifications: " . $e->getMessage());
        return false;
    }
}

