<?php
/**
 * ============================================================================
 * api/admin-user-management.php - Admin User Creation & Management API
 * ============================================================================
 * Handles admin-side creation of buyers and extension workers
 */

define('AIMS_ACCESS', true);

require_once __DIR__ . '/../config/config.php';

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

try {
    // Get database connection
    $database = new Database();
    $db = $database->getConnection();
    
    // Check admin authentication
    if (!isLoggedIn() || !hasAdminAccess()) {
        jsonError('Unauthorized access', 401);
    }
    
    $action = $_POST['action'] ?? '';
    
    switch ($action) {
        case 'create_extension_worker':
            createExtensionWorker($db);
            break;
            
        case 'create_buyer':
            createBuyer($db);
            break;
            
        default:
            jsonError('Invalid action', 400);
    }
} catch (Exception $e) {
    logError('Admin User Management API Error: ' . $e->getMessage());
    jsonError('An error occurred: ' . $e->getMessage(), 500);
}

/**
 * Create Extension Worker (Admin-side)
 */
function createExtensionWorker($db) {
    try {
        // Validate required fields
        $required = ['full_name', 'phone_number', 'password', 'organization', 'qualification', 'years_of_experience', 'specialization', 'village_id'];
        foreach ($required as $field) {
            if (empty($_POST[$field])) {
                jsonError(ucfirst(str_replace('_', ' ', $field)) . ' is required');
            }
        }
        
        // Validate phone
        $phone = validatePhone($_POST['phone_number']);
        if (!$phone) {
            jsonError('Invalid phone number format');
        }
        
        // Check if phone exists
        $sql = "SELECT id FROM users WHERE phone_number = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$phone]);
        if ($stmt->fetch()) {
            jsonError('Phone number already registered');
        }
        
        // Hash password
        $passwordHash = hashPassword($_POST['password']);
        
        // Start transaction
        $db->beginTransaction();
        
        // Insert user
        $sql = "INSERT INTO users (
                    phone_number, password_hash, full_name, email,
                    region_id, district_id, subcounty_id, parish_id, village_id,
                    user_type, approval_status, is_verified, is_active
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'extension_officer', 'approved', 1, 1)";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $phone,
            $passwordHash,
            sanitize($_POST['full_name']),
            sanitize($_POST['email'] ?? ''),
            !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null,
            !empty($_POST['district_id']) ? (int)$_POST['district_id'] : null,
            !empty($_POST['subcounty_id']) ? (int)$_POST['subcounty_id'] : null,
            !empty($_POST['parish_id']) ? (int)$_POST['parish_id'] : null,
            !empty($_POST['village_id']) ? (int)$_POST['village_id'] : null
        ]);
        
        $userId = $db->lastInsertId();
        
        // Create extension officer profile
        $sql = "INSERT INTO extension_officer_profiles (
                    user_id, organization, qualification, years_of_experience, specialization
                ) VALUES (?, ?, ?, ?, ?)";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $userId,
            sanitize($_POST['organization']),
            sanitize($_POST['qualification']),
            (int)$_POST['years_of_experience'],
            sanitize($_POST['specialization'])
        ]);
        
        // Optional: Create assignment if role is selected
        if (!empty($_POST['role_id']) && !empty($_POST['role_level'])) {
            $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, is_active, assigned_by
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURDATE(), 1, ?)";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $userId,
                (int)$_POST['role_id'],
                sanitize($_POST['organization']),
                sanitize($_POST['role_level']),
                !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null,
                !empty($_POST['district_id']) ? (int)$_POST['district_id'] : null,
                !empty($_POST['subcounty_id']) ? (int)$_POST['subcounty_id'] : null,
                !empty($_POST['parish_id']) ? (int)$_POST['parish_id'] : null,
                !empty($_POST['village_id']) ? (int)$_POST['village_id'] : null,
                getUserId()
            ]);
        }
        
        // Commit transaction
        $db->commit();
        
        // Log activity
        logAdminActivity(getUserId(), 'create_extension_worker', "Created extension worker: {$_POST['full_name']} (ID: $userId)", $db);
        
        // TODO: Send SMS with login credentials
        
        echo json_encode([
            'success' => true,
            'message' => 'Extension worker created successfully',
            'user_id' => $userId,
            'phone' => $phone,
            'password' => $_POST['password']
        ]);
        exit;
        
    } catch (PDOException $e) {
        $db->rollBack();
        logError('Extension Worker Creation Error: ' . $e->getMessage());
        jsonError('Database error: ' . $e->getMessage());
    }
}

