<?php
include("conexion.php");
session_start();

if (!isset($_SESSION['usuario'])) {
    header('Location: login.php');
    exit;
}

$personas = [];
$success_message = '';
$error_message = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Obtener y sanitizar datos del formulario
    $id_persona = mysqli_real_escape_string($conexion, $_POST["id_persona"]);
    $apellido = mysqli_real_escape_string($conexion, $_POST["apellido"]);
    $nombre = mysqli_real_escape_string($conexion, $_POST["nombre"]);
    $cedula = mysqli_real_escape_string($conexion, $_POST["cedula"]);
    $edad = mysqli_real_escape_string($conexion, $_POST["edad"]);
    $parentesco = mysqli_real_escape_string($conexion, $_POST["parentesco"]);
    $fecha_nacimiento = mysqli_real_escape_string($conexion, $_POST["fecha_nacimiento"]);
    $sexo = mysqli_real_escape_string($conexion, $_POST["sexo"]);

    // Validar que todos los campos requeridos estén completos
    if (empty($id_persona) || empty($apellido) || empty($nombre) || empty($cedula) || empty($edad) || empty($parentesco) || empty($fecha_nacimiento) || empty($sexo)) {
        $error_message = "Todos los campos son requeridos.";
    } else {
        // Insertar en la tabla carga_familiar
        $sql = "INSERT INTO carga_familiar (id_persona, apellido, nombre, cedula, edad, parentesco, fecha_nacimiento, sexo) 
                VALUES ('$id_persona', '$apellido', '$nombre', '$cedula', '$edad', '$parentesco', '$fecha_nacimiento', '$sexo')";

        if (mysqli_query($conexion, $sql)) {
            $success_message = "Carga familiar registrada correctamente.";
            // Redirigir después de 2 segundos
            header("refresh:2;url=index.php");
        } else {
            $error_message = "Error al registrar carga familiar: " . mysqli_error($conexion);
        }
    }
}

// Consulta para obtener las personas ordenadas alfabéticamente
$sql_personas = "SELECT id, nombre, apellido, cedula FROM personas ORDER BY apellido, nombre";
$resultado_personas = mysqli_query($conexion, $sql_personas);

