<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

include 'conexion.php';
session_start();

// Verificar si la sesión del usuario está activa
if (!isset($_SESSION['id_usuario'])) {
    die("Acceso no autorizado.");
}

$id_usuario = $_SESSION['id_usuario'];
$usuario = $conexion->query("SELECT * FROM usuarios_sistema WHERE id_usuario  = $id_usuario")->fetch_assoc();

// Obtener rol y empresa
$rol = $usuario['rol'];
$id_empresa_usuario = $usuario['id_empresa'];

// Guardar subcontrata
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id_empresa = ($rol === 'admin_general') ? $_POST['id_empresa'] : $id_empresa_usuario;
    $nombre = $_POST['nombre_subcontrata'];
    $ruc = $_POST['ruc_subcontrata'];
    $direccion = $_POST['direccion_subcontrata'];
    $telefono = $_POST['telefono_subcontrata'];
    $correo = $_POST['correo_subcontrata'];

    $stmt = $conexion->prepare("INSERT INTO subcontratas (id_empresa, nombre_subcontrata, ruc_subcontrata, direccion_subcontrata, telefono_subcontrata, correo_subcontrata) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("isssss", $id_empresa, $nombre, $ruc, $direccion, $telefono, $correo);
    $stmt->execute();
}
?>

 <!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>nn</title>
  <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/1.0.4/tailwind.min.css'><link rel="stylesheet" href="./style.css">

</head>
<body>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" rel="stylesheet">

<!-- partial:index.partial.html -->
<div class="relative bg-gray-100 min-h-screen flex" id="app">
 <?php include 'menu.php' ?>

<div class="w-full" style="margin-left: 50px;">
     <?php include 'user.php' ?>
   <div class="px-16 bg-header py-6">
    <!-- EMPRESAS -->
    <div class="card filter-menu bg-gray-100 rounded-2xl shadow-md p-4 mb-6">
        
    </div>

   
</div>

  <header class="h-16  bg-header w-full  rounded-bl-full">
</header>
    <app-klatsch v-bind:klatsch="today"></app-klatsch> 



    <div class="px-16 pt-8 content">
      <div class="h-2 border-gray-200 border-t-2 w-2/3"></div>
  
  </div>
      <div class="klatsch-grid">
    <app-klatsch v-for="kl in upcoming" v-bind:klatsch="kl"></app-klatsch>
       <!-- Sección de Tabla -->
  
    </div>
