<?php
// File: /fuelpos/admin/empresa.php
require __DIR__ . '/../init.php';
require_login();

if (!function_exists('esc')) {
    function esc($s){ return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); }
}

$pdo = pdo();
$msg = '';
$err = '';

// ========== ACCIONES ==========

// CREAR/EDITAR
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    if ($action === 'save') {
        $id = (int)($_POST['id'] ?? 0);
        $codigo = trim($_POST['codigo'] ?? '');
        $nombre = trim($_POST['nombre'] ?? '');
        $direccion = trim($_POST['direccion'] ?? '');
        $telefono = trim($_POST['telefono'] ?? '');
        $contacto = trim($_POST['contacto'] ?? '');
        $centro_costo = trim($_POST['centro_costo'] ?? '');
        
        if (empty($codigo) || empty($nombre)) {
            $err = 'Código y Nombre son obligatorios.';
        } else {
            try {
                if ($id > 0) {
                    // EDITAR
                    $stmt = $pdo->prepare("
                        UPDATE empresa 
                        SET codigo=?, nombre=?, direccion=?, telefono=?, contacto=?, centro_costo=?, updated_at=NOW()
                        WHERE id=?
                    ");
                    $stmt->execute([$codigo, $nombre, $direccion, $telefono, $contacto, $centro_costo, $id]);
                    $msg = 'Empresa actualizada correctamente.';
                } else {
                    // CREAR
                    $stmt = $pdo->prepare("
                        INSERT INTO empresa (codigo, nombre, direccion, telefono, contacto, centro_costo) 
                        VALUES (?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$codigo, $nombre, $direccion, $telefono, $contacto, $centro_costo]);
                    $msg = 'Empresa creada correctamente.';
                }
            } catch (PDOException $e) {
                if (strpos($e->getMessage(), 'Duplicate entry') !== false) {
                    $err = 'El código ya existe. Por favor use otro código.';
                } else {
                    $err = 'Error al guardar: ' . $e->getMessage();
                }
            }
        }
    }
    
    // ELIMINAR
    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0) {
            try {
                $stmt = $pdo->prepare("DELETE FROM empresa WHERE id=?");
                $stmt->execute([$id]);
                $msg = 'Empresa eliminada correctamente.';
            } catch (PDOException $e) {
                $err = 'Error al eliminar: ' . $e->getMessage();
            }
        }
    }
}

// ========== OBTENER DATOS ==========
$empresas = [];
try {
    $stmt = $pdo->query("SELECT * FROM empresa ORDER BY nombre ASC");
    $empresas = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $err = 'Error al cargar empresas: ' . $e->getMessage();
}

