<?php
/**
 * Seed de permisos para actividades y comentarios (Leads/Clientes).
 * Ejecutar:
 *   php modules/database/seed_activity_permissions.php
 */
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

$db = getDB();
$pdo = $db->getConnection();

$perms = [
  // Actividades de Lead
  ['lead_activities.view','Ver actividades de leads','Permite ver el historial de actividades de leads','leads','activities.view',1],
  ['lead_activities.add','Agregar actividades de leads','Permite crear nuevas actividades en leads','leads','activities.add',1],
  ['lead_activities.edit','Editar actividades de leads','Permite editar actividades existentes en leads','leads','activities.edit',1],
  ['lead_activities.delete','Eliminar actividades de leads','Permite eliminar actividades en leads','leads','activities.delete',1],
  // Comentarios / Notas de Lead
  ['lead_comments.view','Ver comentarios de leads','Permite ver comentarios/notas en leads','leads','comments.view',1],
  ['lead_comments.add','Agregar comentarios de leads','Permite agregar comentarios/notas en leads','leads','comments.add',1],
  ['lead_comments.edit','Editar comentarios de leads','Permite editar comentarios/notas en leads','leads','comments.edit',1],
  ['lead_comments.delete','Eliminar comentarios de leads','Permite eliminar comentarios/notas en leads','leads','comments.delete',1],
  // Actividades visibles en perfil de clientes (histórico desde lead)
  ['client_profile.activities.view','Ver actividades históricas en perfil de cliente','Permite ver actividades heredadas del lead en el perfil de cliente','clients','activities.view',1],
];

$insPerm = $pdo->prepare("INSERT IGNORE INTO permissions (name, display_name, description, module, action, is_system, updated_at) VALUES (?,?,?,?,?,?,NOW())");
foreach ($perms as $p) { $insPerm->execute($p); }

// Asignar a rol admin
$adminRoleId = null;
$stmt = $pdo->prepare("SELECT id FROM roles WHERE name = 'admin' LIMIT 1");
if ($stmt->execute() && ($row = $stmt->fetch())) { $adminRoleId = (int)$row['id']; }

if ($adminRoleId) {
  $getPermId = $pdo->prepare("SELECT id FROM permissions WHERE name = ?");
  $insRolePerm = $pdo->prepare("INSERT IGNORE INTO role_permissions (role_id, permission_id) VALUES (?, ?)");
  foreach ($perms as $p) {
    $getPermId->execute([$p[0]]);
    if ($pid = $getPermId->fetchColumn()) { $insRolePerm->execute([$adminRoleId, (int)$pid]); }
  }
}

echo "Permisos de actividades/comentarios creados y asignados a Admin.\n";
?>
