<?php

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

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

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

$user_id  = intval($_SESSION['user_id']);
$is_admin = intval($_SESSION['can_manage_users'] ?? 0) === 1;

// Campañas del usuario
$camp_ids = [];
$cq = $conn->query("SELECT campaign_id FROM user_campaigns WHERE user_id='$user_id'");
while($c = $cq->fetch_assoc()) $camp_ids[] = $c['campaign_id'];

$filter_type = $_GET['type'] ?? '';
$filter_comp = $_GET['company'] ?? '';

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

// Admin ve todo, agente solo sus campañas
if(!$is_admin && !empty($camp_ids)){
    $cids = implode(',', $camp_ids);
    $wcamps = "AND (p.campaign_id IS NULL OR p.campaign_id IN ($cids))";
} else {
    $wcamps = "";
}

$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 p.is_active = 1 $wt $wc $wcamps
ORDER BY p.company_name ASC, p.product_type ASC, p.product_name ASC
");

// Compañías disponibles
$companies = $conn->query("
SELECT DISTINCT p.company_name, cl.logo_path, cl.color_hex
FROM products p
LEFT JOIN company_logos cl ON cl.company_name = p.company_name
WHERE p.is_active = 1 $wcamps
ORDER BY p.company_name ASC
");

$product_types = [
    'luz'        => ['label'=>'⚡ Luz',         'color'=>'#fef9c3','text'=>'#854d0e'],
    'gas'        => ['label'=>'🔥 Gas',         'color'=>'#fee2e2','text'=>'#991b1b'],
    'luz_gas'    => ['label'=>'⚡🔥 Luz + Gas', 'color'=>'#ede9fe','text'=>'#5b21b6'],
    'telecom'    => ['label'=>'📡 Telecom',     'color'=>'#dbeafe','text'=>'#1e40af'],
    'alarma'     => ['label'=>'🔔 Alarma',      'color'=>'#dcfce7','text'=>'#166534'],
    'seguro'     => ['label'=>'🛡️ Seguro',      'color'=>'#fce7f3','text'=>'#9d174d'],
    'financiero' => ['label'=>'💳 Financiero',  'color'=>'#f1f5f9','text'=>'#475569'],
    'otro'       => ['label'=>'📦 Otro',        'color'=>'#f8fafc','text'=>'#64748b'],
];

// Agrupar por tipo
$grouped = [];
while($p = $products->fetch_assoc()){
    $grouped[$p['product_type']][] = $p;
}

$selected_type = $filter_type ?: 'all';

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Productos</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; }

.type-selector{
    display:grid;
    grid-template-columns:repeat(auto-fill,minmax(140px,1fr));
    gap:12px;
    margin-bottom:32px;
}

.type-btn{
    background:#fff;
    border:2px solid #e2e8f0;
    border-radius:16px;
    padding:16px 12px;
    text-align:center;
    cursor:pointer;
    text-decoration:none;
    transition:.2s;
    display:block;
}

