<?php
/**
 * Notifications System
 * GHAMECC Choir Management Platform
 * 
 * This file contains functions for generating and displaying notifications
 * related to reports, approvals, and other system events.
 */

// Include database connection
require_once __DIR__ . '/../config/database.php';

// Include notifications library
require_once __DIR__ . '/notifications-library.php';

/**
 * Check if a table exists in the database
 * 
 * @param string $tableName Name of the table to check
 * @return bool True if table exists, false otherwise
 */
function tableExists($tableName) {
    global $conn;
    $result = $conn->query("SHOW TABLES LIKE '$tableName'");
    return ($result && $result->num_rows > 0);
}

/**
 * Get pending reports count for the current user based on their role and organizational level
 * 
 * @return int Number of pending reports
 */
function getPendingReportsCount() {
    if (!isset($_SESSION['user_id'])) {
        return 0;
    }
    
    // Check if required tables exist
    if (!tableExists('users') || !tableExists('reports')) {
        return 0;
    }
    
    $userId = $_SESSION['user_id'];
    $count = 0;
    
    // Get user's role and organizational associations
    $userInfo = fetchRow("SELECT * FROM users WHERE id = $userId");
    if (!$userInfo) {
        return 0;
    }
    
    // Check if user is associated with a society
    if (tableExists('society_roles')) {
        $societyRole = fetchRow("SELECT * FROM society_roles WHERE user_id = $userId");
        if ($societyRole) {
            $societyId = $societyRole['society_id'];
            // Count reports targeted to this society
            $societyCount = fetchRow("SELECT COUNT(*) as count FROM reports 
                                    WHERE target_type = 'society' 
                                    AND target_id = $societyId 
                                    AND status = 'pending'");
            if ($societyCount && isset($societyCount['count'])) {
                $count += $societyCount['count'];
            }
        }
    }
    
    // Check if user is associated with a circuit
    if (tableExists('circuit_roles')) {
        $circuitRole = fetchRow("SELECT * FROM circuit_roles WHERE user_id = $userId");
        if ($circuitRole) {
            $circuitId = $circuitRole['circuit_id'];
            // Count reports targeted to this circuit
            $circuitCount = fetchRow("SELECT COUNT(*) as count FROM reports 
                                    WHERE target_type = 'circuit' 
                                    AND target_id = $circuitId 
                                    AND status = 'pending'");
            if ($circuitCount && isset($circuitCount['count'])) {
                $count += $circuitCount['count'];
            }
        }
    }
    
    // Check if user is associated with a diocese
    if (tableExists('diocese_roles')) {
        $dioceseRole = fetchRow("SELECT * FROM diocese_roles WHERE user_id = $userId");
        if ($dioceseRole) {
            $dioceseId = $dioceseRole['diocese_id'];
            // Count reports targeted to this diocese
            $dioceseCount = fetchRow("SELECT COUNT(*) as count FROM reports 
                                    WHERE target_type = 'diocese' 
                                    AND target_id = $dioceseId 
                                    AND status = 'pending'");
            if ($dioceseCount && isset($dioceseCount['count'])) {
                $count += $dioceseCount['count'];
            }
        }
    }
    
    // Check if user is an admin and if hasRole function exists
    if (function_exists('hasRole') && hasRole(['admin'])) {
        // Count reports targeted to connexional level
        $connexionalCount = fetchRow("SELECT COUNT(*) as count FROM reports 
                                    WHERE target_type = 'connexional' 
                                    AND status = 'pending'");
        if ($connexionalCount && isset($connexionalCount['count'])) {
            $count += $connexionalCount['count'];
        }
    }
    
    return $count;
}

/**
 * Get recent report responses for the current user
 * 
 * @param int $limit Maximum number of notifications to return
 * @return array Array of recent report responses
 */
function getRecentReportResponses($limit = 5) {
    if (!isset($_SESSION['user_id']) || !tableExists('reports') || !tableExists('users')) {
        return [];
    }
    if (!tableExists('report_responses')) {
        return [];
    }
    
    // Check if report_responses has the necessary columns
    $hasRequiredColumns = false;
    $columns = [];
    try {
        global $conn;
        $columnsResult = $conn->query("SHOW COLUMNS FROM report_responses");
        if ($columnsResult) {
            while ($row = $columnsResult->fetch_assoc()) {
                $columns[] = $row['Field'];
            }
        }
    } catch (Exception $e) {
        error_log("Error checking report_responses columns: " . $e->getMessage());
        return [];
    }
    
    // If we don't have the minimal required columns, return empty array
    if (!in_array('report_id', $columns)) {
        return [];
    }
    
    $userId = $_SESSION['user_id'];
    global $conn;
    
    // Determine which column to use for report subject
    $columnToUse = 'report_type';
    $titleCheck = $conn->query("SHOW COLUMNS FROM reports LIKE 'title'");
    if ($titleCheck && $titleCheck->num_rows > 0) {
        $columnToUse = 'title';
    }
    $subjectCheck = $conn->query("SHOW COLUMNS FROM reports LIKE 'subject'");
    if ($subjectCheck && $subjectCheck->num_rows > 0) {
        $columnToUse = 'subject';
    }
    
    // Build query based on available columns
    $query = "SELECT rr.id, r.$columnToUse as report_subject, r.id as report_id";
    
    // Add optional columns if they exist
    if (in_array('created_at', $columns)) {
        $query .= ", rr.created_at";
    } else {
        $query .= ", r.updated_at as created_at"; // Fallback to report's updated_at
    }
    
    // Add user information if user_id column exists
    if (in_array('user_id', $columns)) {
        $query .= ", u.full_name as responder_name, u.profile_image as responder_image";
    } else {
        $query .= ", 'System' as responder_name, NULL as responder_image"; // Default values
    }
    
    $query .= " FROM report_responses rr
              JOIN reports r ON rr.report_id = r.id";
    
    // Only join users table if user_id column exists
    if (in_array('user_id', $columns)) {
        $query .= " JOIN users u ON rr.user_id = u.id";
    }
    
    $query .= " WHERE r.user_id = $userId
              ORDER BY " . (in_array('created_at', $columns) ? "rr.created_at" : "r.updated_at") . " DESC
              LIMIT $limit";
    
    return fetchRows($query);
}

/**
 * Get reports with status updates for the current user
 * 
 * @param int $limit Maximum number of notifications to return
 * @return array Array of reports with recent status changes
 */
function getReportStatusUpdates($limit = 5) {
    if (!isset($_SESSION['user_id']) || !tableExists('reports')) {
        return [];
    }
    
    $userId = $_SESSION['user_id'];
    
    // Check if required tables exist for the CASE statement
    $hasCircuits = tableExists('circuits');
    $hasDioceses = tableExists('dioceses');
    
    // Build the query based on available tables
    $query = "SELECT r.*, 
              CASE 
                  WHEN r.target_type = 'circuit' " . ($hasCircuits ? "THEN (SELECT name FROM circuits WHERE id = r.target_id)" : "THEN 'Circuit'") . "
                  WHEN r.target_type = 'diocese' " . ($hasDioceses ? "THEN (SELECT name FROM dioceses WHERE id = r.target_id)" : "THEN 'Diocese'") . "
                  WHEN r.target_type = 'connexional' THEN 'Connexional Office'
                  ELSE 'Unknown'
              END as target_name
              FROM reports r
              WHERE r.user_id = $userId
              AND r.status IN ('approved', 'rejected', 'completed')
              ORDER BY r.updated_at DESC
              LIMIT $limit";
    
    return fetchRows($query);
}

/**
 * Display notification badge for pending reports
 * 
 * @return string HTML for the notification badge
 */
function displayReportNotificationBadge() {
    $count = 0;
    
    try {
        $count = getPendingReportsCount();
    } catch (Exception $e) {
        error_log("Error getting pending reports count: " . $e->getMessage());
    }
    
    if ($count > 0) {
        return '<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">' . 
               $count . '<span class="visually-hidden">pending reports</span></span>';
    }
    
    return '';
}

/**
 * Display notification dropdown with recent updates
 * 
 * @return string HTML for the notification dropdown
 */
function displayNotificationDropdown() {
    $responses = [];
    $statusUpdates = [];
    
    try {
        $responses = getRecentReportResponses(3);
        $statusUpdates = getReportStatusUpdates(3);
    } catch (Exception $e) {
        error_log("Error getting notifications: " . $e->getMessage());
    }
    
    $totalCount = count($responses) + count($statusUpdates);
    $basePath = isset($GLOBALS['basePath']) ? $GLOBALS['basePath'] : '';
    
    $html = '<div class="dropdown">';
    $html .= '<a class="nav-link dropdown-toggle position-relative" href="#" id="notificationsDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">';
    $html .= '<i class="fas fa-bell"></i>';
    
    if ($totalCount > 0) {
        $html .= '<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger">' . 
                $totalCount . '<span class="visually-hidden">notifications</span></span>';
    }
    
    $html .= '</a>';
    $html .= '<ul class="dropdown-menu dropdown-menu-end notification-dropdown" aria-labelledby="notificationsDropdown" style="width: 320px; max-height: 400px; overflow-y: auto;">';
    
    if ($totalCount === 0) {
        $html .= '<li><div class="dropdown-item text-center text-muted">No new notifications</div></li>';
    } else {
        $html .= '<li><h6 class="dropdown-header">Notifications</h6></li>';
        
        // Add status updates
        foreach ($statusUpdates as $update) {
            $html .= '<li>';
            $html .= '<a class="dropdown-item notification-item" href="' . $basePath . '/reports/sent.php">';
            
            if ($update['status'] === 'approved') {
                $html .= '<div class="notification-icon bg-success"><i class="fas fa-check-circle"></i></div>';
                $html .= '<div class="notification-content">';
                $html .= '<div class="notification-title">Report Approved</div>';
                $html .= '<div class="notification-text">Your report to ' . htmlspecialchars($update['target_name']) . ' has been approved</div>';
            } elseif ($update['status'] === 'rejected') {
                $html .= '<div class="notification-icon bg-danger"><i class="fas fa-times-circle"></i></div>';
                $html .= '<div class="notification-content">';
                $html .= '<div class="notification-title">Report Rejected</div>';
                $html .= '<div class="notification-text">Your report to ' . htmlspecialchars($update['target_name']) . ' has been rejected</div>';
            } elseif ($update['status'] === 'completed') {
                $html .= '<div class="notification-icon bg-info"><i class="fas fa-check-double"></i></div>';
                $html .= '<div class="notification-content">';
                $html .= '<div class="notification-title">Report Completed</div>';
                $html .= '<div class="notification-text">Your report to ' . htmlspecialchars($update['target_name']) . ' has been completed</div>';
            }
            
            $html .= '<div class="notification-time">' . timeAgo($update['updated_at']) . '</div>';
            $html .= '</div>';
            $html .= '</a>';
            $html .= '</li>';
        }
        
        // Add responses
        foreach ($responses as $response) {
            $html .= '<li>';
            $html .= '<a class="dropdown-item notification-item" href="' . $basePath . '/reports/sent.php">';
            $html .= '<div class="notification-icon bg-primary">';
            
            if (!empty($response['responder_image'])) {
                $html .= '<img src="' . $basePath . '/uploads/profile/' . $response['responder_image'] . '" alt="Profile" class="rounded-circle" width="32" height="32">';
            } else {
                $html .= '<div class="avatar-circle-sm">' . getInitials($response['responder_name']) . '</div>';
            }
            
            $html .= '</div>';
            $html .= '<div class="notification-content">';
            $html .= '<div class="notification-title">New Response</div>';
            $html .= '<div class="notification-text">' . htmlspecialchars($response['responder_name']) . ' responded to your report</div>';
            $html .= '<div class="notification-time">' . timeAgo($response['created_at']) . '</div>';
            $html .= '</div>';
            $html .= '</a>';
            $html .= '</li>';
        }
        
        $html .= '<li><hr class="dropdown-divider"></li>';
        $html .= '<li><a class="dropdown-item text-center" href="' . $basePath . '/reports/sent.php">View All Reports</a></li>';
    }
    
    $html .= '</ul>';
    $html .= '</div>';
    
    return $html;
}

/**
 * Helper function to get time ago string
 * 
 * @param string $datetime MySQL datetime string
 * @return string Time ago string (e.g., "2 hours ago")
 */
function timeAgo($datetime) {
    $time = strtotime($datetime);
    $now = time();
    $diff = $now - $time;
    
    if ($diff < 60) {
        return "Just now";
    } elseif ($diff < 3600) {
        $mins = floor($diff / 60);
        return $mins . " min" . ($mins > 1 ? "s" : "") . " ago";
    } elseif ($diff < 86400) {
        $hours = floor($diff / 3600);
        return $hours . " hour" . ($hours > 1 ? "s" : "") . " ago";
    } elseif ($diff < 604800) {
        $days = floor($diff / 86400);
        return $days . " day" . ($days > 1 ? "s" : "") . " ago";
    } else {
        return date("M j, Y", $time);
    }
}

/**
 * Helper function to get initials from a name
 * 
 * @param string $name Full name
 * @return string Initials (up to 2 characters)
 */
function getInitials($name) {
    $words = explode(' ', $name);
    $initials = '';
    
    foreach ($words as $word) {
        if (!empty($word[0])) {
            $initials .= strtoupper($word[0]);
            if (strlen($initials) >= 2) {
                break;
            }
        }
    }
    
    return $initials;
}
?>