/**
 * Create Buyer (Admin-side)
 */
function createBuyer($db) {
    try {
        // Validate required fields
        $required = ['full_name', 'phone_number', 'email', 'password', 'buyer_type', 'district_id'];
        foreach ($required as $field) {
            if (empty($_POST[$field])) {
                jsonError(ucfirst(str_replace('_', ' ', $field)) . ' is required');
            }
        }
        
        // Validate phone
        $phone = validatePhone($_POST['phone_number']);
        if (!$phone) {
            jsonError('Invalid phone number format');
        }
        
        // Check if phone exists
        $sql = "SELECT id FROM users WHERE phone_number = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$phone]);
        if ($stmt->fetch()) {
            jsonError('Phone number already registered');
        }
        
        // Hash password
        $passwordHash = hashPassword($_POST['password']);
        
        // Start transaction
        $db->beginTransaction();
        
        // Insert user
        $sql = "INSERT INTO users (
                    phone_number, password_hash, full_name, email,
                    region_id, district_id, subcounty_id, parish_id, village_id,
                    user_type, approval_status, is_verified, is_active
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'buyer', 'approved', 1, 1)";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $phone,
            $passwordHash,
            sanitize($_POST['full_name']),
            sanitize($_POST['email']),
            !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null,
            !empty($_POST['district_id']) ? (int)$_POST['district_id'] : null,
            !empty($_POST['subcounty_id']) ? (int)$_POST['subcounty_id'] : null,
            !empty($_POST['parish_id']) ? (int)$_POST['parish_id'] : null,
            !empty($_POST['village_id']) ? (int)$_POST['village_id'] : null
        ]);
        
        $userId = $db->lastInsertId();
        
        // Create buyer profile
        $sql = "INSERT INTO buyer_profiles (
                    user_id, buyer_type, business_name, business_registration, 
                    tax_id, business_address, business_phone
                ) VALUES (?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $userId,
            sanitize($_POST['buyer_type']),
            sanitize($_POST['business_name'] ?? ''),
            sanitize($_POST['business_registration'] ?? ''),
            sanitize($_POST['tax_id'] ?? ''),
            sanitize($_POST['business_address'] ?? ''),
            sanitize($_POST['business_phone'] ?? '')
        ]);
        
        // Commit transaction
        $db->commit();
        
        // Log activity
        logAdminActivity(getUserId(), 'create_buyer', "Created buyer: {$_POST['full_name']} (ID: $userId)", $db);
        
        // TODO: Send SMS with login credentials
        
        echo json_encode([
            'success' => true,
            'message' => 'Buyer account created successfully',
            'user_id' => $userId,
            'phone' => $phone,
            'password' => $_POST['password']
        ]);
        exit;
        
    } catch (PDOException $e) {
        $db->rollBack();
        logError('Buyer Creation Error: ' . $e->getMessage());
        jsonError('Database error: ' . $e->getMessage());
    }
}

/**
 * Log admin activity
 */
function logAdminActivity($adminId, $actionType, $description, $db) {
    $sql = "INSERT INTO admin_activity_log (admin_id, action_type, action_description, ip_address, user_agent)
            VALUES (?, ?, ?, ?, ?)";
    $stmt = $db->prepare($sql);
    $stmt->execute([
        $adminId,
        $actionType,
        $description,
        $_SERVER['REMOTE_ADDR'] ?? '',
        $_SERVER['HTTP_USER_AGENT'] ?? ''
    ]);
}
?>