<?php
/**
 * ============================================================================
 * api/admin-user-management.php - Admin User Creation & 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
$database = new Database();
$db = $database->getConnection();

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

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

try {
    switch ($action) {
        case 'create_extension_worker':
            createExtensionWorker($db);
            break;
            
        case 'create_buyer':
            createBuyer($db);
            break;
            
        default:
            jsonError('Invalid action');
    }
} catch (Exception $e) {
    error_log('Admin User Management API Error: ' . $e->getMessage());
    jsonError('An error occurred: ' . $e->getMessage());
}

/**
 * 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 using existing function
        $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 using existing function
        $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, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'extension_officer', 'approved', 1, 1, NOW())";
        
        $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,
            (int)$_POST['village_id']
        ]);
        
        $userId = $db->lastInsertId();
        
        // Create extension officer profile
        $sql = "INSERT INTO extension_officer_profiles (
                    user_id, organization, qualification, years_of_experience, specialization, created_at
                ) VALUES (?, ?, ?, ?, ?, NOW())";
        
        $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, created_at
                    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CURDATE(), 1, ?, NOW())";
            
            $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
        logActivity(getUserId(), 'create_extension_worker', "Created extension worker: {$_POST['full_name']} (ID: $userId)");
        
        echo json_encode([
            'success' => true,
            'message' => 'Extension worker created successfully',
            'user_id' => $userId,
            'phone' => $phone,
            'password' => $_POST['password']
        ]);
        exit;
        
    } catch (PDOException $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        error_log('Extension Worker Creation Error: ' . $e->getMessage());
        jsonError('Database error: ' . $e->getMessage());
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        error_log('Extension Worker Creation Error: ' . $e->getMessage());
        jsonError('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, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'buyer', 'approved', 1, 1, NOW())";
        
        $stmt = $db->prepare($sql);
        $stmt->execute([
            $phone,
            $passwordHash,
            sanitize($_POST['full_name']),
            sanitize($_POST['email']),
            !empty($_POST['region_id']) ? (int)$_POST['region_id'] : null,
            (int)$_POST['district_id'],
            !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, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())";
        
        $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
        logActivity(getUserId(), 'create_buyer', "Created buyer: {$_POST['full_name']} (ID: $userId)");
        
        echo json_encode([
            'success' => true,
            'message' => 'Buyer account created successfully',
            'user_id' => $userId,
            'phone' => $phone,
            'password' => $_POST['password']
        ]);
        exit;
        
    } catch (PDOException $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        error_log('Buyer Creation Error: ' . $e->getMessage());
        jsonError('Database error: ' . $e->getMessage());
    } catch (Exception $e) {
        if ($db->inTransaction()) {
            $db->rollBack();
        }
        error_log('Buyer Creation Error: ' . $e->getMessage());
        jsonError('Error: ' . $e->getMessage());
    }
}