<?php
/**
 * ============================================================================
 * extension/workers.php
 * Extension Workers Management - Hierarchical View
 * National sees all, Regional sees district/lower, etc.
 * ============================================================================
 */

require_once __DIR__ . '/includes/base.php';

// Get subordinates
$subordinates = $extensionSystem->getSubordinates();

// Group by level for better organization
$groupedWorkers = [];
foreach ($subordinates as $worker) {
    $level = $worker['assigned_level'];
    if (!isset($groupedWorkers[$level])) {
        $groupedWorkers[$level] = [];
    }
    $groupedWorkers[$level][] = $worker;
}

// Get statistics
$statsSql = "SELECT 
    COUNT(*) as total_workers,
    SUM(CASE WHEN ea.is_active = 1 THEN 1 ELSE 0 END) as active_workers,
    COUNT(DISTINCT ea.organization_name) as organizations,
    COUNT(DISTINCT CASE WHEN ea.assigned_level = 'district' THEN ea.id END) as district_level,
    COUNT(DISTINCT CASE WHEN ea.assigned_level = 'subcounty' THEN ea.id END) as subcounty_level,
    COUNT(DISTINCT CASE WHEN ea.assigned_level = 'parish' THEN ea.id END) as parish_level,
    COUNT(DISTINCT CASE WHEN ea.assigned_level = 'village' THEN ea.id END) as village_level
    FROM extension_assignments ea
    WHERE ea.id IN (" . implode(',', array_map(function($w) { return $w['id']; }, $subordinates)) . ")";

if (!empty($subordinates)) {
    $statsStmt = $db->prepare($statsSql);
    $statsStmt->execute();
    $stats = $statsStmt->fetch(PDO::FETCH_ASSOC);
} else {
    $stats = [
        'total_workers' => 0,
        'active_workers' => 0,
        'organizations' => 0,
        'district_level' => 0,
        'subcounty_level' => 0,
        'parish_level' => 0,
        'village_level' => 0
    ];
}

$pageTitle = 'Extension Workers - AIMS Extension';
$breadcrumbs = [
    ['title' => 'Extension Workers', 'url' => '']
];

renderExtensionHeader($pageTitle, $breadcrumbs);
?>

<style>
.worker-card {
    transition: all 0.3s ease;
    border-left: 4px solid var(--level-color);
}

.worker-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.level-badge {
    padding: 6px 14px;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 700;
    text-transform: uppercase;
}

.org-badge {
    background: #f3f4f6;
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 0.75rem;
}
</style>