if (mysqli_num_rows($resultado_personas) > 0) {
    while ($row = mysqli_fetch_assoc($resultado_personas)) {
        $personas[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Registrar Carga Familiar | Sistema de Talento Humano</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: #1a3c8b;
            --secondary-color: #4CAF50;
            --accent-color: #FF9800;
            --light-color: #f8f9fa;
            --dark-color: #2c3e50;
            --gray-light: #f5f7fa;
            --border-color: #e1e5eb;
        }
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background-color: var(--gray-light);
            color: var(--dark-color);
            line-height: 1.6;
        }
        
        .app-container {
            display: flex;
            min-height: 100vh;
        }
        
        /* Sidebar */
        .sidebar {
            width: 260px;
            background: linear-gradient(180deg, var(--primary-color) 0%, #15326f 100%);
            color: white;
            padding: 0;
            box-shadow: 3px 0 15px rgba(0, 0, 0, 0.1);
            z-index: 100;
            position: fixed;
            height: 100vh;
            overflow-y: auto;
        }
        
        .sidebar-header {
            padding: 25px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            text-align: center;
        }
        
        .company-logo {
            width: 70px;
            height: 70px;
            background-color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 15px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
        }
        
        .company-logo img {
            max-width: 50px;
            max-height: 50px;
        }
        
        .company-name {
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 5px;
        }
        
        .system-name {
            font-size: 0.85rem;
            opacity: 0.9;
            font-weight: 400;
        }
        
        .user-info {
            padding: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            align-items: center;
        }
        
        .user-avatar {
            width: 45px;
            height: 45px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
        }
        
        .user-avatar i {
            font-size: 1.2rem;
        }
        
        .user-details h4 {
            font-size: 1rem;
            font-weight: 600;
            margin-bottom: 2px;
        }
        
        .user-details p {
            font-size: 0.8rem;
            opacity: 0.8;
        }
        
        .sidebar-menu {
            padding: 20px 0;
        }
        
        .menu-section {
            margin-bottom: 25px;
        }
        
        .menu-title {
            font-size: 0.8rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            opacity: 0.7;
            padding: 0 20px 10px;
            margin-bottom: 10px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .menu-item {
            display: flex;
            align-items: center;
            padding: 12px 20px;
            color: rgba(255, 255, 255, 0.8);
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }
        
        .menu-item:hover, .menu-item.active {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border-left-color: var(--accent-color);
        }
        
        .menu-item i {
            margin-right: 12px;
            width: 20px;
            text-align: center;
            font-size: 1.1rem;
        }
        
        .logout-item {
            margin-top: 20px;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
            padding-top: 20px;
        }
        
        /* Main Content */
        .main-content {
            flex: 1;
            margin-left: 260px;
            padding: 0;
        }
        
        .top-navbar {
            background-color: white;
            padding: 15px 30px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: sticky;
            top: 0;
            z-index: 99;
        }
        
        .page-title h1 {
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--dark-color);
            margin: 0;
        }
        
        .page-title p {
            font-size: 0.9rem;
            color: #666;
            margin: 5px 0 0;
        }
        
        .content-wrapper {
            padding: 30px;
        }
        
        /* Registration Container */
        .registration-container {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            margin-bottom: 30px;
            border: 1px solid var(--border-color);
        }
        
        .form-header {
            background: linear-gradient(135deg, var(--primary-color), #2a4ca3);
            color: white;
            padding: 25px 30px;
        }
        
        .form-header h2 {
            font-size: 1.8rem;
            font-weight: 600;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .form-header h2 i {
            color: var(--accent-color);
        }
        
        .form-header p {
            opacity: 0.9;
            margin-top: 8px;
            font-size: 0.95rem;
        }
        
        .form-body {
            padding: 30px;
        }
        
        /* Form Layout */
        .form-main {
            display: flex;
            flex-wrap: wrap;
            gap: 30px;
        }
        
        .employee-selector {
            flex: 1;
            min-width: 300px;
        }
        
        .family-form {
            flex: 2;
            min-width: 300px;
        }
        
        /* Employee Selector */
        .selector-card {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 25px;
            border: 1px solid var(--border-color);
            height: 100%;
        }
        
        .selector-title {
            color: var(--primary-color);
            font-size: 1.2rem;
            font-weight: 600;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .selector-title i {
            color: var(--accent-color);
        }
        
        .employee-list {
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
        }
        
        .employee-item {
            padding: 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .employee-item:hover {
            background: white;
            border-color: var(--primary-color);
            transform: translateY(-2px);
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }
        
        .employee-item.selected {
            background: rgba(26, 60, 139, 0.1);
            border-color: var(--primary-color);
        }
        
        .employee-name {
            font-weight: 600;
            color: var(--dark-color);
            margin-bottom: 5px;
        }
        
        .employee-details {
            font-size: 0.9rem;
            color: #666;
        }
        
        /* Family Form */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-label {
            font-weight: 600;
            color: var(--dark-color);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .required::after {
            content: '*';
            color: #dc3545;
            margin-left: 4px;
        }
        
        .form-control, .form-select {
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s;
            width: 100%;
        }
        
        .form-control:focus, .form-select:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(26, 60, 139, 0.1);
        }
        
        /* Family Member Info */
        .family-info {
            background: linear-gradient(135deg, #f8f9fa, #e9ecef);
            border-radius: 12px;
            padding: 25px;
            margin-bottom: 30px;
            border: 1px solid var(--border-color);
        }
        
        .family-info h3 {
            color: var(--primary-color);
            font-size: 1.3rem;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .family-info h3 i {
            color: var(--accent-color);
        }
        
        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
        }
        
        .info-item {
            display: flex;
            flex-direction: column;
        }
        
        .info-label {
            font-weight: 600;
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 5px;
        }
        
        .info-value {
            font-size: 1rem;
            color: var(--dark-color);
            padding: 8px 12px;
            background: white;
            border-radius: 6px;
            border-left: 4px solid var(--primary-color);
        }
        
        /* Form Actions */
        .form-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-top: 30px;
            border-top: 1px solid var(--border-color);
            margin-top: 20px;
        }
        
        .btn-primary {
            background: linear-gradient(to right, var(--primary-color), #2a4ca3);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .btn-primary:hover {
            background: linear-gradient(to right, #15326f, var(--primary-color));
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(26, 60, 139, 0.2);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 8px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.3s;
        }
        
        .btn-secondary:hover {
            background: #545b62;
            color: white;
            transform: translateY(-2px);
        }
        
        /* Alert Messages */
        .alert-message {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .alert-success {
            background: rgba(40, 167, 69, 0.1);
            border: 1px solid rgba(40, 167, 69, 0.2);
            color: #155724;
        }
        
        .alert-danger {
            background: rgba(220, 53, 69, 0.1);
            border: 1px solid rgba(220, 53, 69, 0.2);
            color: #721c24;
        }
        
        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 40px 20px;
            color: #666;
        }
        
        .empty-state i {
            font-size: 3rem;
            margin-bottom: 15px;
            color: #ddd;
        }
        
        /* Animations */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        /* Responsive */
        @media (max-width: 992px) {
            .sidebar {
                width: 70px;
                overflow: visible;
            }
            
            .sidebar-header, .company-name, .system-name, .user-details, .menu-title, .menu-item span {
                display: none;
            }
            
            .company-logo {
                width: 40px;
                height: 40px;
                margin-bottom: 0;
            }
            
            .company-logo img {
                max-width: 25px;
                max-height: 25px;
            }
            
            .user-info {
                justify-content: center;
                padding: 15px 10px;
            }
            
            .user-avatar {
                margin-right: 0;
            }
            
            .menu-item {
                justify-content: center;
                padding: 15px 10px;
            }
            
            .menu-item i {
                margin-right: 0;
                font-size: 1.3rem;
            }
            
            .main-content {
                margin-left: 70px;
            }
            
            .form-main {
                flex-direction: column;
            }
        }
        
        @media (max-width: 768px) {
            .top-navbar {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
                padding: 15px 20px;
            }
            
            .content-wrapper {
                padding: 20px 15px;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .info-grid {
                grid-template-columns: 1fr;
            }
            
            .form-actions {
                flex-direction: column;
                gap: 15px;
            }
            
            .btn-primary, .btn-secondary {
                width: 100%;
                justify-content: center;
            }
        }
        
        /* Custom scrollbar */
        .employee-list::-webkit-scrollbar {
            width: 6px;
        }
        
        .employee-list::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }
        
        .employee-list::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }
        
        .employee-list::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
        
        ::-webkit-scrollbar {
            width: 6px;
        }
        
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        
        ::-webkit-scrollbar-thumb {
            background: #c1c1c1;
            border-radius: 3px;
        }
        
        ::-webkit-scrollbar-thumb:hover {
            background: #a8a8a8;
        }
    </style>
</head>
<body>
    <div class="app-container">
        <!-- Sidebar -->
        <aside class="sidebar">
            <div class="sidebar-header">
                <div class="company-logo">
                    <i class="fas fa-building" style="color: var(--primary-color); font-size: 1.8rem;"></i>
                </div>
                <div class="company-name">Distribuidora Riga0803 C.A.</div>
                <div class="system-name">Sistema de Talento Humano</div>
            </div>
            
            <div class="user-info">
                <div class="user-avatar">
                    <i class="fas fa-user-circle"></i>
                </div>
                <div class="user-details">
                    <h4><?php echo $_SESSION['usuario']; ?></h4>
                    <p><?php echo ucfirst($_SESSION['rol']); ?></p>
                </div>
            </div>
            
            <nav class="sidebar-menu">
                <div class="menu-section">
                    <div class="menu-title">Principal</div>
                    <a href="index.php" class="menu-item">
                        <i class="fas fa-users"></i>
                        <span>Personal</span>
                    </a>
                    <a href="ficha.php" class="menu-item">
                        <i class="fas fa-id-card"></i>
                        <span>Fichas</span>
                    </a>
                </div>
                
                <div class="menu-section">
                    <div class="menu-title">Módulos</div>
                    <a href="turnos.php" class="menu-item">
                        <i class="fas fa-clock"></i>
                        <span>Turnos</span>
                    </a>
                    <a href="cargos.php" class="menu-item">
                        <i class="fas fa-briefcase"></i>
                        <span>Cargos</span>
                    </a>
                    <a href="carga_familiar.php" class="menu-item active">
                        <i class="fas fa-family"></i>
                        <span>Carga Familiar</span>
                    </a>
                    <a href="consultar_carga_familiar.php" class="menu-item">
                        <i class="fas fa-search"></i>
                        <span>Consulta Carga</span>
                    </a>
                </div>
                
                <div class="menu-section logout-item">
                    <a href="logout.php" class="menu-item">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>Cerrar Sesión</span>
                    </a>
                </div>
            </nav>
        </aside>
        
        <!-- Main Content -->
        <main class="main-content">
            <!-- Top Navbar -->
            <header class="top-navbar">
                <div class="page-title">
                    <h1>Registrar Carga Familiar</h1>
                    <p>Registro de familiares dependientes del personal</p>
                </div>
            </header>
            
            <!-- Content Area -->
            <div class="content-wrapper">
                <?php if ($success_message): ?>
                    <div class="alert-message alert-success">
                        <i class="fas fa-check-circle"></i>
                        <div>
                            <strong>¡Éxito!</strong> <?php echo $success_message; ?>
                            <p>Redirigiendo al listado principal...</p>
                        </div>
                    </div>
                <?php endif; ?>
                
                <?php if ($error_message): ?>
                    <div class="alert-message alert-danger">
                        <i class="fas fa-exclamation-circle"></i>
                        <div>
                            <strong>Error:</strong> <?php echo $error_message; ?>
                        </div>
                    </div>
                <?php endif; ?>
                
                <div class="registration-container">
                    <div class="form-header">
                        <h2><i class="fas fa-user-friends"></i> Registro de Carga Familiar</h2>
                        <p>Seleccione el empleado y complete la información del familiar dependiente</p>
                    </div>
                    
                    <div class="form-body">
                        <form action="" method="post" id="familyForm">
                            <div class="form-main">
                                <!-- Employee Selector -->
                                <div class="employee-selector">
                                    <div class="selector-card">
                                        <h3 class="selector-title">
                                            <i class="fas fa-user-tie"></i> Seleccionar Empleado
                                        </h3>
                                        
                                        <?php if (count($personas) > 0): ?>
                                            <div class="employee-list">
                                                <?php foreach ($personas as $persona): ?>
                                                    <div class="employee-item" data-id="<?php echo $persona['id']; ?>" 
                                                         data-name="<?php echo htmlspecialchars($persona['nombre'] . ' ' . $persona['apellido']); ?>"
                                                         data-cedula="<?php echo htmlspecialchars($persona['cedula']); ?>">
                                                        <div class="employee-name">
                                                            <?php echo htmlspecialchars($persona['nombre'] . ' ' . $persona['apellido']); ?>
                                                        </div>
                                                        <div class="employee-details">
                                                            Cédula: <?php echo htmlspecialchars($persona['cedula']); ?>
                                                        </div>
                                                    </div>
                                                <?php endforeach; ?>
                                            </div>
                                            
                                            <input type="hidden" name="id_persona" id="id_persona" required>
                                            <div class="selected-employee-info" id="selectedEmployeeInfo" style="display: none;">
                                                <div class="info-value">
                                                    <i class="fas fa-check-circle text-success"></i>
                                                    <span id="selectedEmployeeName"></span>
                                                </div>
                                            </div>
                                        <?php else: ?>
                                            <div class="empty-state">
                                                <i class="fas fa-users-slash"></i>
                                                <h3>No hay empleados registrados</h3>
                                                <p>Primero debe registrar empleados en el sistema</p>
                                                <a href="crear.php" class="btn-primary mt-3">
                                                    <i class="fas fa-user-plus"></i> Registrar Empleado
                                                </a>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <!-- Family Member Form -->
                                <div class="family-form">
                                    <div class="family-info" id="familyInfo" style="display: none;">
                                        <h3><i class="fas fa-info-circle"></i> Empleado Seleccionado</h3>
                                        <div class="info-grid">
                                            <div class="info-item">
                                                <span class="info-label">Nombre Completo</span>
                                                <span class="info-value" id="infoEmployeeName">-</span>
                                            </div>
                                            <div class="info-item">
                                                <span class="info-label">Cédula</span>
                                                <span class="info-value" id="infoEmployeeCedula">-</span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <h3 class="selector-title mt-4">
                                        <i class="fas fa-user-plus"></i> Información del Familiar
                                    </h3>
                                    
                                    <div class="form-grid">
                                        <div class="form-group">
                                            <label for="nombre" class="form-label required">
                                                <i class="fas fa-signature"></i> Nombre
                                            </label>
                                            <input type="text" class="form-control" name="nombre" id="nombre" required 
                                                   placeholder="Ingrese el nombre del familiar">
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="apellido" class="form-label required">
                                                <i class="fas fa-signature"></i> Apellido
                                            </label>
                                            <input type="text" class="form-control" name="apellido" id="apellido" required 
                                                   placeholder="Ingrese el apellido del familiar">
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="cedula" class="form-label required">
                                                <i class="fas fa-id-card"></i> Cédula
                                            </label>
                                            <input type="text" class="form-control" name="cedula" id="cedula" required 
                                                   placeholder="Ej: V-12345678">
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="edad" class="form-label required">
                                                <i class="fas fa-birthday-cake"></i> Edad
                                            </label>
                                            <input type="number" class="form-control" name="edad" id="edad" required 
                                                   placeholder="Ingrese la edad" min="0" max="120">
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="fecha_nacimiento" class="form-label required">
                                                <i class="fas fa-calendar-alt"></i> Fecha de Nacimiento
                                            </label>
                                            <input type="date" class="form-control" name="fecha_nacimiento" id="fecha_nacimiento" required>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="sexo" class="form-label required">
                                                <i class="fas fa-venus-mars"></i> Sexo
                                            </label>
                                            <select class="form-select" name="sexo" id="sexo" required>
                                                <option value="">Seleccione...</option>
                                                <option value="Masculino">Masculino</option>
                                                <option value="Femenino">Femenino</option>
                                            </select>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label for="parentesco" class="form-label required">
                                                <i class="fas fa-family"></i> Parentesco
                                            </label>
                                            <select class="form-select" name="parentesco" id="parentesco" required>
                                                <option value="">Seleccione el parentesco...</option>
                                                <option value="Cónyuge">Cónyuge</option>
                                                <option value="Hijo(a)">Hijo(a)</option>
                                                <option value="Padre">Padre</option>
                                                <option value="Madre">Madre</option>
                                                <option value="Hermano(a)">Hermano(a)</option>
                                                <option value="Abuelo(a)">Abuelo(a)</option>
                                                <option value="Nieto(a)">Nieto(a)</option>
                                                <option value="Sobrino(a)">Sobrino(a)</option>
                                                <option value="Primo(a)">Primo(a)</option>
                                                <option value="Tío(a)">Tío(a)</option>
                                                <option value="Otro">Otro</option>
                                            </select>
                                        </div>
                                        
                                        <div class="form-group" id="otherParentescoContainer" style="display: none;">
                                            <label for="other_parentesco" class="form-label">
                                                <i class="fas fa-comment-alt"></i> Especificar Parentesco
                                            </label>
                                            <input type="text" class="form-control" id="other_parentesco" 
                                                   placeholder="Especifique el parentesco">
                                        </div>
                                    </div>
                                    
                                    <!-- Form Actions -->
                                    <div class="form-actions">
                                        <a href="index.php" class="btn-secondary">
                                            <i class="fas fa-arrow-left"></i> Cancelar
                                        </a>
                                        
                                        <button type="submit" class="btn-primary" id="submitBtn" disabled>
                                            <i class="fas fa-save"></i> Registrar Familiar
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </main>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.12.9/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Employee selection
            const employeeItems = document.querySelectorAll('.employee-item');
            const idPersonaInput = document.getElementById('id_persona');
            const familyInfo = document.getElementById('familyInfo');
            const infoEmployeeName = document.getElementById('infoEmployeeName');
            const infoEmployeeCedula = document.getElementById('infoEmployeeCedula');
            const submitBtn = document.getElementById('submitBtn');
            
            employeeItems.forEach(item => {
                item.addEventListener('click', function() {
                    // Remove selected class from all items
                    employeeItems.forEach(el => el.classList.remove('selected'));
                    
                    // Add selected class to clicked item
                    this.classList.add('selected');
                    
                    // Set the hidden input value
                    const employeeId = this.getAttribute('data-id');
                    const employeeName = this.getAttribute('data-name');
                    const employeeCedula = this.getAttribute('data-cedula');
                    
                    idPersonaInput.value = employeeId;
                    
                    // Show employee info
                    familyInfo.style.display = 'block';
                    infoEmployeeName.textContent = employeeName;
                    infoEmployeeCedula.textContent = employeeCedula;
                    
                    // Enable submit button
                    submitBtn.disabled = false;
                    
                    // Smooth animation
                    familyInfo.style.opacity = '0';
                    familyInfo.style.transform = 'translateY(10px)';
                    setTimeout(() => {
                        familyInfo.style.transition = 'all 0.3s ease';
                        familyInfo.style.opacity = '1';
                        familyInfo.style.transform = 'translateY(0)';
                    }, 10);
                });
            });
            
            // Parentesco "Otro" handling
            const parentescoSelect = document.getElementById('parentesco');
            const otherParentescoContainer = document.getElementById('otherParentescoContainer');
            const otherParentescoInput = document.getElementById('other_parentesco');
            
            parentescoSelect.addEventListener('change', function() {
                if (this.value === 'Otro') {
                    otherParentescoContainer.style.display = 'block';
                    // Copy value from other input to hidden field before submit
                } else {
                    otherParentescoContainer.style.display = 'none';
                    otherParentescoInput.value = '';
                }
            });
            
            // Form validation
            const familyForm = document.getElementById('familyForm');
            
            familyForm.addEventListener('submit', function(e) {
                // If "Otro" is selected, copy the custom value to parentesco field
                if (parentescoSelect.value === 'Otro' && otherParentescoInput.value.trim()) {
                    // Create a hidden input with the custom value
                    const hiddenInput = document.createElement('input');
                    hiddenInput.type = 'hidden';
                    hiddenInput.name = 'parentesco';
                    hiddenInput.value = otherParentescoInput.value;
                    this.appendChild(hiddenInput);
                    
                    // Disable the original select to avoid duplicate submission
                    parentescoSelect.disabled = true;
                }
                
                // Validate required fields
                const requiredInputs = this.querySelectorAll('[required]');
                let isValid = true;
                
                requiredInputs.forEach(input => {
                    if (!input.value.trim() && !input.disabled) {
                        isValid = false;
                        input.style.borderColor = '#dc3545';
                        setTimeout(() => {
                            input.style.borderColor = '';
                        }, 2000);
                        
                        // Scroll to first error
                        if (isValid === false) {
                            input.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    }
                });
                
                if (!isValid) {
                    e.preventDefault();
                    alert('Por favor complete todos los campos requeridos.');
                } else if (!idPersonaInput.value) {
                    e.preventDefault();
                    alert('Por favor seleccione un empleado.');
                }
            });
            
            // Auto-calculate age based on birth date
            const birthDateInput = document.getElementById('fecha_nacimiento');
            const ageInput = document.getElementById('edad');
            
            if (birthDateInput && ageInput) {
                birthDateInput.addEventListener('change', function() {
                    const birthDate = new Date(this.value);
                    const today = new Date();
                    let age = today.getFullYear() - birthDate.getFullYear();
                    const monthDiff = today.getMonth() - birthDate.getMonth();
                    
                    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
                        age--;
                    }
                    
                    if (age >= 0) {
                        ageInput.value = age;
                    }
                });
                
                // Also update age when manually changed
                ageInput.addEventListener('change', function() {
                    if (this.value && birthDateInput.value) {
                        // Calculate approximate birth date from age
                        const today = new Date();
                        const birthYear = today.getFullYear() - parseInt(this.value);
                        const approximateDate = new Date(birthYear, today.getMonth(), today.getDate());
                        
                        // Format as YYYY-MM-DD
                        const formattedDate = approximateDate.toISOString().split('T')[0];
                        
                        // Don't overwrite if user already selected a specific date
                        if (!birthDateInput.value || birthDateInput.value === formattedDate) {
                            birthDateInput.value = formattedDate;
                        }
                    }
                });
            }
            
            // Smooth transitions
            document.body.style.opacity = '0';
            setTimeout(() => {
                document.body.style.transition = 'opacity 0.3s';
                document.body.style.opacity = '1';
            }, 50);
            
            // Auto-focus first input
            setTimeout(() => {
                document.querySelector('.form-control')?.focus();
            }, 100);
        });
    </script>
</body>
</html>
