<?php

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

// Solo super admin puede entrar
if(
    !isset($_SESSION['is_super_admin']) ||
    intval($_SESSION['is_super_admin']) !== 1
){
    header("Location: /pages/settings.php");
    exit;
}

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

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

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

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

    // CREAR EMPRESA
    if($action === 'create_company'){

        $name      = trim($_POST['name'] ?? '');
        $slug      = strtolower(preg_replace('/[^a-z0-9]+/i','-', trim($_POST['slug'] ?? '')));
        $plan      = trim($_POST['plan'] ?? 'basic');
        $color_p   = trim($_POST['color_primary']   ?? '#5b4bff');
        $color_s   = trim($_POST['color_secondary'] ?? '#7b61ff');
        $color_sb  = trim($_POST['color_sidebar']   ?? '#02122c');

        if(empty($name) || empty($slug)){
            $error = "Nombre y slug son obligatorios.";
        } else {

            $stmt = $conn->prepare("
            INSERT INTO companies (name, slug, color_primary, color_secondary, color_sidebar, plan)
            VALUES (?, ?, ?, ?, ?, ?)
            ");
            $stmt->bind_param("ssssss", $name, $slug, $color_p, $color_s, $color_sb, $plan);

            if($stmt->execute()){

                $new_id = $conn->insert_id;

                // Módulos por defecto
                $default_modules = ['leads','contracts','pipeline','reports','metrics'];
                foreach($default_modules as $m){
                    $conn->query("
                    INSERT IGNORE INTO company_modules (company_id, module, is_active)
                    VALUES ('$new_id', '$m', 1)
                    ");
                }

                // Subir logo si viene
                if(isset($_FILES['logo']) && $_FILES['logo']['error'] === 0){
                    $ext      = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
                    $filename = 'company_'.$new_id.'_'.time().'.'.$ext;
                    $dest     = __DIR__.'/../uploads/branding/'.$filename;
                    if(move_uploaded_file($_FILES['logo']['tmp_name'], $dest)){
                        $conn->query("UPDATE companies SET logo='/uploads/branding/$filename' WHERE id='$new_id'");
                    }
                }

                $success = "Empresa <strong>$name</strong> creada correctamente.";

            } else {
                $error = "Error al crear empresa: ".$conn->error;
            }
        }
    }

    // ACTUALIZAR EMPRESA
    if($action === 'update_company'){

        $id        = intval($_POST['company_id']);
        $name      = trim($_POST['name'] ?? '');
        $plan      = trim($_POST['plan'] ?? 'basic');
        $color_p   = trim($_POST['color_primary']   ?? '#5b4bff');
        $color_s   = trim($_POST['color_secondary'] ?? '#7b61ff');
        $color_sb  = trim($_POST['color_sidebar']   ?? '#02122c');
        $is_active = isset($_POST['is_active']) ? 1 : 0;

        $conn->query("
        UPDATE companies SET
            name             = '".mysqli_real_escape_string($conn,$name)."',
            plan             = '".mysqli_real_escape_string($conn,$plan)."',
            color_primary    = '".mysqli_real_escape_string($conn,$color_p)."',
            color_secondary  = '".mysqli_real_escape_string($conn,$color_s)."',
            color_sidebar    = '".mysqli_real_escape_string($conn,$color_sb)."',
            is_active        = '$is_active'
        WHERE id = '$id'
        ");

        // Actualizar módulos
        $all_modules = ['leads','contracts','pipeline','telefonia','whatsapp','email','ranking','comparativas','ia_assistant','reports','metrics','import'];
        foreach($all_modules as $m){
            $active = isset($_POST['mod_'.$m]) ? 1 : 0;
            $conn->query("
            INSERT INTO company_modules (company_id, module, is_active)
            VALUES ('$id', '$m', '$active')
            ON DUPLICATE KEY UPDATE is_active = '$active'
            ");
        }

        // Logo
        if(isset($_FILES['logo']) && $_FILES['logo']['error'] === 0){
            $ext      = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
            $filename = 'company_'.$id.'_'.time().'.'.$ext;
            $dest     = __DIR__.'/../uploads/branding/'.$filename;
            if(move_uploaded_file($_FILES['logo']['tmp_name'], $dest)){
                $conn->query("UPDATE companies SET logo='/uploads/branding/$filename' WHERE id='$id'");
            }
        }

        $success = "Empresa actualizada correctamente.";
    }

    // TOGGLE ACTIVO/INACTIVO
    if($action === 'toggle_company'){
        $id     = intval($_POST['company_id']);
        $active = intval($_POST['is_active']);
        $conn->query("UPDATE companies SET is_active='$active' WHERE id='$id'");
        $success = "Estado actualizado.";
    }
}

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

$companies = $conn->query("
SELECT c.*,
    (SELECT COUNT(*) FROM users WHERE company_id = c.id) AS total_users,
    (SELECT COUNT(*) FROM campaigns WHERE company_id = c.id) AS total_campaigns
FROM companies c
ORDER BY c.id ASC
");

$all_modules = [
    'leads'        => '📋 Leads',
    'contracts'    => '📄 Contratos',
    'pipeline'     => '🔄 Pipeline',
    'telefonia'    => '📞 Telefonía',
    'whatsapp'     => '💬 WhatsApp',
    'email'        => '📧 Email',
    'ranking'      => '🏆 Ranking',
    'comparativas' => '📊 Comparativas IA',
    'ia_assistant' => '🤖 IA Assistant',
    'reports'      => '📈 Reportes',
    'metrics'      => '📉 Métricas',
    'import'       => '📥 Importar bases',
];

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

.content-area{
    margin-left:260px;
    padding:40px;
}

.page-title{
    font-size:36px;
    font-weight:800;
    color:#02122c;
    margin-bottom:6px;
}

.page-subtitle{
    color:#64748b;
    margin-bottom:32px;
    font-size:15px;
}

.super-badge{
    display:inline-block;
    background:linear-gradient(90deg,#f59e0b,#ef4444);
    color:#fff;
    font-size:11px;
    font-weight:800;
    padding:3px 10px;
    border-radius:20px;
    margin-left:10px;
    vertical-align:middle;
    letter-spacing:.5px;
}

.companies-grid{
    display:grid;
    grid-template-columns:repeat(auto-fill,minmax(340px,1fr));
    gap:24px;
    margin-bottom:40px;
}

.company-card{
    background:#fff;
    border-radius:20px;
    padding:24px;
    box-shadow:0 4px 20px rgba(15,23,42,.07);
    border:2px solid transparent;
    transition:.2s;
}

.company-card.inactive{
    opacity:.55;
    border-color:#fee2e2;
}

.company-card-header{
    display:flex;
    align-items:center;
    gap:14px;
    margin-bottom:16px;
}

.company-logo{
    width:52px;
    height:52px;
    border-radius:12px;
    object-fit:contain;
    background:#f1f5f9;
    padding:4px;
}

.company-logo-placeholder{
    width:52px;
    height:52px;
    border-radius:12px;
    display:flex;
    align-items:center;
    justify-content:center;
    font-size:22px;
    font-weight:800;
    color:#fff;
}

.company-name{
    font-size:18px;
    font-weight:800;
    color:#02122c;
}

.company-slug{
    font-size:12px;
    color:#94a3b8;
}

.plan-badge{
    display:inline-block;
    padding:3px 10px;
    border-radius:20px;
    font-size:11px;
    font-weight:700;
    text-transform:uppercase;
    letter-spacing:.5px;
}

.plan-basic      { background:#f1f5f9; color:#475569; }
.plan-pro        { background:#dbeafe; color:#1d4ed8; }
.plan-enterprise { background:#ede9fe; color:#6d28d9; }

.company-stats{
    display:flex;
    gap:16px;
    margin:12px 0 16px;
}

.stat-item{
    background:#f8fafc;
    border-radius:10px;
    padding:8px 14px;
    text-align:center;
    flex:1;
}

.stat-value{
    font-size:20px;
    font-weight:800;
    color:#02122c;
}

.stat-label{
    font-size:11px;
    color:#94a3b8;
}

.modules-mini{
    display:flex;
    flex-wrap:wrap;
    gap:6px;
    margin-bottom:16px;
}

.module-chip{
    background:#f1f5f9;
    border-radius:8px;
    padding:3px 8px;
    font-size:11px;
    color:#475569;
}

.module-chip.on{
    background:#dcfce7;
    color:#166534;
}

.btn-edit{
    display:inline-block;
    background:linear-gradient(90deg,#5b4bff,#7b61ff);
    color:#fff;
    border:none;
    border-radius:10px;
    padding:8px 18px;
    font-size:13px;
    font-weight:700;
    cursor:pointer;
    text-decoration:none;
    transition:.2s;
}

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

.btn-toggle-off{
    display:inline-block;
    background:#fee2e2;
    color:#dc2626;
    border:none;
    border-radius:10px;
    padding:8px 18px;
    font-size:13px;
    font-weight:700;
    cursor:pointer;
    margin-left:8px;
}

.btn-toggle-on{
    display:inline-block;
    background:#dcfce7;
    color:#16a34a;
    border:none;
    border-radius:10px;
    padding:8px 18px;
    font-size:13px;
    font-weight:700;
    cursor:pointer;
    margin-left:8px;
}

/* FORM CREAR/EDITAR */
.white-card{
    background:#fff;
    border-radius:20px;
    padding:30px;
    box-shadow:0 4px 20px rgba(15,23,42,.07);
    margin-bottom:30px;
}

.section-title{
    font-size:20px;
    font-weight:800;
    color:#02122c;
    margin-bottom:20px;
}

.form-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(220px,1fr));
    gap:16px;
    margin-bottom:20px;
}

.form-group label{
    display:block;
    font-size:13px;
    font-weight:700;
    color:#475569;
    margin-bottom:6px;
}

.form-group input,
.form-group select{
    width:100%;
    height:44px;
    border:1.5px solid #e2e8f0;
    border-radius:10px;
    padding:0 14px;
    font-size:14px;
    color:#02122c;
    background:#f8fafc;
    box-sizing:border-box;
}

.form-group input[type="color"]{
    padding:2px 6px;
    height:44px;
    cursor:pointer;
}

.form-group input[type="file"]{
    padding:8px 14px;
    height:auto;
}

.modules-grid{
    display:grid;
    grid-template-columns:repeat(auto-fill,minmax(180px,1fr));
    gap:10px;
    margin-bottom:20px;
}

.module-toggle{
    display:flex;
    align-items:center;
    gap:10px;
    background:#f8fafc;
    border-radius:10px;
    padding:10px 14px;
    cursor:pointer;
    font-size:13px;
    font-weight:600;
    color:#475569;
    transition:.15s;
}

.module-toggle:hover{ background:#f1f5f9; }

.module-toggle input{ cursor:pointer; }

.btn-save{
    height:48px;
    background:linear-gradient(90deg,#5b4bff,#7b61ff);
    color:#fff;
    border:none;
    border-radius:12px;
    padding:0 28px;
    font-size:15px;
    font-weight:700;
    cursor:pointer;
}

.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;
}

.modal-overlay{
    display:none;
    position:fixed;
    inset:0;
    background:rgba(0,0,0,.5);
    z-index:1000;
    align-items:center;
    justify-content:center;
}

.modal-overlay.open{ display:flex; }

.modal-box{
    background:#fff;
    border-radius:20px;
    padding:30px;
    width:100%;
    max-width:680px;
    max-height:90vh;
    overflow-y:auto;
    box-shadow:0 20px 60px rgba(0,0,0,.2);
}

.modal-title{
    font-size:22px;
    font-weight:800;
    margin-bottom:20px;
    color:#02122c;
}

.modal-close{
    float:right;
    background:none;
    border:none;
    font-size:22px;
    cursor:pointer;
    color:#94a3b8;
    margin-top:-4px;
}

.color-preview{
    display:flex;
    gap:8px;
    align-items:center;
    margin-top:6px;
}

.color-dot{
    width:20px;
    height:20px;
    border-radius:50%;
    border:2px solid #e2e8f0;
}

</style>
</head>
<body>

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

<div class="content-area">

    <div class="page-title">
        Empresas
        <span class="super-badge">⚡ SUPER ADMIN</span>
    </div>

    <div class="page-subtitle">
        Gestiona todas las empresas del CRM — módulos, branding y configuración
    </div>

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

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

    <!-- EMPRESAS EXISTENTES -->
    <div class="companies-grid">

        <?php while($c = $companies->fetch_assoc()): ?>

        <?php
        // Módulos activos de esta empresa
        $mods_q = $conn->query("SELECT module FROM company_modules WHERE company_id='".$c['id']."' AND is_active=1");
        $active_mods = [];
        while($m = $mods_q->fetch_assoc()) $active_mods[] = $m['module'];

        $bg_color = $c['color_primary'] ?? '#5b4bff';
        $initials = strtoupper(substr($c['name'],0,2));
        ?>

        <div class="company-card <?= $c['is_active'] ? '' : 'inactive' ?>">

            <div class="company-card-header">

                <?php if($c['logo']): ?>
                <img src="<?= htmlspecialchars($c['logo']) ?>" class="company-logo" alt="Logo">
                <?php else: ?>
                <div class="company-logo-placeholder" style="background:<?= htmlspecialchars($bg_color) ?>">
                    <?= $initials ?>
                </div>
                <?php endif; ?>

                <div>
                    <div class="company-name"><?= htmlspecialchars($c['name']) ?></div>
                    <div class="company-slug">slug: <?= htmlspecialchars($c['slug']) ?></div>
                    <span class="plan-badge plan-<?= $c['plan'] ?>"><?= $c['plan'] ?></span>
                </div>

            </div>

            <div class="company-stats">
                <div class="stat-item">
                    <div class="stat-value"><?= $c['total_users'] ?></div>
                    <div class="stat-label">Usuarios</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value"><?= $c['total_campaigns'] ?></div>
                    <div class="stat-label">Campañas</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value"><?= count($active_mods) ?></div>
                    <div class="stat-label">Módulos</div>
                </div>
            </div>

            <div class="modules-mini">
                <?php foreach($all_modules as $key => $label): ?>
                <span class="module-chip <?= in_array($key,$active_mods) ? 'on' : '' ?>">
                    <?= $label ?>
                </span>
                <?php endforeach; ?>
            </div>

            <div>
                <button
                    class="btn-edit"
                    onclick="openEdit(<?= htmlspecialchars(json_encode($c)) ?>, <?= htmlspecialchars(json_encode($active_mods)) ?>)"
                >
                    ✏️ Editar
                </button>

                <form method="POST" style="display:inline">
                    <input type="hidden" name="action" value="toggle_company">
                    <input type="hidden" name="company_id" value="<?= $c['id'] ?>">
                    <input type="hidden" name="is_active" value="<?= $c['is_active'] ? 0 : 1 ?>">
                    <button type="submit" class="<?= $c['is_active'] ? 'btn-toggle-off' : 'btn-toggle-on' ?>">
                        <?= $c['is_active'] ? '⏸ Desactivar' : '▶ Activar' ?>
                    </button>
                </form>
            </div>

        </div>

        <?php endwhile; ?>

    </div>

    <!-- CREAR NUEVA EMPRESA -->
    <div class="white-card">

        <div class="section-title">➕ Nueva empresa</div>

        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="create_company">

            <div class="form-grid">

                <div class="form-group">
                    <label>Nombre de la empresa *</label>
                    <input type="text" name="name" placeholder="Ej: Acme Corp" required>
                </div>

                <div class="form-group">
                    <label>Slug (URL único) *</label>
                    <input type="text" name="slug" placeholder="ej: acme-corp" required>
                </div>

                <div class="form-group">
                    <label>Plan</label>
                    <select name="plan">
                        <option value="basic">Basic</option>
                        <option value="pro">Pro</option>
                        <option value="enterprise">Enterprise</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Logo</label>
                    <input type="file" name="logo" accept="image/*">
                </div>

                <div class="form-group">
                    <label>Color primario</label>
                    <input type="color" name="color_primary" value="#5b4bff">
                </div>

                <div class="form-group">
                    <label>Color secundario</label>
                    <input type="color" name="color_secondary" value="#7b61ff">
                </div>

                <div class="form-group">
                    <label>Color sidebar</label>
                    <input type="color" name="color_sidebar" value="#02122c">
                </div>

            </div>

            <div class="section-title" style="font-size:16px;margin-bottom:12px;">Módulos activos</div>

            <div class="modules-grid">
                <?php foreach($all_modules as $key => $label): ?>
                <label class="module-toggle">
                    <input type="checkbox" name="mod_<?= $key ?>" value="1"
                        <?= in_array($key,['leads','contracts','pipeline','reports','metrics']) ? 'checked' : '' ?>
                    >
                    <?= $label ?>
                </label>
                <?php endforeach; ?>
            </div>

            <button type="submit" class="btn-save">Crear empresa</button>

        </form>

    </div>

</div>

<!-- MODAL EDITAR EMPRESA -->
<div class="modal-overlay" id="editModal">
    <div class="modal-box">

        <button class="modal-close" onclick="closeEdit()">✕</button>
        <div class="modal-title">✏️ Editar empresa</div>

        <form method="POST" enctype="multipart/form-data" id="editForm">
            <input type="hidden" name="action" value="update_company">
            <input type="hidden" name="company_id" id="edit_company_id">

            <div class="form-grid">

                <div class="form-group">
                    <label>Nombre *</label>
                    <input type="text" name="name" id="edit_name" required>
                </div>

                <div class="form-group">
                    <label>Plan</label>
                    <select name="plan" id="edit_plan">
                        <option value="basic">Basic</option>
                        <option value="pro">Pro</option>
                        <option value="enterprise">Enterprise</option>
                    </select>
                </div>

                <div class="form-group">
                    <label>Logo (dejar vacío para no cambiar)</label>
                    <input type="file" name="logo" accept="image/*">
                </div>

                <div class="form-group">
                    <label>Color primario</label>
                    <input type="color" name="color_primary" id="edit_color_p" value="#5b4bff">
                </div>

                <div class="form-group">
                    <label>Color secundario</label>
                    <input type="color" name="color_secondary" id="edit_color_s" value="#7b61ff">
                </div>

                <div class="form-group">
                    <label>Color sidebar</label>
                    <input type="color" name="color_sidebar" id="edit_color_sb" value="#02122c">
                </div>

                <div class="form-group">
                    <label>Estado</label>
                    <select name="is_active" id="edit_active">
                        <option value="1">Activa</option>
                        <option value="0">Inactiva</option>
                    </select>
                </div>

            </div>

            <div style="font-size:15px;font-weight:800;margin-bottom:12px;">Módulos</div>

            <div class="modules-grid" id="edit_modules">
                <?php foreach($all_modules as $key => $label): ?>
                <label class="module-toggle">
                    <input type="checkbox" name="mod_<?= $key ?>" value="1" id="emod_<?= $key ?>">
                    <?= $label ?>
                </label>
                <?php endforeach; ?>
            </div>

            <button type="submit" class="btn-save">Guardar cambios</button>

        </form>

    </div>
</div>

<script>
function openEdit(company, activeMods){
    document.getElementById('edit_company_id').value = company.id;
    document.getElementById('edit_name').value        = company.name;
    document.getElementById('edit_plan').value        = company.plan;
    document.getElementById('edit_color_p').value     = company.color_primary  || '#5b4bff';
    document.getElementById('edit_color_s').value     = company.color_secondary|| '#7b61ff';
    document.getElementById('edit_color_sb').value    = company.color_sidebar  || '#02122c';
    document.getElementById('edit_active').value      = company.is_active;

    // Módulos
    const allMods = <?= json_encode(array_keys($all_modules)) ?>;
    allMods.forEach(m => {
        const el = document.getElementById('emod_'+m);
        if(el) el.checked = activeMods.includes(m);
    });

    document.getElementById('editModal').classList.add('open');
}

function closeEdit(){
    document.getElementById('editModal').classList.remove('open');
}

// Auto-generar slug desde nombre
document.querySelector('input[name="name"]').addEventListener('input', function(){
    const slug = this.value
        .toLowerCase()
        .replace(/[^a-z0-9]+/g,'-')
        .replace(/^-|-$/g,'');
    document.querySelector('input[name="slug"]').value = slug;
});

// Cerrar modal al click fuera
document.getElementById('editModal').addEventListener('click', function(e){
    if(e.target === this) closeEdit();
});
</script>

</body>
</html>