<div class="mx-4 py-3 px-8 bg-white shadow-lg ml-16 rounded-lg" style="border-left: 8px solid #572073;">
    <div class="w-full"> <div class="font-extrabold text-xl text-gray-900 mb-4">Lista Subcontrata</div>
        <div class="flex justify-between items-center mb-4">

            <!-- Buscador -->
            <div class="flex items-center">
                <input type="text" placeholder="Buscar..." id="searchSerie" class="px-4 py-2 border border-gray-300 rounded-lg text-sm w-64 focus:outline-none focus:ring-2 focus:ring-indigo-500">
            </div>
            
            <!-- Botones Exportar con íconos -->
            <div class="flex items-center">
                <!-- Botón Exportar Excel -->
                <a href="exportar_excel_seriado.php"  class="flex items-center bg-green-500 text-white py-2 px-6 rounded-lg hover:bg-green-700 focus:outline-none mr-2">
                    <!-- Ícono de Excel -->
                    <i class="fas fa-file-excel h-4 w-4 mr-3"></i>
                    Exportar Excel
                </a>

    <!-- Botón para abrir el modal -->
        <button onclick="toggleModal()" class="bg-blue-600 text-white py-2 px-6 rounded-lg hover:bg-blue-500 transition flex items-center">Registrar Subcontrata</button>

            </div>
        </div>

 


 <table class="min-w-full border border-gray-300 text-sm">
            <thead class="bg-gray-200">
                <tr>
                    <th class="px-4 py-2 border">Empresa</th>
                    <th class="px-4 py-2 border">Nombre</th>
                    <th class="px-4 py-2 border">RUC</th>
                    <th class="px-4 py-2 border">Teléfono</th>
                    <th class="px-4 py-2 border">Correo</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $filtro = ($rol == 'admin_general') ? '' : "WHERE s.id_empresa = $id_empresa_usuario";
                $subcontratas = $conexion->query("
                    SELECT s.*, e.nombre AS nombre_empresa 
                    FROM subcontratas s 
                    LEFT JOIN empresas e ON s.id_empresa = e.id_empresa 
                    $filtro
                ");

                while ($sub = $subcontratas->fetch_assoc()):
                ?>
                    <tr class="border-b">
                        <td class="px-4 py-2 border"><?= htmlspecialchars($sub['nombre_empresa']) ?></td>
                        <td class="px-4 py-2 border"><?= htmlspecialchars($sub['nombre_subcontrata']) ?></td>
                        <td class="px-4 py-2 border"><?= htmlspecialchars($sub['ruc_subcontrata']) ?></td>
                        <td class="px-4 py-2 border"><?= htmlspecialchars($sub['telefono_subcontrata']) ?></td>
                        <td class="px-4 py-2 border"><?= htmlspecialchars($sub['correo_subcontrata']) ?></td>
                    </tr>
                <?php endwhile; ?>
            </tbody>
        </table>

    </div>
</div>


  </div>

</div> 

    </div>
</body>
</html>

    <script src="https://cdn.tailwindcss.com"></script>
    <script>
        function toggleModal() {
            document.getElementById('modal_subcontrata').classList.toggle('hidden');
        }
    </script>

    <!-- Modal flotante -->
    <div id="modal_subcontrata" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center hidden z-50">
        <div class="bg-white rounded-lg p-6 w-full max-w-xl shadow-lg relative">
            <h2 class="text-xl font-bold mb-4">Registrar Subcontrata</h2>

            <!-- Botón de cierre -->
            <button onclick="toggleModal()" class="absolute top-2 right-3 text-gray-500 hover:text-red-600 text-lg">&times;</button>

            <!-- Formulario dentro del modal -->
            <form method="POST" class="space-y-4">
                <?php if ($rol == 'admin_general'): ?>
                    <div>
                        <label class="block text-sm font-medium text-gray-700">Empresa:</label>
                        <select name="id_empresa" class="w-full border border-gray-300 rounded px-3 py-2" required>
                            <option value="">Seleccione una empresa</option>
                            <?php
                            $empresas = $conexion->query("SELECT id_empresa, nombre FROM empresas");
                            while ($empresa = $empresas->fetch_assoc()):
                            ?>
                                <option value="<?= htmlspecialchars($empresa['id_empresa']) ?>"><?= htmlspecialchars($empresa['nombre']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                <?php else: ?>
                    <p class="text-gray-700 text-sm">Empresa:
                        <strong>
                            <?php
                            $empresa = $conexion->query("SELECT nombre FROM empresas WHERE id_empresa = $id_empresa_usuario")->fetch_assoc();
                            echo htmlspecialchars($empresa['nombre'] ?? 'Empresa no encontrada');
                            ?>
                        </strong>
                    </p>
                <?php endif; ?>

                <div>
                    <label class="block text-sm font-medium text-gray-700">Nombre de la Subcontrata:</label>
                    <input type="text" name="nombre_subcontrata" class="w-full border border-gray-300 rounded px-3 py-2" required>
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700">RUC:</label>
                    <input type="text" name="ruc_subcontrata" class="w-full border border-gray-300 rounded px-3 py-2">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700">Dirección:</label>
                    <input type="text" name="direccion_subcontrata" class="w-full border border-gray-300 rounded px-3 py-2">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700">Teléfono:</label>
                    <input type="text" name="telefono_subcontrata" class="w-full border border-gray-300 rounded px-3 py-2">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700">Correo:</label>
                    <input type="email" name="correo_subcontrata" class="w-full border border-gray-300 rounded px-3 py-2">
                </div>

                <div class="text-right">
                    <button type="submit" class="bg-green-600 text-white px-5 py-2 rounded hover:bg-green-700">Guardar</button>
                </div>
            </form>
        </div>
    </div>