<div class="container-fluid py-4">
    <!-- Header -->
    <div class="row mb-4">
        <div class="col-12">
            <div class="card border-0 shadow-sm" style="background: linear-gradient(135deg, #059669 0%, #10b981 100%);">
                <div class="card-body text-white p-4">
                    <div class="row align-items-center">
                        <div class="col-md-8">
                            <h3 class="mb-2 fw-bold">
                                <i class="bi bi-diagram-3 me-2"></i>Your Extension Team
                            </h3>
                            <p class="mb-0 opacity-90">
                                Managing extension workers at <?php echo ucfirst($userLevel); ?> level
                                <?php if ($coverageArea !== 'Not Assigned'): ?>
                                    - <i class="bi bi-geo-alt me-1"></i><?php echo $coverageArea; ?>
                                <?php endif; ?>
                            </p>
                        </div>
                        <div class="col-md-4 text-md-end mt-3 mt-md-0">
                            <?php if ($extensionSystem->hasPermission('assign_regional') || 
                                      $extensionSystem->hasPermission('assign_district') ||
                                      $extensionSystem->hasPermission('assign_subcounty') ||
                                      $extensionSystem->hasPermission('assign_parish')): ?>
                            <a href="<?php echo APP_URL; ?>/extension/assignments.php" class="btn btn-light btn-lg">
                                <i class="bi bi-person-plus"></i> Assign Worker
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Statistics -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Total Workers</p>
                            <h3 class="mb-0 fw-bold"><?php echo $stats['total_workers']; ?></h3>
                        </div>
                        <div class="stat-icon bg-primary bg-opacity-10 text-primary">
                            <i class="bi bi-people"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Active Workers</p>
                            <h3 class="mb-0 fw-bold text-success"><?php echo $stats['active_workers']; ?></h3>
                        </div>
                        <div class="stat-icon bg-success bg-opacity-10 text-success">
                            <i class="bi bi-check-circle"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">Organizations</p>
                            <h3 class="mb-0 fw-bold text-info"><?php echo $stats['organizations']; ?></h3>
                        </div>
                        <div class="stat-icon bg-info bg-opacity-10 text-info">
                            <i class="bi bi-building"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card stat-card border-0 shadow-sm">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <p class="text-muted mb-1 small">District Level</p>
                            <h3 class="mb-0 fw-bold text-warning"><?php echo $stats['district_level']; ?></h3>
                        </div>
                        <div class="stat-icon bg-warning bg-opacity-10 text-warning">
                            <i class="bi bi-geo-alt"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Workers by Level -->
    <?php if (empty($subordinates)): ?>
    <div class="card border-0 shadow-sm">
        <div class="card-body text-center py-5">
            <i class="bi bi-people" style="font-size: 4rem; color: #d1d5db;"></i>
            <h5 class="mt-3 text-muted">No extension workers found</h5>
            <p class="text-muted">You don't have any workers under your supervision yet</p>
            <?php if ($extensionSystem->hasPermission('assign_regional') || 
                      $extensionSystem->hasPermission('assign_district')): ?>
            <a href="<?php echo APP_URL; ?>/extension/assign-worker.php" class="btn btn-primary mt-2">
                <i class="bi bi-person-plus"></i> Assign First Worker
            </a>
            <?php endif; ?>
        </div>
    </div>
    <?php else: ?>
        <?php
        $levelOrder = ['regional', 'district', 'subcounty', 'parish', 'village'];
        $levelColors = [
            'regional' => '#ef4444',
            'district' => '#f59e0b',
            'subcounty' => '#10b981',
            'parish' => '#06b6d4',
            'village' => '#84cc16'
        ];
        $levelIcons = [
            'regional' => 'globe',
            'district' => 'building',
            'subcounty' => 'geo',
            'parish' => 'house',
            'village' => 'tree'
        ];
        
        foreach ($levelOrder as $level):
            if (!isset($groupedWorkers[$level])) continue;
            $workers = $groupedWorkers[$level];
        ?>
        
        <div class="mb-4">
            <div class="d-flex align-items-center mb-3">
                <div class="level-badge" style="background: <?php echo $levelColors[$level]; ?>; color: white;">
                    <i class="bi bi-<?php echo $levelIcons[$level]; ?> me-1"></i>
                    <?php echo ucfirst($level); ?> Level (<?php echo count($workers); ?>)
                </div>
            </div>

            <div class="row">
                <?php foreach ($workers as $worker): ?>
                <div class="col-lg-4 col-md-6 mb-3">
                    <div class="card worker-card border-0 shadow-sm h-100" style="--level-color: <?php echo $levelColors[$level]; ?>">
                        <div class="card-body">
                            <!-- Header -->
                            <div class="d-flex align-items-start mb-3">
                                <div class="flex-shrink-0 me-3">
                                    <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($worker['full_name']); ?>&background=059669&color=fff&size=64" 
                                         class="rounded-circle" width="64" height="64">
                                </div>
                                <div class="flex-grow-1">
                                    <h6 class="mb-1 fw-bold"><?php echo e($worker['full_name']); ?></h6>
                                    <p class="text-muted small mb-1">
                                        <i class="bi bi-briefcase me-1"></i><?php echo e($worker['role_name']); ?>
                                    </p>
                                    <?php if ($worker['organization_name']): ?>
                                    <span class="org-badge">
                                        <i class="bi bi-building me-1"></i><?php echo e($worker['organization_name']); ?>
                                    </span>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Contact -->
                            <div class="mb-3 pb-3 border-bottom">
                                <p class="mb-1 small">
                                    <i class="bi bi-telephone text-primary me-2"></i>
                                    <?php echo e($worker['phone_number']); ?>
                                </p>
                                <?php if ($worker['email']): ?>
                                <p class="mb-0 small">
                                    <i class="bi bi-envelope text-primary me-2"></i>
                                    <?php echo e($worker['email']); ?>
                                </p>
                                <?php endif; ?>
                            </div>

                            <!-- Coverage Area -->
                            <div class="mb-3">
                                <p class="text-muted small mb-1">Coverage Area:</p>
                                <p class="fw-semibold mb-0">
                                    <i class="bi bi-geo-alt me-1"></i>
                                    <?php 
                                    echo $worker['village_name'] ?? 
                                         $worker['parish_name'] ?? 
                                         $worker['subcounty_name'] ?? 
                                         $worker['district_name'] ?? 
                                         $worker['region_name'] ?? 'Unknown'; 
                                    ?>
                                </p>
                            </div>

                            <!-- Specializations -->
                            <?php if (!empty($worker['specializations'])): ?>
                            <div class="mb-3">
                                <p class="text-muted small mb-1">Specializations:</p>
                                <div class="d-flex flex-wrap gap-1">
                                    <?php 
                                    $specs = explode(', ', $worker['specializations']);
                                    foreach (array_slice($specs, 0, 3) as $spec): 
                                    ?>
                                    <span class="badge bg-light text-dark"><?php echo e($spec); ?></span>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>

                            <!-- Actions -->
                            <div class="d-flex gap-2 pt-3 border-top">
                                <button class="btn btn-sm btn-outline-primary flex-fill" 
                                        onclick="viewWorker(<?php echo $worker['id']; ?>)">
                                    <i class="bi bi-eye"></i> View
                                </button>
                                <a href="tel:<?php echo $worker['phone_number']; ?>" 
                                   class="btn btn-sm btn-outline-success">
                                    <i class="bi bi-telephone"></i>
                                </a>
                                <?php if ($extensionSystem->hasPermission('manage_all')): ?>
                                <button class="btn btn-sm btn-outline-secondary" 
                                        onclick="editWorker(<?php echo $worker['id']; ?>)">
                                    <i class="bi bi-pencil"></i>
                                </button>
                                <?php endif; ?>
                            </div>
                        </div>

                        <div class="card-footer bg-light">
                            <small class="text-muted">
                                <i class="bi bi-calendar me-1"></i>
                                Started <?php echo formatDate($worker['start_date']); ?>
                            </small>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- View Worker Modal -->
<div class="modal fade" id="viewWorkerModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Worker Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="workerDetails">
                <!-- Loaded via AJAX -->
            </div>
        </div>
    </div>
</div>

<script>
function viewWorker(workerId) {
    showLoading();
    $.get('<?php echo APP_URL; ?>/api/extension.php', {
        action: 'get_worker_details',
        worker_id: workerId
    }, function(response) {
        hideLoading();
        if (response.success) {
            $('#workerDetails').html(response.html);
            new bootstrap.Modal('#viewWorkerModal').show();
        } else {
            showToast(response.message, 'error');
        }
    });
}

function editWorker(workerId) {
    window.location.href = '<?php echo APP_URL; ?>/extension/assignments.php?id=' + workerId;
}
</script>

<?php renderExtensionFooter(); ?>