<?php
include("conexion.php");
include_once("nomina_helpers.php");
nomina_ensure_cargos_schema($conexion);
session_start();

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

// Inicializar variables
$id_cargo = $cargo = $salario = $bono_extra_usd_mensual = "";
$moneda_salario = "VES";
$edit_state = false;
$message = "";
$message_type = "";

// Manejar edición de cargo
if (isset($_GET['edit'])) {
    $id_cargo = mysqli_real_escape_string($conexion, $_GET['edit']);
    $result = mysqli_query($conexion, "SELECT * FROM cargos WHERE id_cargo='$id_cargo'");
    
    if (mysqli_num_rows($result) == 1) {
        $row = mysqli_fetch_assoc($result);
        $cargo = $row['cargo'];
        $salario = $row['salario'];
        $bono_extra_usd_mensual = isset($row['bono_extra_usd_mensual']) ? $row['bono_extra_usd_mensual'] : '';
        $moneda_salario = strtoupper((string)($row['moneda_salario'] ?? 'VES'));
        $edit_state = true;
    }
}

// Crear o actualizar cargo
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $id_cargo = isset($_POST['id_cargo']) ? mysqli_real_escape_string($conexion, $_POST['id_cargo']) : '';
    $cargo = mysqli_real_escape_string($conexion, trim((string)($_POST['cargo'] ?? '')));
    $salario = mysqli_real_escape_string($conexion, trim((string)($_POST['salario'] ?? '0')));
    $moneda_salario = strtoupper(trim((string)($_POST['moneda_salario'] ?? 'VES')));
    if (!in_array($moneda_salario, ['VES','USD'], true)) { $moneda_salario = 'VES'; }
    $bono_extra_usd_mensual = isset($_POST['bono_extra_usd_mensual']) ? mysqli_real_escape_string($conexion, trim((string)$_POST['bono_extra_usd_mensual'])) : '';
    if (isset($_POST['save'])) {
        // Validar que el cargo no exista
        $check_sql = "SELECT * FROM cargos WHERE cargo = '$cargo'";
        $check_result = mysqli_query($conexion, $check_sql);
        
        if (mysqli_num_rows($check_result) > 0) {
            $message = "El cargo '$cargo' ya existe en el sistema.";
            $message_type = "error";
        } else {
            // Insertar nuevo cargo
            $sql = "INSERT INTO cargos (cargo, salario, moneda_salario, bono_extra_usd_mensual) VALUES ('$cargo', '$salario', '$moneda_salario', '$bono_extra_usd_mensual')";
            if (mysqli_query($conexion, $sql)) {
                $message = "Cargo creado exitosamente.";
                $message_type = "success";
                // Limpiar campos
                $cargo = $salario = $bono_extra_usd_mensual = "";
                $moneda_salario = 'VES';
            } else {
                $message = "Error al crear el cargo: " . mysqli_error($conexion);
                $message_type = "error";
            }
        }
    } elseif (isset($_POST['update'])) {
        // Validar que el cargo no exista (excepto el actual)
        $check_sql = "SELECT * FROM cargos WHERE cargo = '$cargo' AND id_cargo != '$id_cargo'";
        $check_result = mysqli_query($conexion, $check_sql);
        
        if (mysqli_num_rows($check_result) > 0) {
            $message = "El cargo '$cargo' ya existe en el sistema.";
            $message_type = "error";
        } else {
            // Actualizar cargo
            $sql = "UPDATE cargos SET cargo='$cargo', salario='$salario', moneda_salario='$moneda_salario', bono_extra_usd_mensual='$bono_extra_usd_mensual' WHERE id_cargo='$id_cargo'";
            if (mysqli_query($conexion, $sql)) {
                $message = "Cargo actualizado exitosamente.";
                $message_type = "success";
                // Resetear estado de edición
                $edit_state = false;
                $id_cargo = $cargo = $salario = "";
                $moneda_salario = 'VES';
            } else {
                $message = "Error al actualizar el cargo: " . mysqli_error($conexion);
                $message_type = "error";
            }
        }
    }
}

