<?php

session_start();
include("../includes/auth.php");
include("../config/db.php");

if(
    !isset($_SESSION['can_manage_products']) ||
    intval($_SESSION['can_manage_products']) !== 1
){
    if(!isset($_SESSION['can_manage_users']) || intval($_SESSION['can_manage_users']) !== 1){
        header("Location: /pages/dashboard.php");
        exit;
    }
}

$success = "";
$error   = "";

$product_types = [
    'luz'        => '⚡ Luz',
    'gas'        => '🔥 Gas',
    'luz_gas'    => '⚡🔥 Luz + Gas',
    'telecom'    => '📡 Telecom',
    'alarma'     => '🔔 Alarma',
    'seguro'     => '🛡️ Seguro',
    'financiero' => '💳 Financiero',
    'otro'       => '📦 Otro',
];

/*
|--------------------------------------------------------------------------
| ACCIONES POST
|--------------------------------------------------------------------------
*/

if($_SERVER['REQUEST_METHOD'] === 'POST'){

    $action = trim($_POST['action'] ?? '');

    if($action === 'save_product'){

        $id           = intval($_POST['product_id'] ?? 0);
        $campaign_id  = intval($_POST['campaign_id'] ?? 0) ?: null;
        $company      = trim($_POST['company_name'] ?? '');
        $name         = trim($_POST['product_name'] ?? '');
        $type         = trim($_POST['product_type'] ?? 'luz');
        $atr          = trim($_POST['tarifa_atr']   ?? '');
        $kwh          = floatval(str_replace(',','.',$_POST['precio_kwh']   ?? 0));
        $kwh2         = floatval(str_replace(',','.',$_POST['precio_kwh_p2'] ?? 0));
        $kwh3         = floatval(str_replace(',','.',$_POST['precio_kwh_p3'] ?? 0));
        $pot1         = floatval(str_replace(',','.',$_POST['precio_potencia_p1'] ?? 0));
        $pot2         = floatval(str_replace(',','.',$_POST['precio_potencia_p2'] ?? 0));
        $fijo         = floatval(str_replace(',','.',$_POST['termino_fijo'] ?? 0));
        $dto          = floatval(str_replace(',','.',$_POST['descuento']    ?? 0));
        $dto_pot      = floatval(str_replace(',','.',$_POST['descuento_potencia'] ?? 0));
        $perm         = isset($_POST['permanencia']) ? 1 : 0;
        $meses        = intval($_POST['meses_permanencia'] ?? 12);
        $promo        = trim($_POST['promo']        ?? '');
        $sva          = trim($_POST['sva']          ?? '');
        $precio_sva   = floatval(str_replace(',','.',$_POST['precio_sva'] ?? 0));
        $desc         = trim($_POST['descripcion']  ?? '');
        $active       = isset($_POST['is_active']) ? 1 : 0;

        // Subir logo de compañía
        if(isset($_FILES['company_logo']) && $_FILES['company_logo']['error'] === 0){
            $ext  = pathinfo($_FILES['company_logo']['name'], PATHINFO_EXTENSION);
            $fname = 'logo_'.strtolower(preg_replace('/[^a-z0-9]/i','_',$company)).'.'.$ext;
            $dest  = __DIR__.'/../uploads/branding/'.$fname;
            if(move_uploaded_file($_FILES['company_logo']['tmp_name'], $dest)){
                $logo_path = '/uploads/branding/'.$fname;
                $co = mysqli_real_escape_string($conn, $company);
                $conn->query("INSERT INTO company_logos (company_name, logo_path) VALUES ('$co','$logo_path')
                              ON DUPLICATE KEY UPDATE logo_path='$logo_path'");
            }
        }

        $cn = mysqli_real_escape_string($conn, $company);
        $nm = mysqli_real_escape_string($conn, $name);
        $at = mysqli_real_escape_string($conn, $atr);
        $pr = mysqli_real_escape_string($conn, $promo);
        $sv = mysqli_real_escape_string($conn, $sva);
        $de = mysqli_real_escape_string($conn, $desc);
        $ci = $campaign_id ? "'$campaign_id'" : "NULL";

        if($id > 0){
            $conn->query("
            UPDATE products SET
                campaign_id='$campaign_id', company_name='$cn', product_name='$nm',
                product_type='$type', tarifa_atr='$at',
                precio_kwh='$kwh', precio_kwh_p2='$kwh2', precio_kwh_p3='$kwh3',
                precio_potencia_p1='$pot1', precio_potencia_p2='$pot2',
                termino_fijo='$fijo', descuento='$dto', descuento_potencia='$dto_pot',
                permanencia='$perm', meses_permanencia='$meses',
                promo='$pr', sva='$sv', precio_sva='$precio_sva',
                descripcion='$de', is_active='$active'
            WHERE id='$id'
            ");
            $success = "Producto actualizado correctamente.";
        } else {
            $conn->query("
            INSERT INTO products
                (campaign_id, company_name, product_name, product_type, tarifa_atr,
                 precio_kwh, precio_kwh_p2, precio_kwh_p3,
                 precio_potencia_p1, precio_potencia_p2,
                 termino_fijo, descuento, descuento_potencia,
                 permanencia, meses_permanencia,
                 promo, sva, precio_sva, descripcion, is_active)
            VALUES
                ($ci, '$cn', '$nm', '$type', '$at',
                 '$kwh', '$kwh2', '$kwh3',
                 '$pot1', '$pot2',
                 '$fijo', '$dto', '$dto_pot',
                 '$perm', '$meses',
                 '$pr', '$sv', '$precio_sva', '$de', '$active')
            ");
            $success = "Producto creado correctamente.";
        }
    }

    if($action === 'delete_product'){
        $id = intval($_POST['product_id']);
        $conn->query("DELETE FROM products WHERE id='$id'");
        $success = "Producto eliminado.";
    }

    if($action === 'toggle_product'){
        $id  = intval($_POST['product_id']);
        $val = intval($_POST['is_active']);
        $conn->query("UPDATE products SET is_active='$val' WHERE id='$id'");
    }

    if($action === 'save_logo'){
        $company = trim($_POST['company_name'] ?? '');
        $color   = trim($_POST['color_hex']    ?? '#5b4bff');
        if(isset($_FILES['logo']) && $_FILES['logo']['error'] === 0){
            $ext   = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
            $fname = 'logo_'.strtolower(preg_replace('/[^a-z0-9]/i','_',$company)).'.'.$ext;
            $dest  = __DIR__.'/../uploads/branding/'.$fname;
            if(move_uploaded_file($_FILES['logo']['tmp_name'], $dest)){
                $logo_path = '/uploads/branding/'.$fname;
                $cn = mysqli_real_escape_string($conn, $company);
                $co = mysqli_real_escape_string($conn, $color);
                $conn->query("INSERT INTO company_logos (company_name, logo_path, color_hex) VALUES ('$cn','$logo_path','$co')
                              ON DUPLICATE KEY UPDATE logo_path='$logo_path', color_hex='$co'");
                $success = "Logo guardado para $company.";
            }
        }
    }
}

/*
|--------------------------------------------------------------------------
| LISTAR
|--------------------------------------------------------------------------
*/

$filter_type     = $_GET['type']        ?? '';
$filter_campaign = intval($_GET['campaign_id'] ?? 0);
$filter_company  = $_GET['company']     ?? '';

$wt = $filter_type     ? "AND p.product_type = '".mysqli_real_escape_string($conn,$filter_type)."'" : "";
$wc = $filter_campaign ? "AND p.campaign_id = '$filter_campaign'" : "";
$wo = $filter_company  ? "AND p.company_name = '".mysqli_real_escape_string($conn,$filter_company)."'" : "";

$products = $conn->query("
SELECT p.*, c.campaign_name, cl.logo_path AS logo, cl.color_hex
FROM products p
LEFT JOIN campaigns c ON c.id = p.campaign_id
LEFT JOIN company_logos cl ON cl.company_name = p.company_name
WHERE 1=1 $wt $wc $wo
ORDER BY p.company_name ASC, p.product_type ASC, p.product_name ASC
");

$campaigns = $conn->query("SELECT id, campaign_name FROM campaigns ORDER BY campaign_name");
$companies = $conn->query("SELECT * FROM company_logos ORDER BY company_name");

// Editar producto
$edit_product = null;
if(isset($_GET['edit'])){
    $eid = intval($_GET['edit']);
    $edit_product = $conn->query("SELECT * FROM products WHERE id='$eid' LIMIT 1")->fetch_assoc();
}

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Productos — Settings</title>
<link rel="stylesheet" href="/assets/css/style.css">
<style>

.content-area{ margin-left:260px; padding:32px 40px; background:#f8fafc; min-height:100vh; }

.page-title{ font-size:32px; font-weight:800; color:#02122c; margin-bottom:6px; }
.page-subtitle{ color:#64748b; margin-bottom:28px; font-size:15px; }

.tabs{ display:flex; gap:8px; margin-bottom:28px; }
.tab{ padding:10px 20px; border-radius:12px; font-size:14px; font-weight:700; color:#64748b; background:#fff; border:1.5px solid #e2e8f0; cursor:pointer; text-decoration:none; transition:.2s; }
.tab.active{ background:#02122c; color:#fff; border-color:#02122c; }

.section-card{ background:#fff; border-radius:20px; padding:28px; box-shadow:0 4px 20px rgba(0,0,0,.06); margin-bottom:24px; }
.section-title{ font-size:20px; font-weight:800; color:#02122c; margin-bottom:20px; }

.form-grid{ display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:16px; margin-bottom:16px; }
.form-group label{ display:block; font-size:13px; font-weight:700; color:#475569; margin-bottom:6px; }
.form-group input, .form-group select, .form-group textarea{
    width:100%; border:1.5px solid #e2e8f0; border-radius:10px; padding:10px 14px;
    font-size:14px; color:#02122c; background:#f8fafc; box-sizing:border-box;
}
.form-group textarea{ height:80px; resize:vertical; }
.form-group input[type="file"]{ padding:8px; }
.form-group input[type="color"]{ height:42px; padding:4px 8px; cursor:pointer; }
.form-group input[type="checkbox"]{ width:auto; }

.btn-save{ height:44px; background:linear-gradient(90deg,#5b4bff,#7b61ff); color:#fff; border:none; border-radius:12px; padding:0 24px; font-size:14px; font-weight:700; cursor:pointer; }
.btn-danger{ height:36px; background:#fee2e2; color:#dc2626; border:none; border-radius:8px; padding:0 16px; font-size:13px; font-weight:700; cursor:pointer; }
.btn-edit{ height:36px; background:#ede9fe; color:#5b4bff; border:none; border-radius:8px; padding:0 16px; font-size:13px; font-weight:700; cursor:pointer; text-decoration:none; display:inline-flex; align-items:center; }

.filters{ display:flex; gap:12px; margin-bottom:20px; flex-wrap:wrap; }
.filter-select{ height:40px; border:1.5px solid #e2e8f0; border-radius:10px; padding:0 14px; font-size:14px; background:#fff; cursor:pointer; }

.product-grid{ display:grid; grid-template-columns:repeat(auto-fill,minmax(300px,1fr)); gap:16px; }

.product-card{ background:#fff; border-radius:16px; padding:20px; box-shadow:0 2px 12px rgba(0,0,0,.06); border:1.5px solid #f1f5f9; transition:.2s; }
.product-card:hover{ border-color:#e2e8f0; transform:translateY(-2px); }
.product-card.inactive{ opacity:.5; }

.product-header{ display:flex; align-items:center; gap:12px; margin-bottom:12px; }
.company-badge{ padding:4px 10px; border-radius:20px; font-size:11px; font-weight:800; color:#fff; }
.type-badge{ padding:4px 10px; border-radius:20px; font-size:11px; font-weight:700; background:#f1f5f9; color:#475569; }

.product-name{ font-size:16px; font-weight:800; color:#02122c; margin-bottom:8px; }
.product-price{ font-size:14px; color:#64748b; margin-bottom:4px; }
.product-price strong{ color:#02122c; }
.product-promo{ font-size:12px; color:#10b981; font-weight:600; margin-top:6px; }

.company-logos-grid{ display:grid; grid-template-columns:repeat(auto-fill,minmax(200px,1fr)); gap:16px; }
.logo-card{ background:#f8fafc; border-radius:14px; padding:16px; text-align:center; border:1.5px solid #e2e8f0; }
.logo-img{ width:80px; height:40px; object-fit:contain; margin-bottom:8px; }
.logo-placeholder{ width:80px; height:40px; border-radius:8px; display:inline-flex; align-items:center; justify-content:center; font-size:11px; font-weight:800; color:#fff; margin-bottom:8px; }

.alert-success{ background:#dcfce7; color:#166534; border-radius:12px; padding:14px 18px; margin-bottom:20px; font-weight:600; }
.alert-error  { background:#fee2e2; color:#dc2626; border-radius:12px; padding:14px 18px; margin-bottom:20px; font-weight:600; }

.separator{ border:none; border-top:1.5px solid #f1f5f9; margin:20px 0; }

</style>
</head>
<body>

<?php include("../includes/sidebar.php"); ?>

<div class="content-area">

    <div class="page-title">🛒 Productos</div>
    <div class="page-subtitle">Gestiona el catálogo de productos y tarifas por compañía y campaña</div>

    <?php if($success): ?><div class="alert-success">✅ <?= $success ?></div><?php endif; ?>
    <?php if($error):   ?><div class="alert-error">❌ <?= $error ?></div><?php endif; ?>

    <!-- TABS -->
    <?php $tab = $_GET['tab'] ?? 'productos'; ?>
    <div class="tabs">
        <a href="?tab=productos" class="tab <?= $tab=='productos'?'active':'' ?>">📦 Productos</a>
        <a href="?tab=nuevo"     class="tab <?= $tab=='nuevo'?'active':'' ?>">➕ Nuevo producto</a>
        <a href="?tab=logos"     class="tab <?= $tab=='logos'?'active':'' ?>">🏷️ Logos compañías</a>
    </div>

    <?php if($tab === 'productos'): ?>

    <!-- FILTROS -->
    <form method="GET" action="">
        <input type="hidden" name="tab" value="productos">
        <div class="filters">
            <select name="type" class="filter-select" onchange="this.form.submit()">
                <option value="">Todos los tipos</option>
                <?php foreach($product_types as $k=>$v): ?>
                <option value="<?= $k ?>" <?= $filter_type==$k?'selected':'' ?>><?= $v ?></option>
                <?php endforeach; ?>
            </select>
            <select name="campaign_id" class="filter-select" onchange="this.form.submit()">
                <option value="0">Todas las campañas</option>
                <?php
                $campaigns->data_seek(0);
                while($c = $campaigns->fetch_assoc()):
                ?>
                <option value="<?= $c['id'] ?>" <?= $filter_campaign==$c['id']?'selected':'' ?>>
                    <?= htmlspecialchars($c['campaign_name']) ?>
                </option>
                <?php endwhile; ?>
            </select>
            <select name="company" class="filter-select" onchange="this.form.submit()">
                <option value="">Todas las compañías</option>
                <?php
                $companies->data_seek(0);
                while($co = $companies->fetch_assoc()):
                ?>
                <option value="<?= htmlspecialchars($co['company_name']) ?>" <?= $filter_company==$co['company_name']?'selected':'' ?>>
                    <?= htmlspecialchars($co['company_name']) ?>
                </option>
                <?php endwhile; ?>
            </select>
        </div>
    </form>

    <div class="product-grid">
    <?php
    $has_products = false;
    while($p = $products->fetch_assoc()):
        $has_products = true;
        $color = $p['color_hex'] ?? '#5b4bff';
    ?>
    <div class="product-card <?= $p['is_active'] ? '' : 'inactive' ?>">

        <div class="product-header">
            <?php if($p['logo']): ?>
            <img src="<?= htmlspecialchars($p['logo']) ?>" style="height:28px;object-fit:contain;">
            <?php else: ?>
            <span class="company-badge" style="background:<?= htmlspecialchars($color) ?>">
                <?= strtoupper(substr($p['company_name'],0,3)) ?>
            </span>
            <?php endif; ?>
            <span class="type-badge"><?= $product_types[$p['product_type']] ?? $p['product_type'] ?></span>
            <?php if($p['campaign_name']): ?>
            <span style="font-size:11px;color:#94a3b8;"><?= htmlspecialchars($p['campaign_name']) ?></span>
            <?php endif; ?>
        </div>

        <div class="product-name"><?= htmlspecialchars($p['product_name']) ?></div>

        <?php if($p['precio_kwh'] > 0): ?>
        <div class="product-price">⚡ Energía: <strong><?= number_format($p['precio_kwh'],6) ?> €/kWh</strong>
            <?php if($p['descuento'] > 0): ?> <span style="color:#10b981">(-<?= $p['descuento'] ?>%)</span><?php endif; ?>
        </div>
        <?php endif; ?>

        <?php if($p['precio_potencia_p1'] > 0): ?>
        <div class="product-price">🔌 Potencia P1: <strong><?= number_format($p['precio_potencia_p1'],2) ?> €/kW año</strong></div>
        <?php endif; ?>

        <?php if($p['termino_fijo'] > 0): ?>
        <div class="product-price">📋 Término fijo: <strong><?= number_format($p['termino_fijo'],2) ?> €/mes</strong></div>
        <?php endif; ?>

        <?php if($p['permanencia']): ?>
        <div class="product-price">📅 Permanencia: <strong><?= $p['meses_permanencia'] ?> meses</strong></div>
        <?php endif; ?>

        <?php if($p['promo']): ?>
        <div class="product-promo">🎁 <?= htmlspecialchars($p['promo']) ?></div>
        <?php endif; ?>

        <?php if($p['sva']): ?>
        <div class="product-price" style="margin-top:4px;">➕ SVA: <?= htmlspecialchars($p['sva']) ?> (<?= number_format($p['precio_sva'],2) ?>€/mes)</div>
        <?php endif; ?>

        <hr class="separator">

        <div style="display:flex;gap:8px;align-items:center;">
            <a href="?tab=nuevo&edit=<?= $p['id'] ?>" class="btn-edit">✏️ Editar</a>
            <form method="POST" style="display:inline" onsubmit="return confirm('¿Eliminar producto?')">
                <input type="hidden" name="action" value="delete_product">
                <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
                <button type="submit" class="btn-danger">🗑️</button>
            </form>
            <form method="POST" style="display:inline;margin-left:auto">
                <input type="hidden" name="action" value="toggle_product">
                <input type="hidden" name="product_id" value="<?= $p['id'] ?>">
                <input type="hidden" name="is_active" value="<?= $p['is_active'] ? 0 : 1 ?>">
                <button type="submit" style="background:none;border:none;cursor:pointer;font-size:18px;" title="<?= $p['is_active']?'Desactivar':'Activar' ?>">
                    <?= $p['is_active'] ? '✅' : '⭕' ?>
                </button>
            </form>
        </div>

    </div>
    <?php endwhile; ?>

    <?php if(!$has_products): ?>
    <div style="grid-column:1/-1;text-align:center;padding:60px;color:#94a3b8;">
        <div style="font-size:48px;margin-bottom:12px;">📦</div>
        No hay productos. <a href="?tab=nuevo" style="color:#5b4bff;font-weight:700;">Añade el primero</a>
    </div>
    <?php endif; ?>

    </div>

    <?php elseif($tab === 'nuevo'): ?>

    <?php
    $ep = $edit_product ?? [];
    $form_title = $ep ? '✏️ Editar producto' : '➕ Nuevo producto';
    ?>

    <div class="section-card">
        <div class="section-title"><?= $form_title ?></div>

        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="save_product">
            <input type="hidden" name="product_id" value="<?= $ep['id'] ?? 0 ?>">

            <div class="form-grid">

                <div class="form-group">
                    <label>Compañía *</label>
                    <input type="text" name="company_name" value="<?= htmlspecialchars($ep['company_name'] ?? '') ?>" placeholder="Ej: TOTAL ENERGIES" required list="companies_list">
                    <datalist id="companies_list">
                        <?php
                        $companies->data_seek(0);
                        while($co = $companies->fetch_assoc()):
                        ?>
                        <option value="<?= htmlspecialchars($co['company_name']) ?>">
                        <?php endwhile; ?>
                    </datalist>
                </div>

                <div class="form-group">
                    <label>Nombre del producto *</label>
                    <input type="text" name="product_name" value="<?= htmlspecialchars($ep['product_name'] ?? '') ?>" placeholder="Ej: Tarifa Luz Fija 24h" required>
                </div>

                <div class="form-group">
                    <label>Tipo de producto</label>
                    <select name="product_type">
                        <?php foreach($product_types as $k=>$v): ?>
                        <option value="<?= $k ?>" <?= ($ep['product_type']??'luz')==$k?'selected':'' ?>><?= $v ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label>Campaña (opcional)</label>
                    <select name="campaign_id">
                        <option value="0">Todas las campañas</option>
                        <?php
                        $campaigns->data_seek(0);
                        while($c = $campaigns->fetch_assoc()):
                        ?>
                        <option value="<?= $c['id'] ?>" <?= ($ep['campaign_id']??0)==$c['id']?'selected':'' ?>>
                            <?= htmlspecialchars($c['campaign_name']) ?>
                        </option>
                        <?php endwhile; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label>Tarifa ATR</label>
                    <input type="text" name="tarifa_atr" value="<?= htmlspecialchars($ep['tarifa_atr'] ?? '') ?>" placeholder="Ej: 2.0TD, RL1, RL2">
                </div>

                <div class="form-group">
                    <label>Logo compañía (imagen)</label>
                    <input type="file" name="company_logo" accept="image/*">
                </div>

            </div>

            <div class="section-title" style="font-size:16px;margin-bottom:12px;">💡 Precios energía</div>

            <div class="form-grid">

                <div class="form-group">
                    <label>Precio kWh P1 (€)</label>
                    <input type="text" name="precio_kwh" value="<?= $ep['precio_kwh'] ?? '0' ?>" placeholder="0.1399">
                </div>

                <div class="form-group">
                    <label>Precio kWh P2 (€)</label>
                    <input type="text" name="precio_kwh_p2" value="<?= $ep['precio_kwh_p2'] ?? '0' ?>" placeholder="0.0800">
                </div>

                <div class="form-group">
                    <label>Precio kWh P3 (€)</label>
                    <input type="text" name="precio_kwh_p3" value="<?= $ep['precio_kwh_p3'] ?? '0' ?>" placeholder="0.0600">
                </div>

                <div class="form-group">
                    <label>Potencia P1 (€/kW año)</label>
                    <input type="text" name="precio_potencia_p1" value="<?= $ep['precio_potencia_p1'] ?? '0' ?>" placeholder="43.99">
                </div>

                <div class="form-group">
                    <label>Potencia P2 (€/kW año)</label>
                    <input type="text" name="precio_potencia_p2" value="<?= $ep['precio_potencia_p2'] ?? '0' ?>" placeholder="21.99">
                </div>

                <div class="form-group">
                    <label>Término fijo €/mes (gas)</label>
                    <input type="text" name="termino_fijo" value="<?= $ep['termino_fijo'] ?? '0' ?>" placeholder="5.15">
                </div>

                <div class="form-group">
                    <label>Descuento % energía</label>
                    <input type="text" name="descuento" value="<?= $ep['descuento'] ?? '0' ?>" placeholder="10">
                </div>

                <div class="form-group">
                    <label>Descuento % potencia</label>
                    <input type="text" name="descuento_potencia" value="<?= $ep['descuento_potencia'] ?? '0' ?>" placeholder="0">
                </div>

            </div>

            <div class="section-title" style="font-size:16px;margin-bottom:12px;">📋 Condiciones</div>

            <div class="form-grid">

                <div class="form-group">
                    <label>
                        <input type="checkbox" name="permanencia" value="1" <?= ($ep['permanencia']??0)?'checked':'' ?>>
                        Con permanencia
                    </label>
                    <input type="number" name="meses_permanencia" value="<?= $ep['meses_permanencia'] ?? 12 ?>" placeholder="12 meses" style="margin-top:6px">
                </div>

                <div class="form-group">
                    <label>Promoción / Oferta</label>
                    <input type="text" name="promo" value="<?= htmlspecialchars($ep['promo'] ?? '') ?>" placeholder="Ej: 720 horas gratis">
                </div>

                <div class="form-group">
                    <label>SVA (servicio adicional)</label>
                    <input type="text" name="sva" value="<?= htmlspecialchars($ep['sva'] ?? '') ?>" placeholder="Ej: Seguro hogar">
                </div>

                <div class="form-group">
                    <label>Precio SVA (€/mes)</label>
                    <input type="text" name="precio_sva" value="<?= $ep['precio_sva'] ?? '0' ?>" placeholder="5.99">
                </div>

                <div class="form-group">
                    <label>
                        <input type="checkbox" name="is_active" value="1" <?= ($ep['is_active']??1)?'checked':'' ?>>
                        Producto activo
                    </label>
                </div>

            </div>

            <div class="form-group" style="margin-bottom:20px;">
                <label>Descripción</label>
                <textarea name="descripcion"><?= htmlspecialchars($ep['descripcion'] ?? '') ?></textarea>
            </div>

            <button type="submit" class="btn-save">
                <?= $ep ? '💾 Guardar cambios' : '➕ Crear producto' ?>
            </button>

            <?php if($ep): ?>
            <a href="?tab=nuevo" style="margin-left:12px;color:#64748b;font-size:14px;">Cancelar</a>
            <?php endif; ?>

        </form>

    </div>

    <?php elseif($tab === 'logos'): ?>

    <div class="section-card">
        <div class="section-title">🏷️ Logos de compañías</div>

        <div class="company-logos-grid">
            <?php
            $companies->data_seek(0);
            while($co = $companies->fetch_assoc()):
            ?>
            <div class="logo-card">
                <?php if($co['logo_path']): ?>
                <img src="<?= htmlspecialchars($co['logo_path']) ?>" class="logo-img" alt="Logo">
                <?php else: ?>
                <div class="logo-placeholder" style="background:<?= htmlspecialchars($co['color_hex']) ?>">
                    <?= strtoupper(substr($co['company_name'],0,4)) ?>
                </div>
                <?php endif; ?>
                <div style="font-size:13px;font-weight:700;color:#02122c;margin-bottom:8px;"><?= htmlspecialchars($co['company_name']) ?></div>
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="save_logo">
                    <input type="hidden" name="company_name" value="<?= htmlspecialchars($co['company_name']) ?>">
                    <input type="color" name="color_hex" value="<?= htmlspecialchars($co['color_hex']) ?>" style="width:40px;height:30px;border:none;padding:0;cursor:pointer;">
                    <input type="file" name="logo" accept="image/*" style="font-size:11px;margin:6px 0;">
                    <button type="submit" class="btn-save" style="height:32px;font-size:12px;padding:0 14px;width:100%;margin-top:4px;">Guardar</button>
                </form>
            </div>
            <?php endwhile; ?>
        </div>

        <hr class="separator">

        <div class="section-title" style="font-size:16px;margin-bottom:12px;">➕ Nueva compañía</div>
        <form method="POST" enctype="multipart/form-data" style="display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap;">
            <input type="hidden" name="action" value="save_logo">
            <div class="form-group" style="margin:0">
                <label>Nombre compañía</label>
                <input type="text" name="company_name" placeholder="Ej: GANA ENERGIA" style="width:200px">
            </div>
            <div class="form-group" style="margin:0">
                <label>Color</label>
                <input type="color" name="color_hex" value="#5b4bff" style="width:60px;height:42px;">
            </div>
            <div class="form-group" style="margin:0">
                <label>Logo</label>
                <input type="file" name="logo" accept="image/*">
            </div>
            <button type="submit" class="btn-save">Añadir</button>
        </form>

    </div>

    <?php endif; ?>

</div>

</body>
</html>