<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/permissions.php';
require_once '../../services/analytics/DashboardUserAccessAdminService.php';
require_once '../../services/costs/CostAccess.php';
require_once '../../services/treasury/TreasuryAccess.php';
require_once '../../services/billing/BillingAccess.php';

require_login();
require_permission('admin.users.edit');

if (strtoupper((string)($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'POST') {
    http_response_code(405);
    exit('Método no permitido.');
}
csrf_require_valid_request();

$pdo = db();
$email = strtolower(trim((string)($_POST['email'] ?? '')));
$name = trim((string)($_POST['name'] ?? ''));
$role = trim((string)($_POST['role'] ?? ''));
$status = trim((string)($_POST['status'] ?? ''));
$passwordRaw = (string)($_POST['password'] ?? '');
$postedPermissions = isset($_POST['permissions']) && is_array($_POST['permissions']) ? $_POST['permissions'] : array();
$postedDashboardAccess = isset($_POST['dashboard_access']) && is_array($_POST['dashboard_access']) ? $_POST['dashboard_access'] : array();

$allowedRoles = array('admin','administracion','comercial','operaciones');
$allowedStatuses = array('active','inactive');
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || !in_array($role, $allowedRoles, true) || !in_array($status, $allowedStatuses, true)) {
    $_SESSION['admin_users_notice'] = array('type' => 'error', 'message' => 'Los datos del usuario no son válidos.');
    header('Location: /modules/admin/users.php');
    exit;
}

$allowedModulePermissions = array();
foreach (get_system_modules(true) as $key => $module) $allowedModulePermissions[] = 'module.' . $key;
$allowedModulePermissions = array_merge($allowedModulePermissions, array_keys(cost_permission_catalog()), array_keys(treasury_permission_catalog()), array_keys(billing_permission_catalog()));
$permissions = array_values(array_unique(array_intersect(array_map('strval', $postedPermissions), $allowedModulePermissions)));
$permissions = billing_expand_user_permissions($permissions);
if (array_intersect($permissions, array('costs.edit','costs.approve','costs.payroll.view','costs.payroll.edit','costs.close','costs.product.view','costs.product.edit','costs.product.approve','costs.margin.view')) && !in_array('costs.view', $permissions, true)) $permissions[] = 'costs.view';
if (in_array('costs.payroll.edit', $permissions, true) && !in_array('costs.payroll.view', $permissions, true)) $permissions[] = 'costs.payroll.view';
if (array_intersect($permissions, array('costs.product.edit','costs.product.approve')) && !in_array('costs.product.view', $permissions, true)) $permissions[] = 'costs.product.view';
if (array_intersect($permissions, array('treasury.edit','treasury.reconcile','treasury.scenarios')) && !in_array('treasury.view', $permissions, true)) $permissions[] = 'treasury.view';
$permissionsJson = json_encode($permissions, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$passwordHashed = $passwordRaw !== '' ? password_hash($passwordRaw, PASSWORD_DEFAULT) : null;
$isActive = $status === 'active' ? 1 : 0;

try {
    $pdo->beginTransaction();
    $stmt = $pdo->prepare('INSERT INTO users (email,name,role,status,is_active,password,module_permissions,created_at) VALUES (?,?,?,?,?,?,?,NOW())');
    $stmt->execute(array($email, $name, $role, $status, $isActive, $passwordHashed, $permissionsJson));
    $userId = (int)$pdo->lastInsertId();

    $dashboardAccess = new DashboardUserAccessAdminService($pdo);
    $dashboardAccess->saveAccessMatrix($userId, $role, $postedDashboardAccess, current_user_id(), $role);
    $pdo->commit();
    $_SESSION['admin_users_notice'] = array('type' => 'success', 'message' => 'Usuario y permisos de módulos, dashboards, costos, tesorería y facturación creados correctamente.');
} catch (Throwable $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    error_log('admin user create error: ' . $e->getMessage());
    $_SESSION['admin_users_notice'] = array('type' => 'error', 'message' => 'No fue posible crear el usuario. Verifica que el email no esté registrado.');
}

header('Location: /modules/admin/users.php');
exit;