// Datos para edición
$editData = null;
if (isset($_GET['edit'])) {
    $editId = (int)$_GET['edit'];
    try {
        $stmt = $pdo->prepare("SELECT * FROM empresa WHERE id=? LIMIT 1");
        $stmt->execute([$editId]);
        $editData = $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (PDOException $e) {
        $err = 'Error al cargar datos: ' . $e->getMessage();
    }
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Empresas - SolutionPOS</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
  <style>
    body {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      padding: 20px 0;
    }
    
    .main-container {
      background: white;
      border-radius: 20px;
      padding: 30px;
      box-shadow: 0 20px 60px rgba(0,0,0,0.3);
      max-width: 1200px;
      margin: 0 auto;
    }
    
    .page-header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 25px;
      border-radius: 15px;
      margin-bottom: 30px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    .page-header h3 {
      margin: 0;
      font-weight: 700;
      font-size: 26px;
    }
    
    .btn {
      border-radius: 10px;
      padding: 10px 20px;
      font-weight: 600;
      transition: all 0.3s ease;
    }
    
    .btn-primary {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
    }
    
    .btn-primary:hover {
      background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
      transform: translateY(-2px);
    }
    
    .table {
      background: white;
      border-radius: 10px;
      overflow: hidden;
    }
    
    .table thead {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
    }
    
    .table tbody tr:hover {
      background: #f8f9fa;
    }
    
    .form-card {
      background: #f8f9fa;
      border-radius: 15px;
      padding: 25px;
      margin-bottom: 30px;
      border: 2px solid #e9ecef;
    }
    
    .form-card h5 {
      color: #667eea;
      font-weight: 700;
      margin-bottom: 20px;
    }
    
    .alert {
      border-radius: 10px;
      border: none;
    }
  </style>
</head>
<body>

<div class="container">
  <div class="main-container">
    
    <!-- HEADER -->
    <div class="page-header">
      <div>
        <h3><i class="bi bi-building"></i> Gestión de Empresas</h3>
        <small>Mantenimiento de empresas y clientes corporativos</small>
      </div>
      <a href="<?= site('admin/index.php') ?>" class="btn btn-light">
        <i class="bi bi-arrow-left"></i> Volver
      </a>
    </div>

    <!-- MENSAJES -->
    <?php if ($msg): ?>
      <div class="alert alert-success alert-dismissible fade show">
        <i class="bi bi-check-circle-fill"></i> <?= esc($msg) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
    <?php endif; ?>
    
    <?php if ($err): ?>
      <div class="alert alert-danger alert-dismissible fade show">
        <i class="bi bi-exclamation-triangle-fill"></i> <?= esc($err) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
      </div>
    <?php endif; ?>

    <!-- FORMULARIO -->
    <div class="form-card">
      <h5>
        <i class="bi bi-<?= $editData ? 'pencil-square' : 'plus-circle' ?>"></i>
        <?= $editData ? 'Editar Empresa' : 'Nueva Empresa' ?>
      </h5>
      
      <form method="post">
        <input type="hidden" name="action" value="save">
        <input type="hidden" name="id" value="<?= $editData['id'] ?? 0 ?>">
        
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">Código <span class="text-danger">*</span></label>
            <input type="text" class="form-control" name="codigo" 
                   value="<?= esc($editData['codigo'] ?? '') ?>" required>
          </div>
          
          <div class="col-md-8">
            <label class="form-label">Nombre <span class="text-danger">*</span></label>
            <input type="text" class="form-control" name="nombre" 
                   value="<?= esc($editData['nombre'] ?? '') ?>" required>
          </div>
          
          <div class="col-md-12">
            <label class="form-label">Dirección</label>
            <textarea class="form-control" name="direccion" rows="2"><?= esc($editData['direccion'] ?? '') ?></textarea>
          </div>
          
          <div class="col-md-4">
            <label class="form-label">Teléfono</label>
            <input type="text" class="form-control" name="telefono" 
                   value="<?= esc($editData['telefono'] ?? '') ?>">
          </div>
          
          <div class="col-md-4">
            <label class="form-label">Contacto</label>
            <input type="text" class="form-control" name="contacto" 
                   value="<?= esc($editData['contacto'] ?? '') ?>">
          </div>
          
          <div class="col-md-4">
            <label class="form-label">Centro de Costo</label>
            <input type="text" class="form-control" name="centro_costo" 
                   value="<?= esc($editData['centro_costo'] ?? '') ?>">
          </div>
        </div>
        
        <div class="mt-4 d-flex gap-2">
          <button type="submit" class="btn btn-primary">
            <i class="bi bi-save"></i> <?= $editData ? 'Actualizar' : 'Guardar' ?>
          </button>
          
          <?php if ($editData): ?>
            <a href="<?= site('admin/empresa.php') ?>" class="btn btn-secondary">
              <i class="bi bi-x-circle"></i> Cancelar
            </a>
          <?php endif; ?>
        </div>
      </form>
    </div>

    <!-- TABLA -->
    <div class="table-responsive">
      <table class="table table-hover align-middle">
        <thead>
          <tr>
            <th>Código</th>
            <th>Nombre</th>
            <th>Dirección</th>
            <th>Teléfono</th>
            <th>Contacto</th>
            <th>Centro Costo</th>
            <th style="width: 150px;">Acciones</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($empresas)): ?>
            <tr>
              <td colspan="7" class="text-center text-muted py-4">
                <i class="bi bi-inbox" style="font-size: 48px;"></i>
                <p class="mb-0 mt-2">No hay empresas registradas</p>
              </td>
            </tr>
          <?php else: ?>
            <?php foreach ($empresas as $emp): ?>
              <tr>
                <td><strong><?= esc($emp['codigo']) ?></strong></td>
                <td><?= esc($emp['nombre']) ?></td>
                <td><?= esc($emp['direccion']) ?></td>
                <td><?= esc($emp['telefono']) ?></td>
                <td><?= esc($emp['contacto']) ?></td>
                <td><?= esc($emp['centro_costo']) ?></td>
                <td>
                  <a href="?edit=<?= $emp['id'] ?>" class="btn btn-sm btn-warning" title="Editar">
                    <i class="bi bi-pencil"></i>
                  </a>
                  
                  <button type="button" class="btn btn-sm btn-danger" 
                          onclick="confirmDelete(<?= $emp['id'] ?>, '<?= esc($emp['nombre']) ?>')" 
                          title="Eliminar">
                    <i class="bi bi-trash"></i>
                  </button>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>

  </div>
</div>

<!-- Modal de confirmación -->
<div class="modal fade" id="deleteModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title"><i class="bi bi-exclamation-triangle-fill"></i> Confirmar Eliminación</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <p>¿Está seguro que desea eliminar la empresa <strong id="deleteCompanyName"></strong>?</p>
        <p class="text-danger mb-0"><small>Esta acción no se puede deshacer.</small></p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
        <form method="post" id="deleteForm">
          <input type="hidden" name="action" value="delete">
          <input type="hidden" name="id" id="deleteId">
          <button type="submit" class="btn btn-danger">
            <i class="bi bi-trash"></i> Eliminar
          </button>
        </form>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
function confirmDelete(id, name) {
  document.getElementById('deleteId').value = id;
  document.getElementById('deleteCompanyName').textContent = name;
  new bootstrap.Modal(document.getElementById('deleteModal')).show();
}
</script>

</body>
</html>