<?php
/**
 * ============================================================================
 * admin/create-extension-worker.php - Create Extension Worker
 * ============================================================================
 * Admin-side creation of extension workers (pre-approved, no OTP needed)
 */

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

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

renderAdminHeader('Create Extension Worker', $breadcrumbs);
?>

<div class="row justify-content-center">
    <div class="col-lg-8">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-primary text-white py-3">
                <h5 class="mb-0">
                    <i class="bi bi-person-badge-fill me-2"></i>
                    Create New Extension Worker
                </h5>
            </div>
            <div class="card-body p-4">
                <div class="alert alert-info">
                    <i class="bi bi-info-circle me-2"></i>
                    <strong>Admin Creation:</strong> This account will be created as APPROVED and can login immediately. No OTP verification needed.
                </div>

                <form id="createExtensionWorkerForm" class="needs-validation" novalidate>
                    <!-- Basic Information -->
                    <h6 class="mb-3 fw-bold text-primary">
                        <i class="bi bi-person me-2"></i>Basic Information
                    </h6>

                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Full Name *</label>
                            <input type="text" class="form-control" name="full_name" required minlength="3">
                            <div class="invalid-feedback">Please provide full name (min 3 characters)</div>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Phone Number *</label>
                            <input type="tel" class="form-control" name="phone_number" 
                                   placeholder="0700123456" required pattern="[0-9+]{10,13}">
                            <div class="invalid-feedback">Valid format: 0700123456 or +256700123456</div>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Email (Optional)</label>
                            <input type="email" class="form-control" name="email">
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Password *</label>
                            <div class="input-group">
                                <input type="password" class="form-control" name="password" 
                                       id="password" required minlength="6">
                                <button class="btn btn-outline-secondary" type="button" 
                                        onclick="generatePassword()">
                                    <i class="bi bi-arrow-clockwise"></i> Generate
                                </button>
                            </div>
                            <div class="form-text">Min 6 characters. Click Generate for random password.</div>
                        </div>
                    </div>

                    <!-- Location -->
                    <h6 class="mb-3 fw-bold text-primary">
                        <i class="bi bi-geo-alt me-2"></i>Location
                    </h6>

                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Region *</label>
                            <select class="form-select" name="region_id" id="region_id" required>
                                <option value="">Select Region...</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">District *</label>
                            <select class="form-select" name="district_id" id="district_id" required disabled>
                                <option value="">Select District...</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Subcounty *</label>
                            <select class="form-select" name="subcounty_id" id="subcounty_id" required disabled>
                                <option value="">Select Subcounty...</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Parish *</label>
                            <select class="form-select" name="parish_id" id="parish_id" required disabled>
                                <option value="">Select Parish...</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Village *</label>
                            <select class="form-select" name="village_id" id="village_id" required disabled>
                                <option value="">Select Village...</option>
                            </select>
                        </div>
                    </div>

                    <!-- Professional Information -->
                    <h6 class="mb-3 fw-bold text-primary">
                        <i class="bi bi-briefcase me-2"></i>Professional Information
                    </h6>

                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Organization *</label>
                            <input type="text" class="form-control" name="organization" 
                                   placeholder="e.g., NAADS Luuka District" required>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Qualification *</label>
                            <select class="form-select" name="qualification" required>
                                <option value="">Select...</option>
                                <option value="certificate">Certificate</option>
                                <option value="diploma">Diploma</option>
                                <option value="degree">Degree</option>
                                <option value="masters">Masters</option>
                                <option value="phd">PhD</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Years of Experience *</label>
                            <input type="number" class="form-control" name="years_of_experience" 
                                   min="0" max="50" required>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Specialization *</label>
                            <input type="text" class="form-control" name="specialization" 
                                   placeholder="e.g., Agronomy, Animal Husbandry" required>
                        </div>
                    </div>

                    <!-- Optional: Immediate Role Assignment -->
                    <h6 class="mb-3 fw-bold text-primary">
                        <i class="bi bi-diagram-3 me-2"></i>Role Assignment (Optional)
                    </h6>

                    <div class="mb-4">
                        <div class="form-check form-switch mb-3">
                            <input class="form-check-input" type="checkbox" id="assignRoleNow">
                            <label class="form-check-label" for="assignRoleNow">
                                <strong>Assign Role & Area Now</strong>
                                <small class="d-block text-muted">Check this to assign role and geographic area during creation</small>
                            </label>
                        </div>

                        <div id="roleAssignmentSection" style="display:none;">
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">Role Level</label>
                                    <select class="form-select" name="role_level" id="role_level">
                                        <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="col-md-6" id="roleSelectContainer" style="display:none;">
                                    <label class="form-label">Specific Role</label>
                                    <select class="form-select" name="role_id" id="role_id">
                                        <option value="">Select Role...</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Submit -->
                    <div class="d-flex gap-2 justify-content-end">
                        <a href="<?php echo APP_URL; ?>/admin/extension-assignments.php" class="btn btn-secondary">
                            <i class="bi bi-x-circle me-2"></i>Cancel
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-circle me-2"></i>Create Extension Worker
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {

// Load regions on page load
loadRegions();

function loadRegions() {
    $.get(APP_URL + '/api/locations.php?action=get_regions', function(response) {
        if (response.success) {
            const $select = $('#region_id');
            $select.empty().append('<option value="">Select Region...</option>');
            response.data.forEach(region => {
                $select.append(`<option value="${region.id}">${region.region_name}</option>`);
            });
        }
    });
}

// Location cascade
$('#region_id').change(function() {
    const regionId = $(this).val();
    $('#district_id').prop('disabled', !regionId).html('<option value="">Select District...</option>');
    
    if (regionId) {
        $.get(APP_URL + '/api/locations.php', {action: 'get_districts', region_id: regionId}, function(response) {
            if (response.success) {
                response.data.forEach(d => {
                    $('#district_id').append(`<option value="${d.id}">${d.district_name}</option>`);
                });
            }
        });
    }
});

$('#district_id').change(function() {
    const districtId = $(this).val();
    $('#subcounty_id').prop('disabled', !districtId).html('<option value="">Select Subcounty...</option>');
    
    if (districtId) {
        $.get(APP_URL + '/api/locations.php', {action: 'get_subcounties', district_id: districtId}, function(response) {
            if (response.success) {
                response.data.forEach(s => {
                    $('#subcounty_id').append(`<option value="${s.id}">${s.subcounty_name}</option>`);
                });
            }
        });
    }
});

$('#subcounty_id').change(function() {
    const subcountyId = $(this).val();
    $('#parish_id').prop('disabled', !subcountyId).html('<option value="">Select Parish...</option>');
    
    if (subcountyId) {
        $.get(APP_URL + '/api/locations.php', {action: 'get_parishes', subcounty_id: subcountyId}, function(response) {
            if (response.success) {
                response.data.forEach(p => {
                    $('#parish_id').append(`<option value="${p.id}">${p.parish_name}</option>`);
                });
            }
        });
    }
});

$('#parish_id').change(function() {
    const parishId = $(this).val();
    $('#village_id').prop('disabled', !parishId).html('<option value="">Select Village...</option>');
    
    if (parishId) {
        $.get(APP_URL + '/api/locations.php', {action: 'get_villages', parish_id: parishId}, function(response) {
            if (response.success) {
                response.data.forEach(v => {
                    $('#village_id').append(`<option value="${v.id}">${v.village_name}</option>`);
                });
            }
        });
    }
});

// Toggle role assignment section
$('#assignRoleNow').change(function() {
    $('#roleAssignmentSection').toggle(this.checked);
    if (!this.checked) {
        $('#role_level, #role_id').val('');
        $('#roleSelectContainer').hide();
    }
});

// Role level selection
$('#role_level').change(function() {
    const level = $(this).val();
    if (!level) {
        $('#roleSelectContainer').hide();
        return;
    }

    // Load roles for this level
    $.get(APP_URL + '/api/extension-management.php', {action: 'get_roles_by_level', level: level}, function(response) {
        if (response.success) {
            const $select = $('#role_id');
            $select.empty().append('<option value="">Select Role...</option>');
            response.data.forEach(role => {
                $select.append(`<option value="${role.id}">${role.role_name}</option>`);
            });
            $('#roleSelectContainer').show();
        }
    });
});

// Form submission
$('#createExtensionWorkerForm').submit(function(e) {
    e.preventDefault();
    
    if (!this.checkValidity()) {
        e.stopPropagation();
        this.classList.add('was-validated');
        return;
    }
    
    const formData = $(this).serialize();
    
    showLoading();
    $.post(APP_URL + '/api/admin-user-management.php', formData + '&action=create_extension_worker', function(response) {
        hideLoading();
        if (response.success) {
            Swal.fire({
                icon: 'success',
                title: 'Extension Worker Created!',
                html: `
                    <p>${response.message}</p>
                    <div class="alert alert-info mt-3">
                        <strong>Login Credentials:</strong><br>
                        Phone: ${response.phone}<br>
                        Password: ${response.password || '(as set)'}
                    </div>
                    <p class="small text-muted">SMS notification has been sent to the user.</p>
                `,
                confirmButtonText: 'Go to Assignments'
            }).then(() => {
                window.location.href = APP_URL + '/admin/extension-assignments.php';
            });
        } else {
            showToast(response.message, 'error');
        }
    }, 'json').fail(function() {
        hideLoading();
        showToast('Connection error. Please try again.', 'error');
    });
});

}); // End document ready

// Global function for password generation
function generatePassword() {
    const length = 8;
    const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    let password = "";
    for (let i = 0; i < length; i++) {
        password += charset.charAt(Math.floor(Math.random() * charset.length));
    }
    document.getElementById('password').value = password;
    showToast('Password generated: ' + password, 'success');
}
</script>

<?php renderAdminFooter(); ?>