.type-btn:hover{ transform:translateY(-2px); box-shadow:0 8px 24px rgba(0,0,0,.08); }
.type-btn.active{ border-color:#5b4bff; background:#ede9fe; }

.type-btn-icon{ font-size:28px; margin-bottom:6px; }
.type-btn-label{ font-size:13px; font-weight:700; color:#02122c; }
.type-btn-count{ font-size:11px; color:#94a3b8; margin-top:2px; }

.company-filter{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
    margin-bottom:24px;
    align-items:center;
}

.company-chip{
    display:flex;
    align-items:center;
    gap:6px;
    padding:6px 14px;
    border-radius:20px;
    background:#fff;
    border:1.5px solid #e2e8f0;
    font-size:13px;
    font-weight:700;
    color:#475569;
    cursor:pointer;
    text-decoration:none;
    transition:.2s;
}

.company-chip.active{ border-color:#5b4bff; background:#ede9fe; color:#5b4bff; }
.company-chip img{ height:20px; object-fit:contain; }

.products-section{ margin-bottom:36px; }

.section-header{
    display:flex;
    align-items:center;
    gap:12px;
    margin-bottom:16px;
}

.section-type-badge{
    padding:6px 14px;
    border-radius:20px;
    font-size:14px;
    font-weight:800;
}

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

.product-card{
    background:#fff;
    border-radius:20px;
    padding:22px;
    box-shadow:0 4px 16px rgba(0,0,0,.06);
    border:1.5px solid #f1f5f9;
    transition:.2s;
    position:relative;
    overflow:hidden;
}

.product-card:hover{
    transform:translateY(-3px);
    box-shadow:0 12px 32px rgba(0,0,0,.10);
}

.product-card-accent{
    position:absolute;
    top:0; left:0; right:0;
    height:4px;
}

.product-company{
    display:flex;
    align-items:center;
    gap:8px;
    margin-bottom:10px;
}

.company-logo-sm{
    height:24px;
    object-fit:contain;
}

.company-name-sm{
    font-size:12px;
    font-weight:800;
    color:#64748b;
    text-transform:uppercase;
    letter-spacing:.5px;
}

.product-name{
    font-size:17px;
    font-weight:800;
    color:#02122c;
    margin-bottom:12px;
    line-height:1.3;
}

.price-block{
    background:#f8fafc;
    border-radius:12px;
    padding:12px 14px;
    margin-bottom:10px;
}

.price-row{
    display:flex;
    justify-content:space-between;
    align-items:center;
    padding:4px 0;
    font-size:13px;
}

.price-label{ color:#64748b; }
.price-value{ font-weight:800; color:#02122c; }
.price-value.destacado{ color:#5b4bff; font-size:16px; }
.price-value.green{ color:#10b981; }

.product-promo{
    background:linear-gradient(90deg,#dcfce7,#d1fae5);
    border-radius:10px;
    padding:8px 12px;
    font-size:12px;
    font-weight:700;
    color:#166534;
    margin-bottom:8px;
}

.product-sva{
    background:#f1f5f9;
    border-radius:10px;
    padding:8px 12px;
    font-size:12px;
    color:#475569;
    margin-bottom:8px;
}

.product-perm{
    display:inline-block;
    padding:3px 10px;
    border-radius:20px;
    font-size:11px;
    font-weight:700;
    background:#fef3c7;
    color:#92400e;
    margin-bottom:8px;
}

.product-desc{
    font-size:13px;
    color:#64748b;
    line-height:1.5;
    margin-top:8px;
}

.btn-comparar{
    display:block;
    width:100%;
    margin-top:14px;
    height:40px;
    background:linear-gradient(90deg,#5b4bff,#7b61ff);
    color:#fff;
    border:none;
    border-radius:12px;
    font-size:13px;
    font-weight:700;
    cursor:pointer;
    text-align:center;
    line-height:40px;
    text-decoration:none;
    transition:.2s;
}

.btn-comparar:hover{ opacity:.88; }

.empty-state{
    text-align:center;
    padding:60px;
    color:#94a3b8;
    grid-column:1/-1;
}

</style>
</head>
<body>

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

<div class="content-area">

    <div class="page-title">📦 Productos</div>
    <div class="page-subtitle">Catálogo de tarifas y servicios disponibles para ofrecer</div>

    <!-- SELECTOR DE TIPO -->
    <div class="type-selector">

        <a href="?type=&company=<?= urlencode($filter_comp) ?>"
           class="type-btn <?= !$filter_type?'active':'' ?>">
            <div class="type-btn-icon">🏪</div>
            <div class="type-btn-label">Todos</div>
            <div class="type-btn-count"><?= array_sum(array_map('count',$grouped)) ?> productos</div>
        </a>

        <?php foreach($product_types as $k=>$t): ?>
        <?php $count = count($grouped[$k] ?? []); if(!$count && !$is_admin) continue; ?>
        <a href="?type=<?= $k ?>&company=<?= urlencode($filter_comp) ?>"
           class="type-btn <?= $filter_type==$k?'active':'' ?>">
            <div class="type-btn-icon"><?= explode(' ',$t['label'])[0] ?></div>
            <div class="type-btn-label"><?= implode(' ',array_slice(explode(' ',$t['label']),1)) ?></div>
            <div class="type-btn-count"><?= $count ?> producto<?= $count!=1?'s':'' ?></div>
        </a>
        <?php endforeach; ?>

    </div>

    <!-- FILTRO COMPAÑÍA -->
    <div class="company-filter">
        <span style="font-size:13px;font-weight:700;color:#64748b;">Compañía:</span>
        <a href="?type=<?= urlencode($filter_type) ?>&company="
           class="company-chip <?= !$filter_comp?'active':'' ?>">Todas</a>
        <?php while($co = $companies->fetch_assoc()): ?>
        <a href="?type=<?= urlencode($filter_type) ?>&company=<?= urlencode($co['company_name']) ?>"
           class="company-chip <?= $filter_comp==$co['company_name']?'active':'' ?>">
            <?php if($co['logo_path']): ?>
            <img src="<?= htmlspecialchars($co['logo_path']) ?>" class="company-logo-sm">
            <?php else: ?>
            <span style="width:16px;height:16px;border-radius:4px;background:<?= htmlspecialchars($co['color_hex']??'#5b4bff') ?>;display:inline-block;"></span>
            <?php endif; ?>
            <?= htmlspecialchars($co['company_name']) ?>
        </a>
        <?php endwhile; ?>
    </div>

    <!-- PRODUCTOS POR TIPO -->
    <?php
    $show_types = $filter_type ? [$filter_type] : array_keys($product_types);
    $total_shown = 0;

    foreach($show_types as $type):
        $items = $grouped[$type] ?? [];
        if($filter_comp) $items = array_filter($items, fn($p) => $p['company_name'] === $filter_comp);
        $items = array_values($items);
        if(empty($items)) continue;
        $total_shown += count($items);
        $t = $product_types[$type];
    ?>

    <div class="products-section">

        <div class="section-header">
            <span class="section-type-badge" style="background:<?= $t['color'] ?>;color:<?= $t['text'] ?>">
                <?= $t['label'] ?>
            </span>
            <span style="font-size:14px;color:#94a3b8;"><?= count($items) ?> producto<?= count($items)!=1?'s':'' ?></span>
        </div>

        <div class="products-grid">

        <?php foreach($items as $p):
            $color = $p['color_hex'] ?? '#5b4bff';
            $precio_final_kwh = $p['precio_kwh'] > 0
                ? $p['precio_kwh'] * (1 - ($p['descuento']/100))
                : 0;
        ?>

        <div class="product-card">

            <div class="product-card-accent" style="background:<?= htmlspecialchars($color) ?>"></div>

            <div class="product-company">
                <?php if($p['logo']): ?>
                <img src="<?= htmlspecialchars($p['logo']) ?>" class="company-logo-sm" alt="Logo">
                <?php else: ?>
                <span style="width:20px;height:20px;border-radius:6px;background:<?= htmlspecialchars($color) ?>;display:inline-block;"></span>
                <?php endif; ?>
                <span class="company-name-sm"><?= htmlspecialchars($p['company_name']) ?></span>
                <?php if($p['tarifa_atr']): ?>
                <span style="font-size:11px;background:#f1f5f9;padding:2px 8px;border-radius:10px;color:#64748b;"><?= htmlspecialchars($p['tarifa_atr']) ?></span>
                <?php endif; ?>
            </div>

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

            <div class="price-block">

                <?php if($precio_final_kwh > 0): ?>
                <div class="price-row">
                    <span class="price-label">⚡ Precio energía</span>
                    <span class="price-value destacado"><?= number_format($precio_final_kwh,5) ?> €/kWh</span>
                </div>
                <?php if($p['descuento'] > 0): ?>
                <div class="price-row">
                    <span class="price-label">Descuento</span>
                    <span class="price-value green">-<?= $p['descuento'] ?>%</span>
                </div>
                <?php endif; ?>
                <?php endif; ?>

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

                <?php if($p['precio_potencia_p2'] > 0): ?>
                <div class="price-row">
                    <span class="price-label">Potencia P2</span>
                    <span class="price-value"><?= number_format($p['precio_potencia_p2'],2) ?> €/kW año</span>
                </div>
                <?php endif; ?>

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

            </div>

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

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

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

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

            <?php if(in_array($p['product_type'],['luz','gas','luz_gas'])): ?>
            <a href="/pages/comparativas.php?product_id=<?= $p['id'] ?>" class="btn-comparar">
                📊 Comparar con factura cliente
            </a>
            <?php endif; ?>

        </div>

        <?php endforeach; ?>

        </div>

    </div>

    <?php endforeach; ?>

    <?php if($total_shown === 0): ?>
    <div style="text-align:center;padding:80px;color:#94a3b8;">
        <div style="font-size:48px;margin-bottom:12px;">📦</div>
        No hay productos disponibles para tu perfil.
        <?php if($is_admin): ?>
        <br><a href="/pages/settings_products.php" style="color:#5b4bff;font-weight:700;">Añadir productos</a>
        <?php endif; ?>
    </div>
    <?php endif; ?>

</div>

</body>
</html>