<?php
/**
 * Create Agent Directly - API endpoint for store owners to create agents
 */

session_start();
require_once '../config.php';
require_once '../app/classes/StoreManager.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Authentication required']);
    exit;
}

$userId = $_SESSION['user_id'];

// Verify user owns a store
$storeManager = new StoreManager($conn);
$store = $storeManager->getStoreByOwnerId($userId);

if (!$store) {
    echo json_encode(['success' => false, 'message' => 'Store not found']);
    exit;
}

// Get JSON input
$input = file_get_contents('php://input');
$data = json_decode($input, true);

// Log for debugging (remove in production)
error_log("Create Store Agent - Input: " . $input);
error_log("Create Store Agent - Decoded: " . print_r($data, true));

if (!$data) {
    $error = json_last_error_msg();
    error_log("Create Store Agent - JSON Error: " . $error);
    echo json_encode(['success' => false, 'message' => 'Invalid request data: ' . $error]);
    exit;
}

// SECURITY: Explicitly remove any role or is_store_owner fields
// Store owners can ONLY create agents, never store owners
unset($data['role']);
unset($data['is_store_owner']);

// Create agent directly
try {
    $result = $storeManager->createAgentDirectly($store['id'], $data);
    error_log("Create Store Agent - Result: " . print_r($result, true));
    echo json_encode($result);
} catch (Exception $e) {
    error_log("Create Store Agent - Exception: " . $e->getMessage());
    error_log("Create Store Agent - Trace: " . $e->getTraceAsString());
    echo json_encode([
        'success' => false, 
        'message' => 'Server error: ' . $e->getMessage()
    ]);
}
?>

