<?php
/**
 * ============================================================================
 * api/extension-management.php - Extension Assignment Management API
 * ============================================================================
 */

define('AIMS_ACCESS', true);
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json');

// Require admin authentication
if (!isLoggedIn() || !in_array(getUserType(), ['admin', 'super_admin'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

$database = new Database();
$db = $database->getConnection();

$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    switch ($action) {
        case 'create_assignment':
            createAssignment($db);
            break;
            
        case 'update_assignment':
            updateAssignment($db);
            break;
            
        case 'deactivate_assignment':
            deactivateAssignment($db);
            break;
            
        case 'get_assignment':
            getAssignment($db);
            break;
            
        case 'get_potential_supervisors':
            getPotentialSupervisors($db);
            break;
            
        default:
            jsonError('Invalid action');
    }
} catch (Exception $e) {
    logError('Extension Management API Error: ' . $e->getMessage());
    jsonError('An error occurred: ' . $e->getMessage());
}

/**
 * Create new extension assignment
 */
function createAssignment($db) {
    // Validate required fields
    $required = ['user_id', 'role_id', 'role_level', 'organization_name', 'start_date'];
    foreach ($required as $field) {
        if (empty($_POST[$field])) {
            jsonError(ucfirst(str_replace('_', ' ', $field)) . ' is required');
        }
    }
    
    $userId = (int)$_POST['user_id'];
    $roleId = (int)$_POST['role_id'];
    $roleLevel = sanitize($_POST['role_level']);
    $organizationName = sanitize($_POST['organization_name']);
    $startDate = $_POST['start_date'];
    $endDate = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
    
    // Get location IDs based on role level
    $regionId = !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null;
    $districtId = !empty($_POST['district_id']) ? (int)$_POST['district_id'] : null;
    $subcountyId = !empty($_POST['subcounty_id']) ? (int)$_POST['subcounty_id'] : null;
    $parishId = !empty($_POST['parish_id']) ? (int)$_POST['parish_id'] : null;
    $villageId = !empty($_POST['village_id']) ? (int)$_POST['village_id'] : null;
    
    // Check if user already has active assignment
    $sql = "SELECT id FROM extension_assignments WHERE user_id = ? AND is_active = 1";
    $stmt = $db->prepare($sql);
    $stmt->execute([$userId]);
    
    if ($stmt->fetch()) {
        jsonError('This officer already has an active assignment. Please deactivate it first.');
    }
    
    // Find appropriate supervisor based on hierarchy
    $supervisorId = findSupervisor($db, $roleLevel, $regionId, $districtId, $subcountyId, $parishId);
    
    // Create assignment
    $sql = "INSERT INTO extension_assignments 
            (user_id, role_id, organization_name, assigned_level, 
             region_id, district_id, subcounty_id, parish_id, village_id,
             supervisor_id, start_date, end_date, assigned_by, is_active)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)";
    
    $stmt = $db->prepare($sql);
    $result = $stmt->execute([
        $userId,
        $roleId,
        $organizationName,
        $roleLevel,
        $regionId,
        $districtId,
        $subcountyId,
        $parishId,
        $villageId,
        $supervisorId,
        $startDate,
        $endDate,
        getUserId()
    ]);
    
    if ($result) {
        // Log activity
        logActivity(getUserId(), 'create_extension_assignment', "Created assignment for user ID: $userId");
        
        jsonSuccess('Assignment created successfully', [
            'assignment_id' => $db->lastInsertId()
        ]);
    } else {
        jsonError('Failed to create assignment');
    }
}

/**
 * Update existing assignment
 */
function updateAssignment($db) {
    if (empty($_POST['assignment_id'])) {
        jsonError('Assignment ID is required');
    }
    
    $assignmentId = (int)$_POST['assignment_id'];
    $roleId = (int)$_POST['role_id'];
    $roleLevel = sanitize($_POST['role_level']);
    $organizationName = sanitize($_POST['organization_name']);
    $startDate = $_POST['start_date'];
    $endDate = !empty($_POST['end_date']) ? $_POST['end_date'] : null;
    
    $regionId = !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null;
    $districtId = !empty($_POST['district_id']) ? (int)$_POST['district_id'] : null;
    $subcountyId = !empty($_POST['subcounty_id']) ? (int)$_POST['subcounty_id'] : null;
    $parishId = !empty($_POST['parish_id']) ? (int)$_POST['parish_id'] : null;
    $villageId = !empty($_POST['village_id']) ? (int)$_POST['village_id'] : null;
    
    // Find appropriate supervisor
    $supervisorId = findSupervisor($db, $roleLevel, $regionId, $districtId, $subcountyId, $parishId);
    
    $sql = "UPDATE extension_assignments SET 
            role_id = ?,
            organization_name = ?,
            assigned_level = ?,
            region_id = ?,
            district_id = ?,
            subcounty_id = ?,
            parish_id = ?,
            village_id = ?,
            supervisor_id = ?,
            start_date = ?,
            end_date = ?,
            updated_at = CURRENT_TIMESTAMP
            WHERE id = ?";
    
    $stmt = $db->prepare($sql);
    $result = $stmt->execute([
        $roleId,
        $organizationName,
        $roleLevel,
        $regionId,
        $districtId,
        $subcountyId,
        $parishId,
        $villageId,
        $supervisorId,
        $startDate,
        $endDate,
        $assignmentId
    ]);
    
    if ($result) {
        logActivity(getUserId(), 'update_extension_assignment', "Updated assignment ID: $assignmentId");
        jsonSuccess('Assignment updated successfully');
    } else {
        jsonError('Failed to update assignment');
    }
}

/**
 * Deactivate assignment
 */
function deactivateAssignment($db) {
    if (empty($_POST['assignment_id'])) {
        jsonError('Assignment ID is required');
    }
    
    $assignmentId = (int)$_POST['assignment_id'];
    
    $sql = "UPDATE extension_assignments SET 
            is_active = 0,
            end_date = CURDATE(),
            updated_at = CURRENT_TIMESTAMP
            WHERE id = ?";
    
    $stmt = $db->prepare($sql);
    $result = $stmt->execute([$assignmentId]);
    
    if ($result) {
        logActivity(getUserId(), 'deactivate_extension_assignment', "Deactivated assignment ID: $assignmentId");
        jsonSuccess('Assignment deactivated successfully');
    } else {
        jsonError('Failed to deactivate assignment');
    }
}

/**
 * Get assignment details
 */
function getAssignment($db) {
    if (empty($_GET['assignment_id'])) {
        jsonError('Assignment ID is required');
    }
    
    $assignmentId = (int)$_GET['assignment_id'];
    
    $sql = "SELECT 
                ea.*,
                u.full_name,
                er.role_name,
                r.region_name,
                d.district_name,
                s.subcounty_name,
                p.parish_name,
                v.village_name
            FROM extension_assignments ea
            JOIN users u ON ea.user_id = u.id
            JOIN extension_roles er ON ea.role_id = er.id
            LEFT JOIN regions r ON ea.region_id = r.id
            LEFT JOIN districts d ON ea.district_id = d.id
            LEFT JOIN subcounties s ON ea.subcounty_id = s.id
            LEFT JOIN parishes p ON ea.parish_id = p.id
            LEFT JOIN villages v ON ea.village_id = v.id
            WHERE ea.id = ?";
    
    $stmt = $db->prepare($sql);
    $stmt->execute([$assignmentId]);
    $assignment = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($assignment) {
        jsonSuccess('Assignment retrieved', $assignment);
    } else {
        jsonError('Assignment not found');
    }
}

/**
 * Find appropriate supervisor based on hierarchy and location
 */
function findSupervisor($db, $level, $regionId, $districtId, $subcountyId, $parishId) {
    // Hierarchy mapping
    $supervisorLevel = [
        'regional' => 'national',
        'district' => 'regional',
        'subcounty' => 'district',
        'parish' => 'subcounty',
        'village' => 'parish'
    ];
    
    // National level has no supervisor
    if ($level === 'national') {
        return null;
    }
    
    $requiredLevel = $supervisorLevel[$level] ?? null;
    if (!$requiredLevel) {
        return null;
    }
    
    // Build query based on level
    $sql = "SELECT ea.user_id 
            FROM extension_assignments ea
            WHERE ea.is_active = 1 
            AND ea.assigned_level = ?";
    
    $params = [$requiredLevel];
    
    // Add location constraints based on hierarchy
    if ($requiredLevel === 'regional' && $regionId) {
        $sql .= " AND ea.region_id = ?";
        $params[] = $regionId;
    } elseif ($requiredLevel === 'district' && $districtId) {
        $sql .= " AND ea.district_id = ?";
        $params[] = $districtId;
    } elseif ($requiredLevel === 'subcounty' && $subcountyId) {
        $sql .= " AND ea.subcounty_id = ?";
        $params[] = $subcountyId;
    } elseif ($requiredLevel === 'parish' && $parishId) {
        $sql .= " AND ea.parish_id = ?";
        $params[] = $parishId;
    }
    
    $sql .= " LIMIT 1";
    
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    return $result ? $result['user_id'] : null;
}

/**
 * Get potential supervisors for a given level and location
 */
function getPotentialSupervisors($db) {
    $level = $_GET['level'] ?? '';
    $regionId = $_GET['region_id'] ?? null;
    $districtId = $_GET['district_id'] ?? null;
    $subcountyId = $_GET['subcounty_id'] ?? null;
    $parishId = $_GET['parish_id'] ?? null;
    
    $supervisorId = findSupervisor($db, $level, $regionId, $districtId, $subcountyId, $parishId);
    
    if ($supervisorId) {
        $sql = "SELECT u.id, u.full_name, ea.assigned_level 
                FROM users u
                JOIN extension_assignments ea ON u.id = ea.user_id
                WHERE u.id = ? AND ea.is_active = 1";
        $stmt = $db->prepare($sql);
        $stmt->execute([$supervisorId]);
        $supervisor = $stmt->fetch(PDO::FETCH_ASSOC);
        
        jsonSuccess('Supervisor found', $supervisor);
    } else {
        jsonSuccess('No supervisor required', null);
    }
}
?>