<?php
/**
 * ============================================================================
 * extension/assignments.php
 * Assign Extension Worker (Hierarchical Permissions)
 * ============================================================================
 */

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

// Check permission
$canAssign = $extensionSystem->hasPermission('assign_regional') ||
             $extensionSystem->hasPermission('assign_district') ||
             $extensionSystem->hasPermission('assign_subcounty') ||
             $extensionSystem->hasPermission('assign_parish');

if (!$canAssign && !$isAdmin) {
    redirectTo('/extension/workers.php', 'You do not have permission to assign workers', 'error');
}

// Get available roles based on current level
$rolesSql = "SELECT * FROM extension_roles WHERE is_active = 1 AND role_level IN (";
$allowedLevels = [];

if ($userLevel === 'national') {
    $allowedLevels = ['regional', 'district', 'subcounty', 'parish', 'village'];
} elseif ($userLevel === 'regional') {
    $allowedLevels = ['district', 'subcounty', 'parish', 'village'];
} elseif ($userLevel === 'district') {
    $allowedLevels = ['subcounty', 'parish', 'village'];
} elseif ($userLevel === 'subcounty') {
    $allowedLevels = ['parish', 'village'];
} elseif ($userLevel === 'parish') {
    $allowedLevels = ['village'];
}

$rolesSql .= "'" . implode("','", $allowedLevels) . "') ORDER BY role_level, role_name";
$rolesStmt = $db->prepare($rolesSql);
$rolesStmt->execute();
$roles = $rolesStmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Assign Extension Worker - AIMS Extension';
$breadcrumbs = [
    ['title' => 'Extension Workers', 'url' => APP_URL . '/extension/workers.php'],
    ['title' => 'Assign Worker', 'url' => '']
];

renderExtensionHeader($pageTitle, $breadcrumbs);
?>

