<?php
/**
 * Pending Reports Dashboard Widget
 * GHAMECC Choir Management Platform
 * 
 * This widget displays pending reports that require attention from the current user.
 */

// Include database connection if not already included
if (!function_exists('fetchRows')) {
    require_once __DIR__ . '/../../config/database.php';
}

/**
 * Get pending reports for the current user based on their role and organizational level
 * 
 * @param int $limit Maximum number of reports to return
 * @return array Array of pending reports
 */
function getPendingReportsForWidget($limit = 5) {
    if (!isset($_SESSION['user_id'])) {
        return [];
    }
    
    $userId = $_SESSION['user_id'];
    $reports = [];
    
    // Get user data including entity IDs
    $userData = fetchRow("SELECT society_id, circuit_id, diocese_id FROM users WHERE id = $userId");
    
    // Check if user is associated with a society
    if ($userData && !empty($userData['society_id'])) {
        $societyId = $userData['society_id'];
        // Get reports targeted to this society
        $societyReports = fetchRows("SELECT r.*, 
                                    u.full_name as submitter_name,
                                    'society' as entity_type,
                                    (SELECT name FROM societies WHERE id = $societyId) as entity_name
                                    FROM reports r
                                    JOIN users u ON r.user_id = u.id
                                    WHERE r.target_type = 'society' 
                                    AND r.target_id = $societyId 
                                    AND r.status = 'pending'
                                    ORDER BY r.created_at DESC
                                    LIMIT $limit");
        $reports = array_merge($reports, $societyReports);
    }
    
    // Check if user is associated with a circuit
    if ($userData && !empty($userData['circuit_id'])) {
        $circuitId = $userData['circuit_id'];
        // Get reports targeted to this circuit
        $circuitReports = fetchRows("SELECT r.*, 
                                    u.full_name as submitter_name,
                                    'circuit' as entity_type,
                                    (SELECT name FROM circuits WHERE id = $circuitId) as entity_name
                                    FROM reports r
                                    JOIN users u ON r.user_id = u.id
                                    WHERE r.target_type = 'circuit' 
                                    AND r.target_id = $circuitId 
                                    AND r.status = 'pending'
                                    ORDER BY r.created_at DESC
                                    LIMIT $limit");
        $reports = array_merge($reports, $circuitReports);
    }
    
    // Check if user is associated with a diocese
    if ($userData && !empty($userData['diocese_id'])) {
        $dioceseId = $userData['diocese_id'];
        // Get reports targeted to this diocese
        $dioceseReports = fetchRows("SELECT r.*, 
                                    u.full_name as submitter_name,
                                    'diocese' as entity_type,
                                    (SELECT name FROM dioceses WHERE id = $dioceseId) as entity_name
                                    FROM reports r
                                    JOIN users u ON r.user_id = u.id
                                    WHERE r.target_type = 'diocese' 
                                    AND r.target_id = $dioceseId 
                                    AND r.status = 'pending'
                                    ORDER BY r.created_at DESC
                                    LIMIT $limit");
        $reports = array_merge($reports, $dioceseReports);
    }
    
    // Check if user is an admin
    if (hasRole(['admin'])) {
        // Get reports targeted to connexional level
        $connexionalReports = fetchRows("SELECT r.*, 
                                        u.full_name as submitter_name,
                                        'connexional' as entity_type,
                                        'Connexional Office' as entity_name
                                        FROM reports r
                                        JOIN users u ON r.user_id = u.id
                                        WHERE r.target_type = 'connexional' 
                                        AND r.status = 'pending'
                                        ORDER BY r.created_at DESC
                                        LIMIT $limit");
        $reports = array_merge($reports, $connexionalReports);
    }
    
    // Sort reports by creation date (newest first)
    usort($reports, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    
    // Limit to the specified number
    return array_slice($reports, 0, $limit);
}

// Get pending reports
$pendingReports = getPendingReportsForWidget(5);
$pendingCount = count($pendingReports);

// Report type labels
$reportTypeLabels = [
    'monthly_activity' => 'Monthly Activity',
    'membership_update' => 'Membership Update',
    'financial_statement' => 'Financial Statement',
    'event_report' => 'Event Report',
    'quarterly_report' => 'Quarterly Report',
    'circuit_activity' => 'Circuit Activity',
    'financial_summary' => 'Financial Summary',
    'conference_planning' => 'Conference Planning',
    'annual_report' => 'Annual Report',
    'diocese_activity' => 'Diocese Activity',
    'conference_report' => 'Conference Report',
    'administrative' => 'Administrative',
    'system_update' => 'System Update',
    'policy_update' => 'Policy Update',
    'announcement' => 'Announcement',
    'special_notice' => 'Special Notice',
    'special_request' => 'Special Request'
];
?>

<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center">
        <h6 class="m-0 font-weight-bold text-primary">Pending Reports</h6>
        <?php if ($pendingCount > 0): ?>
            <span class="badge bg-danger"><?php echo $pendingCount; ?></span>
        <?php endif; ?>
    </div>
    <div class="card-body">
        <?php if ($pendingCount === 0): ?>
            <div class="text-center text-muted py-4">
                <i class="fas fa-check-circle fa-3x mb-3"></i>
                <p>No pending reports require your attention.</p>
            </div>
        <?php else: ?>
            <div class="list-group">
                <?php foreach ($pendingReports as $report): ?>
                    <a href="<?php echo $basePath; ?>/reports/received.php" class="list-group-item list-group-item-action">
                        <div class="d-flex w-100 justify-content-between">
                            <h6 class="mb-1"><?php echo htmlspecialchars($report['title']); ?></h6>
                            <small class="text-muted"><?php echo date('M d', strtotime($report['created_at'])); ?></small>
                        </div>
                        <p class="mb-1 small">
                            <span class="badge bg-info me-1"><?php echo $reportTypeLabels[$report['report_type']] ?? $report['report_type']; ?></span>
                            From: <?php echo htmlspecialchars($report['submitter_name']); ?>
                        </p>
                        <small class="text-muted">
                            To: <?php echo htmlspecialchars($report['entity_name']); ?> (<?php echo ucfirst($report['entity_type']); ?>)
                        </small>
                    </a>
                <?php endforeach; ?>
            </div>
            <div class="text-center mt-3">
                <a href="<?php echo $basePath; ?>/reports/received.php" class="btn btn-sm btn-primary">
                    View All Pending Reports
                </a>
            </div>
        <?php endif; ?>
    </div>
</div>