// Eliminar cargo
if (isset($_GET['del'])) {
    $id_cargo = mysqli_real_escape_string($conexion, $_GET['del']);
    
    // Verificar si el cargo está siendo usado por algún empleado
    $check_sql = "SELECT COUNT(*) as count FROM personas WHERE id_cargo = '$id_cargo'";
    $check_result = mysqli_query($conexion, $check_sql);
    $check_row = mysqli_fetch_assoc($check_result);
    
    if ($check_row['count'] > 0) {
        $message = "No se puede eliminar el cargo porque está asignado a " . $check_row['count'] . " empleado(s).";
        $message_type = "error";
    } else {
        $sql = "DELETE FROM cargos WHERE id_cargo='$id_cargo'";
        if (mysqli_query($conexion, $sql)) {
            $message = "Cargo eliminado exitosamente.";
            $message_type = "success";
        } else {
            $message = "Error al eliminar el cargo: " . mysqli_error($conexion);
            $message_type = "error";
        }
    }
}

// Obtener todos los cargos ordenados
$result = mysqli_query($conexion, "SELECT * FROM cargos ORDER BY cargo ASC");

// Contar total de cargos
$total_cargos = mysqli_num_rows($result);
mysqli_data_seek($result, 0); // Resetear puntero
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Administración de Cargos | 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;
        }
        
        /* Dashboard Cards */
        .dashboard-cards {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .dashboard-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
            transition: transform 0.3s, box-shadow 0.3s;
            border: 1px solid var(--border-color);
        }
        
        .dashboard-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        }
        
        .card-icon {
            width: 60px;
            height: 60px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 15px;
            font-size: 1.5rem;
        }
        
        .icon-primary {
            background-color: rgba(26, 60, 139, 0.1);
            color: var(--primary-color);
        }
        
        .icon-success {
            background-color: rgba(76, 175, 80, 0.1);
            color: var(--secondary-color);
        }
        
        .card-value {
            font-size: 2rem;
            font-weight: 700;
            margin: 5px 0;
        }
        
        .card-label {
            font-size: 0.9rem;
            color: #666;
        }
        
        /* Form Container */
        .form-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 Grid */
        .form-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 25px;
            margin-bottom: 20px;
        }
        
        .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 {
            padding: 12px 15px;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            font-size: 1rem;
            transition: all 0.3s;
        }
        
        .form-control:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(26, 60, 139, 0.1);
        }
        
        .currency-input {
            position: relative;
        }
        
        .currency-symbol {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #666;
            font-weight: 600;
        }
        
        .currency-input .form-control {
            padding-left: 30px;
        }
        
        /* Form Actions */
        .form-actions {
            display: flex;
            gap: 15px;
            padding-top: 20px;
            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-warning {
            background: linear-gradient(to right, var(--accent-color), #ffb74d);
            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-warning:hover {
            background: linear-gradient(to right, #e68900, var(--accent-color));
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 152, 0, 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);
        }
        
        /* Table Container */
        .table-container {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            margin-top: 30px;
            border: 1px solid var(--border-color);
        }
        
        .table-header {
            padding: 20px 25px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .table-header h3 {
            font-size: 1.2rem;
            font-weight: 600;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .table-header h3 i {
            color: var(--primary-color);
        }
        
        .table-responsive {
            overflow-x: auto;
        }
        
        .data-table {
            width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        }
        
        .data-table thead th {
            background-color: #f8fafc;
            border: none;
            padding: 15px 20px;
            font-weight: 600;
            color: var(--dark-color);
            border-bottom: 2px solid var(--border-color);
            white-space: nowrap;
        }
        
        .data-table tbody tr {
            transition: background-color 0.2s;
        }
        
        .data-table tbody tr:hover {
            background-color: #f8fafc;
        }
        
        .data-table tbody td {
            padding: 15px 20px;
            border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }
        
        .salary-cell {
            font-weight: 600;
            color: var(--primary-color);
        }
        
        .action-buttons {
            display: flex;
            gap: 8px;
        }
        
        .btn-icon {
            width: 36px;
            height: 36px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: none;
            transition: all 0.2s;
            text-decoration: none;
        }
        
        .btn-edit {
            background-color: rgba(255, 193, 7, 0.1);
            color: #ffc107;
        }
        
        .btn-edit:hover {
            background-color: #ffc107;
            color: white;
        }
        
        .btn-delete {
            background-color: rgba(220, 53, 69, 0.1);
            color: #dc3545;
        }
        
        .btn-delete:hover {
            background-color: #dc3545;
            color: white;
        }
        
        /* Alert Messages */
        .alert-message {
            padding: 15px 20px;
            border-radius: 8px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            gap: 12px;
            animation: fadeIn 0.5s ease;
        }
        
        .alert-success {
            background: rgba(40, 167, 69, 0.1);
            border: 1px solid rgba(40, 167, 69, 0.2);
            color: #155724;
        }
        
        .alert-error {
            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;
            }
        }
        
        @media (max-width: 768px) {
            .top-navbar {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
                padding: 15px 20px;
            }
            
            .content-wrapper {
                padding: 20px 15px;
            }
            
            .dashboard-cards {
                grid-template-columns: 1fr;
            }
            
            .form-grid {
                grid-template-columns: 1fr;
            }
            
            .form-actions {
                flex-direction: column;
            }
            
            .btn-primary, .btn-warning, .btn-secondary {
                width: 100%;
                justify-content: center;
            }
            
            .action-buttons {
                flex-wrap: wrap;
                justify-content: center;
            }
        }
        
        /* Custom scrollbar */
        ::-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 active">
                        <i class="fas fa-briefcase"></i>
                        <span>Cargos</span>
                    </a>
                    <a href="carga_familiar.php" class="menu-item">
                        <i class="fas fa-family"></i>
                        <span>Carga Familiar</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>Administración de Cargos</h1>
                    <p>Gestión de posiciones y salarios del personal. El salario del cargo puede quedar en VES o en USD indexado a Bs en la corrida.</p>
                </div>
            </header>
            
            <!-- Content Area -->
            <div class="content-wrapper">
                <!-- Dashboard Cards -->
                <div class="dashboard-cards">
                    <div class="dashboard-card">
                        <div class="card-icon icon-primary">
                            <i class="fas fa-briefcase"></i>
                        </div>
                        <div class="card-value"><?php echo $total_cargos; ?></div>
                        <div class="card-label">Total de Cargos</div>
                    </div>
                    
                    <div class="dashboard-card">
                        <div class="card-icon icon-success">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <div class="card-value"><?php echo $total_cargos; ?></div>
                        <div class="card-label">Cargos Activos</div>
                    </div>
                    
                    <div class="dashboard-card">
                        <div class="card-icon icon-primary">
                            <i class="fas fa-dollar-sign"></i>
                        </div>
                        <div class="card-value">
                            <?php 
                            // Calcular salario promedio
                            $avg_salary = 0;
                            if ($total_cargos > 0) {
                                $salary_sum = 0;
                                mysqli_data_seek($result, 0);
                                while ($row = mysqli_fetch_assoc($result)) {
                                    $salary_sum += $row['salario'];
                                }
                                $avg_salary = number_format($salary_sum / $total_cargos, 2, ',', '.');
                                mysqli_data_seek($result, 0); // Resetear puntero
                            }
                            echo $avg_salary ? "Bs. $avg_salary" : "Bs. 0,00";
                            ?>
                        </div>
                        <div class="card-label">Salario Promedio</div>
                    </div>
                    
                    <div class="dashboard-card">
                        <div class="card-icon icon-primary">
                            <i class="fas fa-calendar-alt"></i>
                        </div>
                        <div class="card-value"><?php echo date('d/m/Y'); ?></div>
                        <div class="card-label">Fecha Actual</div>
                    </div>
                </div>
                
                <!-- Alert Messages -->
                <?php if ($message): ?>
                    <div class="alert-message <?php echo $message_type == 'success' ? 'alert-success' : 'alert-error'; ?>">
                        <i class="fas <?php echo $message_type == 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'; ?>"></i>
                        <div>
                            <strong><?php echo $message_type == 'success' ? '¡Éxito!' : 'Error:'; ?></strong>
                            <?php echo $message; ?>
                        </div>
                    </div>
                <?php endif; ?>
                
                <!-- Form Container -->
                <div class="form-container">
                    <div class="form-header">
                        <h2>
                            <i class="fas <?php echo $edit_state ? 'fa-edit' : 'fa-plus-circle'; ?>"></i>
                            <?php echo $edit_state ? 'Editar Cargo' : 'Nuevo Cargo'; ?>
                        </h2>
                        <p>
                            <?php echo $edit_state ? 
                                'Modifique la información del cargo seleccionado' : 
                                'Complete los campos para registrar un nuevo cargo'; ?>
                        </p>
                    </div>
                    
                    <div class="form-body">
                        <form action="cargos.php" method="post" id="cargoForm">
                            <input type="hidden" name="id_cargo" value="<?php echo htmlspecialchars($id_cargo); ?>">
                            
                            <div class="form-grid">
                                <div class="form-group">
                                    <label for="cargo" class="form-label required">
                                        <i class="fas fa-user-tie"></i> Nombre del Cargo
                                    </label>
                                    <input type="text" class="form-control" name="cargo" id="cargo" required 
                                           value="<?php echo htmlspecialchars($cargo); ?>" 
                                           placeholder="Ej: Gerente de Ventas, Asistente Administrativo">
                                </div>
                                
                                <div class="form-group">
                                    <label for="salario" class="form-label required">
                                        <i class="fas fa-dollar-sign"></i> Salario base del cargo
                                    </label>
                                    <input type="number" class="form-control" name="salario" id="salario" required 
                                           value="<?php echo htmlspecialchars($salario); ?>" 
                                           placeholder="0.00" step="0.01" min="0">
                                    <small class="text-muted mt-1" id="salarioHelp">Define el monto base del cargo. Si la moneda es USD, la nómina lo convertirá a Bs usando la tasa BCV de la corrida.</small>
                                </div>

                                <div class="form-group">
                                    <label for="moneda_salario" class="form-label">Moneda del salario del cargo</label>
                                    <select class="form-control" name="moneda_salario" id="moneda_salario">
                                        <option value="VES" <?php echo ($moneda_salario === 'VES') ? 'selected' : ''; ?>>VES · Monto fijo en bolívares</option>
                                        <option value="USD" <?php echo ($moneda_salario === 'USD') ? 'selected' : ''; ?>>USD · Indexado a Bs al calcular la nómina</option>
                                    </select>
                                    <small class="text-muted mt-1" id="monedaCargoHint">Al heredar este salario, el trabajador tomará tanto el monto como la moneda definida en el cargo.</small>
                                </div>

                                <div class="form-group">
                                    <label for="bono_extra_usd_mensual" class="form-label">Bono Extra USD (Mensual)</label>
                                    <input type="number" class="form-control" name="bono_extra_usd_mensual" id="bono_extra_usd_mensual"
                                           value="<?php echo htmlspecialchars($bono_extra_usd_mensual); ?>"
                                           placeholder="0.00" step="0.01" min="0">
                                    <small class="text-muted mt-1">Monto mensual en USD según cargo. Se paga por quincena y se convierte a Bs usando la tasa BCV de la corrida.</small>
                                </div>
                            </div>
                            
                            <div class="form-actions">
                                <a href="index.php" class="btn-secondary">
                                    <i class="fas fa-arrow-left"></i> Volver al Dashboard
                                </a>
                                
                                <div>
                                    <?php if ($edit_state): ?>
                                        <button type="submit" name="update" class="btn-warning">
                                            <i class="fas fa-save"></i> Actualizar Cargo
                                        </button>
                                        <a href="cargos.php" class="btn-secondary">
                                            <i class="fas fa-times"></i> Cancelar
                                        </a>
                                    <?php else: ?>
                                        <button type="submit" name="save" class="btn-primary">
                                            <i class="fas fa-plus-circle"></i> Crear Cargo
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Table Container -->
                <div class="table-container">
                    <div class="table-header">
                        <h3><i class="fas fa-list"></i> Listado de Cargos</h3>
                        <div class="table-info">
                            <span class="text-muted">Mostrando <?php echo $total_cargos; ?> cargos</span>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <?php if ($total_cargos > 0): ?>
                            <table class="data-table">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>Cargo</th>
                                        <th>Salario base del cargo</th>
                                        <th>Moneda</th>
                                        <th>Bono extra USD (mensual)</th>
                                        <th>Acciones</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while ($row = mysqli_fetch_assoc($result)): ?>
                                        <tr>
                                            <td><?php echo $row['id_cargo']; ?></td>
                                            <td>
                                                <strong><?php echo htmlspecialchars($row['cargo']); ?></strong>
                                            </td>
                                            <td class="salary-cell">
                                                <?php $monCargo = strtoupper((string)($row['moneda_salario'] ?? 'VES')); ?>
                                                <?php echo $monCargo === 'USD' ? 'USD ' : 'Bs. '; ?><?php echo number_format((float)$row['salario'], 2, ',', '.'); ?>
                                            </td>
                                            <td>
                                                <?php echo $monCargo === 'USD' ? 'USD indexado a Bs' : 'VES fijo'; ?>
                                            </td>
                                            <td class="salary-cell">
                                                $ <?php echo number_format((float)($row['bono_extra_usd_mensual'] ?? 0), 2, ',', '.'); ?>
                                            </td>
                                            <td>
                                                <div class="action-buttons">
                                                    <a href="cargos.php?edit=<?php echo $row['id_cargo']; ?>" 
                                                       class="btn-icon btn-edit" title="Editar">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="cargos.php?del=<?php echo $row['id_cargo']; ?>" 
                                                       class="btn-icon btn-delete" title="Eliminar"
                                                       onclick="return confirm('¿Está seguro de eliminar este cargo?');">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        <?php else: ?>
                            <div class="empty-state">
                                <i class="fas fa-briefcase"></i>
                                <h3>No hay cargos registrados</h3>
                                <p>Comience creando el primer cargo utilizando el formulario anterior</p>
                            </div>
                        <?php endif; ?>
                    </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() {
            const monedaCargoSelect = document.getElementById('moneda_salario');
            const salarioHelp = document.getElementById('salarioHelp');
            function refreshCargoCurrencyHelp(){
                if (!monedaCargoSelect || !salarioHelp) return;
                if (monedaCargoSelect.value === 'USD') {
                    salarioHelp.textContent = 'Define el monto base del cargo en USD. La nómina lo convertirá a Bs usando la tasa BCV guardada en la corrida.';
                } else {
                    salarioHelp.textContent = 'Define el monto base del cargo en bolívares. Se aplicará como VES fijo salvo que el trabajador tenga salario propio.';
                }
            }
            if (monedaCargoSelect) {
                monedaCargoSelect.addEventListener('change', refreshCargoCurrencyHelp);
                refreshCargoCurrencyHelp();
            }

            // Auto-format salario input
            const salarioInput = document.getElementById('salario');
            
            if (salarioInput) {
                salarioInput.addEventListener('blur', function() {
                    if (this.value) {
                        const value = parseFloat(this.value);
                        if (!isNaN(value)) {
                            this.value = value.toFixed(2);
                        }
                    }
                });
                
                salarioInput.addEventListener('input', function() {
                    // Remove any non-numeric characters except decimal point
                    this.value = this.value.replace(/[^\d.]/g, '');
                    
                    // Ensure only one decimal point
                    const parts = this.value.split('.');
                    if (parts.length > 2) {
                        this.value = parts[0] + '.' + parts.slice(1).join('');
                    }
                    
                    // Limit to 2 decimal places
                    if (parts.length > 1 && parts[1].length > 2) {
                        this.value = parts[0] + '.' + parts[1].substring(0, 2);
                    }
                });
            }
            
            // Form validation
            const cargoForm = document.getElementById('cargoForm');
            
            if (cargoForm) {
                cargoForm.addEventListener('submit', function(e) {
                    const cargoInput = document.getElementById('cargo');
                    const salarioInput = document.getElementById('salario');
                    let isValid = true;
                    
                    // Validate cargo
                    if (!cargoInput.value.trim()) {
                        isValid = false;
                        cargoInput.style.borderColor = '#dc3545';
                        setTimeout(() => {
                            cargoInput.style.borderColor = '';
                        }, 2000);
                    }
                    
                    // Validate salario
                    if (!salarioInput.value || parseFloat(salarioInput.value) <= 0) {
                        isValid = false;
                        salarioInput.style.borderColor = '#dc3545';
                        setTimeout(() => {
                            salarioInput.style.borderColor = '';
                        }, 2000);
                    }
                    
                    if (!isValid) {
                        e.preventDefault();
                        alert('Por favor complete todos los campos correctamente.');
                    }
                });
            }
            
            // Auto-focus on cargo input if not editing
            const isEditing = <?php echo $edit_state ? 'true' : 'false'; ?>;
            if (!isEditing) {
                setTimeout(() => {
                    document.getElementById('cargo')?.focus();
                }, 100);
            }
            
            // Smooth transitions
            document.body.style.opacity = '0';
            setTimeout(() => {
                document.body.style.transition = 'opacity 0.3s';
                document.body.style.opacity = '1';
            }, 50);
            
            // Highlight edited row
            const editId = <?php echo $edit_state ? $id_cargo : 'null'; ?>;
            if (editId) {
                setTimeout(() => {
                    const rows = document.querySelectorAll('.data-table tbody tr');
                    rows.forEach(row => {
                        const idCell = row.querySelector('td:first-child');
                        if (idCell && idCell.textContent.trim() == editId) {
                            row.style.backgroundColor = 'rgba(255, 193, 7, 0.1)';
                            row.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    });
                }, 500);
            }
        });
    </script>
</body>
</html>