<div class="container-fluid py-4">
    <div class="row justify-content-center">
        <div class="col-xl-8">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-4">
                    <div class="d-flex align-items-center">
                        <a href="<?php echo APP_URL; ?>/extension/workers.php" class="btn btn-outline-secondary me-3">
                            <i class="bi bi-arrow-left"></i>
                        </a>
                        <div>
                            <h4 class="mb-1 fw-bold">
                                <i class="bi bi-person-plus text-primary me-2"></i>Assign Extension Worker
                            </h4>
                            <p class="text-muted mb-0">Create new assignment for an extension officer</p>
                        </div>
                    </div>
                </div>
            </div>

            <form id="assignWorkerForm" method="POST">
                <!-- User Selection -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-person text-primary me-2"></i>Extension Officer
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label fw-semibold">
                                Select Extension Officer <span class="text-danger">*</span>
                            </label>
                            <select name="user_id" class="form-select form-select-lg" required id="userId">
                                <option value="">-- Select extension officer --</option>
                                <?php
                                $usersSql = "SELECT id, full_name, phone_number, email 
                                            FROM users 
                                            WHERE user_type = 'extension_officer' 
                                            AND is_active = 1
                                            ORDER BY full_name";
                                $usersStmt = $db->prepare($usersSql);
                                $usersStmt->execute();
                                $users = $usersStmt->fetchAll(PDO::FETCH_ASSOC);
                                
                                foreach ($users as $user):
                                ?>
                                <option value="<?php echo $user['id']; ?>">
                                    <?php echo e($user['full_name']); ?> 
                                    (<?php echo e($user['phone_number']); ?>)
                                </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">
                                <i class="bi bi-info-circle me-1"></i>
                                Only approved extension officers are shown
                            </small>
                        </div>
                    </div>
                </div>

                <!-- Role & Organization -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-briefcase text-success me-2"></i>Role & Organization
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">
                                    Role <span class="text-danger">*</span>
                                </label>
                                <select name="role_id" class="form-select form-select-lg" required id="roleId" 
                                        onchange="updateLocationFields()">
                                    <option value="">-- Select role --</option>
                                    <?php foreach ($roles as $role): ?>
                                    <option value="<?php echo $role['id']; ?>" data-level="<?php echo $role['role_level']; ?>">
                                        <?php echo e($role['role_name']); ?> 
                                        (<?php echo ucfirst($role['role_level']); ?>)
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Organization</label>
                                <input type="text" name="organization_name" class="form-control form-control-lg" 
                                       placeholder="e.g., NAADS, MAAIF">
                                <small class="text-muted">Organization or implementing partner</small>
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">Employee ID</label>
                                <input type="text" name="employee_id" class="form-control form-control-lg" 
                                       placeholder="Optional">
                            </div>

                            <div class="col-md-6 mb-3">
                                <label class="form-label fw-semibold">
                                    Start Date <span class="text-danger">*</span>
                                </label>
                                <input type="date" name="start_date" class="form-control form-control-lg" 
                                       value="<?php echo date('Y-m-d'); ?>" required>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Location Assignment -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-geo-alt text-danger me-2"></i>Coverage Area
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <i class="bi bi-info-circle me-2"></i>
                            Select the coverage area based on the assigned level
                        </div>

                        <div class="row" id="locationFields">
                            <!-- Populated dynamically based on role level -->
                        </div>
                    </div>
                </div>

                <!-- Specializations -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-white py-3">
                        <h6 class="mb-0 fw-bold">
                            <i class="bi bi-star text-warning me-2"></i>Specializations (Optional)
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <?php
                            $specializations = [
                                'general' => 'General Agriculture',
                                'crops' => 'Crop Production',
                                'livestock' => 'Livestock',
                                'fisheries' => 'Fisheries',
                                'poultry' => 'Poultry',
                                'horticulture' => 'Horticulture',
                                'soil' => 'Soil Management',
                                'irrigation' => 'Irrigation',
                                'agribusiness' => 'Agribusiness'
                            ];
                            foreach ($specializations as $key => $label):
                            ?>
                            <div class="col-md-4 mb-2">
                                <div class="form-check">
                                    <input type="checkbox" name="specializations[]" value="<?php echo $key; ?>" 
                                           class="form-check-input" id="spec_<?php echo $key; ?>">
                                    <label class="form-check-label" for="spec_<?php echo $key; ?>">
                                        <?php echo $label; ?>
                                    </label>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <!-- Submit -->
                <div class="card border-0 shadow-sm">
                    <div class="card-body">
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary btn-lg flex-fill">
                                <i class="bi bi-check-circle me-2"></i>Create Assignment
                            </button>
                            <a href="<?php echo APP_URL; ?>/extension/workers.php" class="btn btn-outline-secondary btn-lg">
                                Cancel
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
const currentRegionId = <?php echo $extensionSystem->userAssignment['region_id'] ?? 'null'; ?>;
const currentDistrictId = <?php echo $extensionSystem->userAssignment['district_id'] ?? 'null'; ?>;
const currentSubcountyId = <?php echo $extensionSystem->userAssignment['subcounty_id'] ?? 'null'; ?>;
const currentParishId = <?php echo $extensionSystem->userAssignment['parish_id'] ?? 'null'; ?>;

function updateLocationFields() {
    const roleSelect = $('#roleId');
    const selectedOption = roleSelect.find(':selected');
    const level = selectedOption.data('level');
    
    if (!level) {
        $('#locationFields').html('');
        return;
    }
    
    let html = '';
    
    // Build location fields based on level
    if (level === 'regional') {
        html += getRegionField();
    } else if (level === 'district') {
        html += getRegionField() + getDistrictField();
    } else if (level === 'subcounty') {
        html += getRegionField() + getDistrictField() + getSubcountyField();
    } else if (level === 'parish') {
        html += getRegionField() + getDistrictField() + getSubcountyField() + getParishField();
    } else if (level === 'village') {
        html += getRegionField() + getDistrictField() + getSubcountyField() + getParishField() + getVillageField();
    }
    
    $('#locationFields').html(html);
    
    // Load initial data
    loadRegions();
}

function getRegionField() {
    return `<div class="col-md-6 mb-3">
        <label class="form-label fw-semibold">Region <span class="text-danger">*</span></label>
        <select name="region_id" class="form-select" required id="regionId" onchange="loadDistricts()">
            <option value="">-- Select region --</option>
        </select>
    </div>`;
}

function getDistrictField() {
    return `<div class="col-md-6 mb-3">
        <label class="form-label fw-semibold">District <span class="text-danger">*</span></label>
        <select name="district_id" class="form-select" required id="districtId" onchange="loadSubcounties()">
            <option value="">-- Select district --</option>
        </select>
    </div>`;
}

