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

$breadcrumbs = [['title' => 'Extension Assignments', 'url' => '']];

// Get officers
$sql = "SELECT u.id, u.full_name, u.phone_number, u.email,
            u.region_id as user_region_id, u.district_id as user_district_id,
            u.subcounty_id as user_subcounty_id, u.parish_id as user_parish_id, u.village_id as user_village_id,
            eo.organization, eo.qualification,
            ea.id as assignment_id, ea.assigned_level, ea.start_date,
            er.role_name, er.role_level
        FROM users u
        LEFT JOIN extension_officer_profiles eo ON u.id = eo.user_id
        LEFT JOIN extension_assignments ea ON u.id = ea.user_id AND ea.is_active = 1
        LEFT JOIN extension_roles er ON ea.role_id = er.id
        WHERE u.user_type = 'extension_officer' 
        AND u.approval_status = 'approved' AND u.is_active = 1
        ORDER BY u.full_name";
$stmt = $db->query($sql);
$officers = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Get roles
$sql = "SELECT * FROM extension_roles WHERE is_active = 1 ORDER BY role_level, role_name";
$stmt = $db->query($sql);
$roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
$rolesByLevel = [];
foreach ($roles as $role) {
    $rolesByLevel[$role['role_level']][] = $role;
}

$stats = [
    'total' => count($officers),
    'assigned' => count(array_filter($officers, fn($o) => $o['assignment_id'] !== null)),
    'unassigned' => count(array_filter($officers, fn($o) => $o['assignment_id'] === null))
];

renderAdminHeader('Extension Assignments', $breadcrumbs);
?>

