<?php
/**
 * ============================================================================
 * api/extension-management.php - Extension Assignment Management API
 * ============================================================================
 * FIXED VERSION - Works with existing config/database setup
 */

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

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

// Use existing Database class (non-namespaced version that's already working)
$database = new Database();
$db = $database->getConnection();

// Check admin authentication using existing functions
if (!isLoggedIn() || !hasAdminAccess()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit;
}

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

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

/**
 * Get roles by level
 */
function getRolesByLevel($db) {
    $level = $_GET['level'] ?? '';
    
    if (!$level) {
        jsonError('Level is required');
    }
    
    try {
        $sql = "SELECT id, role_name, role_description 
                FROM extension_roles 
                WHERE role_level = ? AND is_active = 1
                ORDER BY role_name";
        $stmt = $db->prepare($sql);
        $stmt->execute([$level]);
        $roles = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        jsonSuccess('Roles retrieved successfully', $roles);
    } catch (PDOException $e) {
        error_log('Get Roles Error: ' . $e->getMessage());
        jsonError('Failed to fetch roles');
    }
}

/**
 * Create new assignment
 */
function createAssignment($db) {
    try {
        // 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 = sanitize($_POST['start_date']);
        $endDate = !empty($_POST['end_date']) ? sanitize($_POST['end_date']) : null;
        
        // Get location IDs
        $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.');
        }
        
        // Start transaction
        $db->beginTransaction();
        
        // Deactivate any existing assignments (safety measure)
        $sql = "UPDATE extension_assignments SET is_active = 0 WHERE user_id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$userId]);
        
        // Create new assignment
        $sql = "INSERT INTO extension_assignments (
                    user_id, role_id, organization_name, assigned_level,
                    region_id, district_id, subcounty_id, parish_id, village_id,
                    start_date, end_date, is_active, assigned_by, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, NOW())";
        
        $stmt = $db->prepare($sql);
        $result = $stmt->execute([
            $userId,
            $roleId,
            $organizationName,
            $roleLevel,
            $regionId,
            $districtId,
            $subcountyId,
            $parishId,
            $villageId,
            $startDate,
            $endDate,
            getUserId()
        ]);
        
        $assignmentId = $db->lastInsertId();
        
        // Commit transaction
        $db->commit();
        
        // Log activity using existing function
        logActivity(getUserId(), 'create_extension_assignment', "Created assignment for user ID: $userId");
        
        jsonSuccess('Assignment created successfully', ['assignment_id' => $assignmentId]);
        
    } catch (PDOException $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        error_log('Create Assignment Error: ' . $e->getMessage());
        jsonError('Database error: ' . $e->getMessage());
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        error_log('Create Assignment Error: ' . $e->getMessage());
        jsonError('Error: ' . $e->getMessage());
    }
}

/**
 * Update existing assignment
 */
function updateAssignment($db) {
    try {
        $assignmentId = (int)$_POST['assignment_id'];
        
        if (!$assignmentId) {
            jsonError('Assignment ID is required');
        }
        
        $organizationName = sanitize($_POST['organization_name']);
        $endDate = !empty($_POST['end_date']) ? sanitize($_POST['end_date']) : null;
        
        $sql = "UPDATE extension_assignments 
                SET organization_name = ?, end_date = ?, updated_at = NOW()
                WHERE id = ?";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$organizationName, $endDate, $assignmentId]);
        
        logActivity(getUserId(), 'update_extension_assignment', "Updated assignment ID: $assignmentId");
        
        jsonSuccess('Assignment updated successfully');
        
    } catch (PDOException $e) {
        error_log('Update Assignment Error: ' . $e->getMessage());
        jsonError('Database error: ' . $e->getMessage());
    }
}

/**
 * Deactivate assignment
 */
function deactivateAssignment($db) {
    try {
        $assignmentId = (int)$_POST['assignment_id'];
        
        if (!$assignmentId) {
            jsonError('Assignment ID is required');
        }
        
        $sql = "UPDATE extension_assignments 
                SET is_active = 0, end_date = CURDATE(), updated_at = NOW()
                WHERE id = ?";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([$assignmentId]);
        
        logActivity(getUserId(), 'deactivate_extension_assignment', "Deactivated assignment ID: $assignmentId");
        
        jsonSuccess('Assignment deactivated successfully');
        
    } catch (PDOException $e) {
        error_log('Deactivate Assignment Error: ' . $e->getMessage());
        jsonError('Database error: ' . $e->getMessage());
    }
}

/**
 * Get assignment details
 */
function getAssignment($db) {
    $assignmentId = (int)($_GET['assignment_id'] ?? 0);
    
    if (!$assignmentId) {
        jsonError('Assignment ID is required');
    }
    
    try {
        $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');
        }
    } catch (PDOException $e) {
        error_log('Get Assignment Error: ' . $e->getMessage());
        jsonError('Failed to fetch assignment');
    }
}