function getSubcountyField() {
    return `<div class="col-md-6 mb-3">
        <label class="form-label fw-semibold">Subcounty <span class="text-danger">*</span></label>
        <select name="subcounty_id" class="form-select" required id="subcountyId" onchange="loadParishes()">
            <option value="">-- Select subcounty --</option>
        </select>
    </div>`;
}

function getParishField() {
    return `<div class="col-md-6 mb-3">
        <label class="form-label fw-semibold">Parish <span class="text-danger">*</span></label>
        <select name="parish_id" class="form-select" required id="parishId" onchange="loadVillages()">
            <option value="">-- Select parish --</option>
        </select>
    </div>`;
}

function getVillageField() {
    return `<div class="col-md-6 mb-3">
        <label class="form-label fw-semibold">Village <span class="text-danger">*</span></label>
        <select name="village_id" class="form-select" required id="villageId">
            <option value="">-- Select village --</option>
        </select>
    </div>`;
}

function loadRegions() {
    $.get('<?php echo APP_URL; ?>/api/locations.php?action=get_regions', function(response) {
        if (response.success) {
            const select = $('#regionId');
            select.html('<option value="">-- Select region --</option>');
            response.data.forEach(region => {
                select.append(`<option value="${region.id}">${region.region_name}</option>`);
            });
            
            if (currentRegionId) {
                select.val(currentRegionId);
                loadDistricts();
            }
        }
    });
}

function loadDistricts() {
    const regionId = $('#regionId').val() || currentRegionId;
    if (!regionId) return;
    
    $.get(`<?php echo APP_URL; ?>/api/locations.php?action=get_districts&region_id=${regionId}`, function(response) {
        if (response.success) {
            const select = $('#districtId');
            select.html('<option value="">-- Select district --</option>');
            response.data.forEach(district => {
                select.append(`<option value="${district.id}">${district.district_name}</option>`);
            });
            
            if (currentDistrictId) {
                select.val(currentDistrictId);
                loadSubcounties();
            }
        }
    });
}

function loadSubcounties() {
    const districtId = $('#districtId').val() || currentDistrictId;
    if (!districtId) return;
    
    $.get(`<?php echo APP_URL; ?>/api/locations.php?action=get_subcounties&district_id=${districtId}`, function(response) {
        if (response.success) {
            const select = $('#subcountyId');
            select.html('<option value="">-- Select subcounty --</option>');
            response.data.forEach(subcounty => {
                select.append(`<option value="${subcounty.id}">${subcounty.subcounty_name}</option>`);
            });
            
            if (currentSubcountyId) {
                select.val(currentSubcountyId);
                loadParishes();
            }
        }
    });
}

function loadParishes() {
    const subcountyId = $('#subcountyId').val() || currentSubcountyId;
    if (!subcountyId) return;
    
    $.get(`<?php echo APP_URL; ?>/api/locations.php?action=get_parishes&subcounty_id=${subcountyId}`, function(response) {
        if (response.success) {
            const select = $('#parishId');
            select.html('<option value="">-- Select parish --</option>');
            response.data.forEach(parish => {
                select.append(`<option value="${parish.id}">${parish.parish_name}</option>`);
            });
            
            if (currentParishId) {
                select.val(currentParishId);
                loadVillages();
            }
        }
    });
}

function loadVillages() {
    const parishId = $('#parishId').val() || currentParishId;
    if (!parishId) return;
    
    $.get(`<?php echo APP_URL; ?>/api/locations.php?action=get_villages&parish_id=${parishId}`, function(response) {
        if (response.success) {
            const select = $('#villageId');
            select.html('<option value="">-- Select village --</option>');
            response.data.forEach(village => {
                select.append(`<option value="${village.id}">${village.village_name}</option>`);
            });
        }
    });
}

$('#assignWorkerForm').on('submit', function(e) {
    e.preventDefault();
    
    showLoading();
    
    $.post('<?php echo APP_URL; ?>/api/extension.php', 
        $(this).serialize() + '&action=assign_worker',
        function(response) {
            hideLoading();
            if (response.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Worker Assigned!',
                    text: response.message,
                    confirmButtonColor: '#059669'
                }).then(() => {
                    window.location.href = '<?php echo APP_URL; ?>/extension/workers.php';
                });
            } else {
                showToast(response.message, 'error');
            }
        }
    ).fail(function() {
        hideLoading();
        showToast('Failed to create assignment', 'error');
    });
});
</script>

<?php renderExtensionFooter(); ?>