<style>
.officer-card { border-left: 4px solid #e5e7eb; }
.officer-card.assigned { border-left-color: #059669; }
.level-badge { font-size: 0.75rem; padding: 0.35rem 0.75rem; border-radius: 20px; font-weight: 600; }
.level-national { background: #9333ea; color: white; }
.level-regional { background: #dc2626; color: white; }
.level-district { background: #ea580c; color: white; }
.level-subcounty { background: #059669; color: white; }
.level-parish { background: #0891b2; color: white; }
.level-village { background: #65a30d; color: white; }
</style>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="mb-1 fw-bold">Extension Worker Assignments</h2>
        <p class="text-muted mb-0">Manage hierarchical assignments</p>
    </div>
    <a href="<?php echo APP_URL; ?>/admin/create-extension-worker.php" class="btn btn-primary">
        <i class="bi bi-person-plus-fill me-2"></i>Create New Extension Worker
    </a>
</div>

<div class="row mb-4">
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <p class="text-muted mb-1 small">Total Officers</p>
                <h3 class="mb-0 fw-bold"><?php echo $stats['total']; ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <p class="text-muted mb-1 small">Assigned</p>
                <h3 class="mb-0 fw-bold text-success"><?php echo $stats['assigned']; ?></h3>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm">
            <div class="card-body">
                <p class="text-muted mb-1 small">Unassigned</p>
                <h3 class="mb-0 fw-bold text-warning"><?php echo $stats['unassigned']; ?></h3>
            </div>
        </div>
    </div>
</div>

<div class="card border-0 shadow-sm">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold"><i class="bi bi-list-ul me-2"></i>Extension Officers</h5>
    </div>
    <div class="card-body p-0">
        <?php if (empty($officers)): ?>
            <div class="text-center py-5">
                <i class="bi bi-inbox text-muted" style="font-size: 4rem;"></i>
                <h5 class="mt-3 text-muted">No Extension Officers Found</h5>
                <a href="<?php echo APP_URL; ?>/admin/create-extension-worker.php" class="btn btn-primary mt-3">
                    <i class="bi bi-plus-circle me-2"></i>Create First Extension Worker
                </a>
            </div>
        <?php else: ?>
            <div class="list-group list-group-flush">
                <?php foreach ($officers as $officer): ?>
                <div class="list-group-item officer-card <?php echo $officer['assignment_id'] ? 'assigned' : ''; ?>" 
                     data-officer='<?php echo htmlspecialchars(json_encode($officer), ENT_QUOTES, 'UTF-8'); ?>'>
                    <div class="row align-items-center">
                        <div class="col-md-4">
                            <h6 class="mb-1 fw-semibold"><?php echo htmlspecialchars($officer['full_name']); ?></h6>
                            <small class="text-muted"><?php echo htmlspecialchars($officer['phone_number']); ?></small>
                        </div>
                        <div class="col-md-3">
                            <small><?php echo htmlspecialchars($officer['organization'] ?? 'N/A'); ?></small>
                        </div>
                        <div class="col-md-3">
                            <?php if ($officer['assignment_id']): ?>
                                <span class="level-badge level-<?php echo $officer['role_level']; ?>">
                                    <?php echo ucfirst($officer['role_level']); ?>
                                </span>
                            <?php else: ?>
                                <span class="badge bg-warning text-dark">Not Assigned</span>
                            <?php endif; ?>
                        </div>
                        <div class="col-md-2 text-end">
                            <?php if ($officer['assignment_id']): ?>
                                <button class="btn btn-sm btn-outline-danger" 
                                        onclick='deactivateAssignment(<?php echo $officer['assignment_id']; ?>)'>
                                    Remove
                                </button>
                            <?php else: ?>
                                <button class="btn btn-sm btn-primary" onclick='openAssignmentModal(this)'>
                                    Assign
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="assignmentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Create Assignment</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="assignmentForm">
                <div class="modal-body">
                    <input type="hidden" name="user_id" id="user_id">
                    <div class="alert alert-info mb-4">
                        <h6 class="mb-1" id="officerName"></h6>
                        <small id="officerDetails"></small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Role Level *</label>
                        <select class="form-select" name="role_level" id="role_level" required>
                            <option value="">Select Level...</option>
                            <option value="national">National Coordinator</option>
                            <option value="regional">Regional Coordinator</option>
                            <option value="district">District Officer</option>
                            <option value="subcounty">Subcounty Extension Officer</option>
                            <option value="parish">Parish Extension Worker</option>
                            <option value="village">Village Extension Agent</option>
                        </select>
                    </div>

                    <div class="mb-3" id="roleSelectContainer" style="display:none;">
                        <label class="form-label fw-semibold">Specific Role *</label>
                        <select class="form-select" name="role_id" id="role_id"></select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-semibold">Organization *</label>
                        <input type="text" class="form-control" name="organization_name" id="organization_name" required>
                    </div>

                    <div id="geoContainer">
                        <h6 class="mt-4 mb-3 fw-bold">Geographic Coverage</h6>
                        <input type="hidden" name="region_id" id="region_id">
                        <input type="hidden" name="district_id" id="district_id">
                        <input type="hidden" name="subcounty_id" id="subcounty_id">
                        <input type="hidden" name="parish_id" id="parish_id">
                        <input type="hidden" name="village_id" id="village_id">
                        
                        <div class="row g-3">
                            <div class="col-md-6" id="regionCont" style="display:none;">
                                <label>Region *</label>
                                <select class="form-select" id="region_sel"></select>
                            </div>
                            <div class="col-md-6" id="districtCont" style="display:none;">
                                <label>District *</label>
                                <select class="form-select" id="district_sel" disabled></select>
                            </div>
                            <div class="col-md-6" id="subcountyCont" style="display:none;">
                                <label>Subcounty *</label>
                                <select class="form-select" id="subcounty_sel" disabled></select>
                            </div>
                            <div class="col-md-6" id="parishCont" style="display:none;">
                                <label>Parish *</label>
                                <select class="form-select" id="parish_sel" disabled></select>
                            </div>
                            <div class="col-md-6" id="villageCont" style="display:none;">
                                <label>Village *</label>
                                <select class="form-select" id="village_sel" disabled></select>
                            </div>
                        </div>
                    </div>

                    <div class="row g-3 mt-3">
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">Start Date *</label>
                            <input type="date" class="form-control" name="start_date" id="start_date" 
                                   value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">End Date</label>
                            <input type="date" class="form-control" name="end_date" id="end_date">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Save Assignment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
const rolesData = <?php echo json_encode($roles); ?>;
const rolesByLevel = <?php echo json_encode($rolesByLevel); ?>;
let currentOfficer = null;

document.addEventListener('DOMContentLoaded', function() {
    if (typeof jQuery === 'undefined') {
        alert('jQuery not loaded! Please refresh.');
        return;
    }
    
    const $ = jQuery;
    
    window.openAssignmentModal = function(btn) {
        const card = $(btn).closest('.officer-card');
        currentOfficer = card.data('officer');
        
        $('#user_id').val(currentOfficer.id);
        $('#officerName').text(currentOfficer.full_name);
        $('#officerDetails').html('<i class="bi bi-phone me-1"></i>' + currentOfficer.phone_number);
        $('#organization_name').val(currentOfficer.organization || '');
        
        new bootstrap.Modal($('#assignmentModal')).show();
    };
    
    $('#role_level').on('change', function() {
        const level = $(this).val();
        $('#roleSelectContainer, #regionCont, #districtCont, #subcountyCont, #parishCont, #villageCont').hide();
        $('#role_id').removeAttr('required');
        
        if (!level) return;
        
        const $roleSelect = $('#role_id');
        $roleSelect.empty().append('<option value="">Select Role...</option>');
        
        if (rolesByLevel[level]) {
            rolesByLevel[level].forEach(role => {
                $roleSelect.append('<option value="' + role.id + '">' + role.role_name + '</option>');
            });
            $('#roleSelectContainer').show();
            $('#role_id').attr('required', 'required');
        }
        
        if (level === 'regional') {
            $('#regionCont').show();
            loadRegions();
        } else if (level === 'district') {
            $('#regionCont, #districtCont').show();
            loadRegions();
        } else if (level === 'subcounty') {
            $('#regionCont, #districtCont, #subcountyCont').show();
            loadRegions();
        } else if (level === 'parish') {
            $('#regionCont, #districtCont, #subcountyCont, #parishCont').show();
            loadRegions();
        } else if (level === 'village') {
            $('#regionCont, #districtCont, #subcountyCont, #parishCont, #villageCont').show();
            loadRegions();
        }
    });
    
    function loadRegions() {
        $.get(APP_URL + '/api/locations.php?action=get_regions', function(r) {
            if (r.success) {
                $('#region_sel').empty().append('<option value="">Select Region...</option>');
                r.data.forEach(reg => {
                    $('#region_sel').append('<option value="' + reg.id + '">' + reg.region_name + '</option>');
                });
            }
        });
    }
    
    $('#region_sel').on('change', function() {
        const rid = $(this).val();
        $('#region_id').val(rid);
        $('#district_sel').prop('disabled', !rid).html('<option value="">Select District...</option>');
        
        if (rid) {
            $.get(APP_URL + '/api/locations.php?action=get_districts&region_id=' + rid, function(r) {
                if (r.success) {
                    r.data.forEach(d => {
                        $('#district_sel').append('<option value="' + d.id + '">' + d.district_name + '</option>');
                    });
                }
            });
        }
    });
    
    $('#district_sel').on('change', function() {
        const did = $(this).val();
        $('#district_id').val(did);
        $('#subcounty_sel').prop('disabled', !did).html('<option value="">Select Subcounty...</option>');
        
        if (did) {
            $.get(APP_URL + '/api/locations.php?action=get_subcounties&district_id=' + did, function(r) {
                if (r.success) {
                    r.data.forEach(s => {
                        $('#subcounty_sel').append('<option value="' + s.id + '">' + s.subcounty_name + '</option>');
                    });
                }
            });
        }
    });
    
    $('#subcounty_sel').on('change', function() {
        const sid = $(this).val();
        $('#subcounty_id').val(sid);
        $('#parish_sel').prop('disabled', !sid).html('<option value="">Select Parish...</option>');
        
        if (sid) {
            $.get(APP_URL + '/api/locations.php?action=get_parishes&subcounty_id=' + sid, function(r) {
                if (r.success) {
                    r.data.forEach(p => {
                        $('#parish_sel').append('<option value="' + p.id + '">' + p.parish_name + '</option>');
                    });
                }
            });
        }
    });
    
    $('#parish_sel').on('change', function() {
        const pid = $(this).val();
        $('#parish_id').val(pid);
        $('#village_sel').prop('disabled', !pid).html('<option value="">Select Village...</option>');
        
        if (pid) {
            $.get(APP_URL + '/api/locations.php?action=get_villages&parish_id=' + pid, function(r) {
                if (r.success) {
                    r.data.forEach(v => {
                        $('#village_sel').append('<option value="' + v.id + '">' + v.village_name + '</option>');
                    });
                }
            });
        }
    });
    
    $('#village_sel').on('change', function() {
        $('#village_id').val($(this).val());
    });
    
    $('#assignmentForm').on('submit', function(e) {
        e.preventDefault();
        
        showLoading();
        
        $.post(APP_URL + '/api/extension-management.php', $(this).serialize() + '&action=create_assignment', function(r) {
            hideLoading();
            if (r.success) {
                showToast(r.message, 'success');
                bootstrap.Modal.getInstance($('#assignmentModal')[0]).hide();
                setTimeout(() => location.reload(), 1000);
            } else {
                showToast(r.message || 'Failed', 'error');
            }
        }, 'json').fail(function(xhr) {
            hideLoading();
            console.error('Error:', xhr.responseText);
            showToast('Connection error', 'error');
        });
    });
    
    window.deactivateAssignment = function(id) {
        Swal.fire({
            title: 'Remove Assignment?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc2626',
            confirmButtonText: 'Yes, remove'
        }).then((result) => {
            if (result.isConfirmed) {
                showLoading();
                $.post(APP_URL + '/api/extension-management.php', {
                    action: 'deactivate_assignment',
                    assignment_id: id
                }, function(r) {
                    hideLoading();
                    if (r.success) {
                        showToast(r.message, 'success');
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        showToast(r.message, 'error');
                    }
                }, 'json');
            }
        });
    };
});
</script>

<?php renderAdminFooter(); ?>