<?php

session_start();

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

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

requirePermission('can_manage_campaigns');

/*
|--------------------------------------------------------------------------
| CREAR TABLAS SI NO EXISTEN
|--------------------------------------------------------------------------
*/

$conn->query("
CREATE TABLE IF NOT EXISTS vici_trunks (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    name        VARCHAR(100) NOT NULL,
    sip_host    VARCHAR(200) NOT NULL,
    sip_user    VARCHAR(100) NOT NULL,
    sip_pass    VARCHAR(100) NOT NULL,
    sip_port    INT DEFAULT 5060,
    active      TINYINT DEFAULT 1,
    created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS vici_dids (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    trunk_id    INT,
    number      VARCHAR(30) NOT NULL,
    label       VARCHAR(100),
    campaign_id INT,
    active      TINYINT DEFAULT 1,
    created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS vici_dispositions (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    campaign_id INT,
    code        VARCHAR(20) NOT NULL,
    label       VARCHAR(100) NOT NULL,
    color       VARCHAR(10) DEFAULT '#64748b',
    is_sale     TINYINT DEFAULT 0,
    rellamar    TINYINT DEFAULT 0,
    active      TINYINT DEFAULT 1
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS vici_campaign_config (
    id              INT AUTO_INCREMENT PRIMARY KEY,
    campaign_id     INT UNIQUE,
    vici_campaign   VARCHAR(50),
    vici_list       VARCHAR(50),
    trunk_id        INT,
    dial_mode       ENUM('manual','preview','progressive','predictive') DEFAULT 'manual',
    caller_id_mode  ENUM('fixed','rotate') DEFAULT 'fixed',
    max_lines       INT DEFAULT 1,
    inbound         TINYINT DEFAULT 0,
    inbound_did     VARCHAR(30),
    updated_at      TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS vici_settings (
    id          INT AUTO_INCREMENT PRIMARY KEY,
    vici_url    VARCHAR(200),
    vici_user   VARCHAR(100),
    vici_pass   VARCHAR(100),
    vici_source VARCHAR(50) DEFAULT 'crm'
)
");

// Insertar fila de settings si no existe
$conn->query("
INSERT IGNORE INTO vici_settings (id, vici_url, vici_user, vici_pass)
VALUES (1, '', '', '')
");

/*
|--------------------------------------------------------------------------
| GUARDAR SETTINGS GENERALES
|--------------------------------------------------------------------------
*/

$success = '';
$error   = '';
$tab     = $_GET['tab'] ?? 'general';

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

    $action = $_POST['action'] ?? '';

    // --- Guardar configuración general VICIdial ---
    if($action === 'save_general'){

        $url    = $conn->real_escape_string(trim($_POST['vici_url']));
        $user   = $conn->real_escape_string(trim($_POST['vici_user']));
        $pass   = $conn->real_escape_string(trim($_POST['vici_pass']));
        $source = $conn->real_escape_string(trim($_POST['vici_source']));

        $conn->query("
        UPDATE vici_settings SET
            vici_url    = '$url',
            vici_user   = '$user',
            vici_pass   = '$pass',
            vici_source = '$source'
        WHERE id = 1
        ");

        $success = 'Configuración guardada.';
        $tab = 'general';

    }

    // --- Agregar troncal ---
    if($action === 'add_trunk'){

        $name = $conn->real_escape_string(trim($_POST['trunk_name']));
        $host = $conn->real_escape_string(trim($_POST['sip_host']));
        $user = $conn->real_escape_string(trim($_POST['sip_user']));
        $pass = $conn->real_escape_string(trim($_POST['sip_pass']));
        $port = intval($_POST['sip_port'] ?? 5060);

        $conn->query("
        INSERT INTO vici_trunks (name, sip_host, sip_user, sip_pass, sip_port)
        VALUES ('$name','$host','$user','$pass','$port')
        ");

        $success = 'Troncal añadida.';
        $tab = 'trunks';

    }

    // --- Eliminar troncal ---
    if($action === 'delete_trunk'){
        $id = intval($_POST['trunk_id']);
        $conn->query("DELETE FROM vici_trunks WHERE id='$id'");
        $success = 'Troncal eliminada.';
        $tab = 'trunks';
    }

    // --- Agregar DID ---
    if($action === 'add_did'){

        $trunk_id    = intval($_POST['trunk_id']);
        $number      = $conn->real_escape_string(trim($_POST['did_number']));
        $label       = $conn->real_escape_string(trim($_POST['did_label']));
        $campaign_id = intval($_POST['campaign_id'] ?? 0);

        $conn->query("
        INSERT INTO vici_dids (trunk_id, number, label, campaign_id)
        VALUES ('$trunk_id','$number','$label','$campaign_id')
        ");

        $success = 'DID añadido.';
        $tab = 'dids';

    }

    // --- Eliminar DID ---
    if($action === 'delete_did'){
        $id = intval($_POST['did_id']);
        $conn->query("DELETE FROM vici_dids WHERE id='$id'");
        $success = 'DID eliminado.';
        $tab = 'dids';
    }

    // --- Guardar configuración de campaña ---
    if($action === 'save_campaign_config'){

        $campaign_id   = intval($_POST['campaign_id']);
        $vici_campaign = $conn->real_escape_string(trim($_POST['vici_campaign']));
        $vici_list     = $conn->real_escape_string(trim($_POST['vici_list']));
        $trunk_id      = intval($_POST['trunk_id']);
        $dial_mode     = $conn->real_escape_string($_POST['dial_mode']);
        $caller_mode   = $conn->real_escape_string($_POST['caller_id_mode']);
        $max_lines     = intval($_POST['max_lines'] ?? 1);
        $inbound       = isset($_POST['inbound']) ? 1 : 0;
        $inbound_did   = $conn->real_escape_string(trim($_POST['inbound_did'] ?? ''));

        $conn->query("
        INSERT INTO vici_campaign_config
            (campaign_id, vici_campaign, vici_list, trunk_id, dial_mode, caller_id_mode, max_lines, inbound, inbound_did)
        VALUES
            ('$campaign_id','$vici_campaign','$vici_list','$trunk_id','$dial_mode','$caller_mode','$max_lines','$inbound','$inbound_did')
        ON DUPLICATE KEY UPDATE
            vici_campaign  = '$vici_campaign',
            vici_list      = '$vici_list',
            trunk_id       = '$trunk_id',
            dial_mode      = '$dial_mode',
            caller_id_mode = '$caller_mode',
            max_lines      = '$max_lines',
            inbound        = '$inbound',
            inbound_did    = '$inbound_did'
        ");

        $success = 'Configuración de campaña guardada.';
        $tab = 'campaigns';

    }

    // --- Agregar disposición ---
    if($action === 'add_disposition'){

        $campaign_id = intval($_POST['campaign_id']);
        $code        = $conn->real_escape_string(strtoupper(trim($_POST['disp_code'])));
        $label       = $conn->real_escape_string(trim($_POST['disp_label']));
        $color       = $conn->real_escape_string($_POST['disp_color'] ?? '#64748b');
        $is_sale     = isset($_POST['is_sale']) ? 1 : 0;
        $rellamar    = isset($_POST['rellamar']) ? 1 : 0;

        $conn->query("
        INSERT INTO vici_dispositions (campaign_id, code, label, color, is_sale, rellamar)
        VALUES ('$campaign_id','$code','$label','$color','$is_sale','$rellamar')
        ");

        $success = 'Tipificación añadida.';
        $tab = 'dispositions';

    }

    // --- Eliminar disposición ---
    if($action === 'delete_disposition'){
        $id = intval($_POST['disp_id']);
        $conn->query("DELETE FROM vici_dispositions WHERE id='$id'");
        $success = 'Tipificación eliminada.';
        $tab = 'dispositions';
    }

}

/*
|--------------------------------------------------------------------------
| CARGAR DATOS
|--------------------------------------------------------------------------
*/

$vici_settings  = $conn->query("SELECT * FROM vici_settings WHERE id=1")->fetch_assoc();
$trunks         = $conn->query("SELECT * FROM vici_trunks ORDER BY name ASC");
$dids           = $conn->query("SELECT d.*, t.name AS trunk_name, c.campaign_name FROM vici_dids d LEFT JOIN vici_trunks t ON t.id=d.trunk_id LEFT JOIN campaigns c ON c.id=d.campaign_id ORDER BY d.number ASC");
$campaigns      = $conn->query("SELECT * FROM campaigns ORDER BY campaign_name ASC");
$dispositions   = $conn->query("SELECT vd.*, c.campaign_name FROM vici_dispositions vd LEFT JOIN campaigns c ON c.id=vd.campaign_id ORDER BY c.campaign_name, vd.code ASC");
$campaign_cfgs  = $conn->query("SELECT vc.*, c.campaign_name, t.name AS trunk_name FROM vici_campaign_config vc LEFT JOIN campaigns c ON c.id=vc.campaign_id LEFT JOIN vici_trunks t ON t.id=vc.trunk_id ORDER BY c.campaign_name ASC");

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

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

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

.page-subtitle{
    color:#64748b;
    margin-bottom:30px;
}

.white-card{
    background:#fff;
    border-radius:24px;
    padding:30px;
    margin-bottom:25px;
    box-shadow:0 10px 30px rgba(15,23,42,.05);
}

.tabs{
    display:flex;
    gap:10px;
    margin-bottom:30px;
    flex-wrap:wrap;
}

.tab-btn{
    height:44px;
    padding:0 20px;
    border-radius:12px;
    border:none;
    font-weight:700;
    font-size:14px;
    cursor:pointer;
    background:#f1f5f9;
    color:#64748b;
    text-decoration:none;
    display:inline-flex;
    align-items:center;
}

.tab-btn.active{
    background:linear-gradient(90deg,#5b4bff,#7b61ff);
    color:#fff;
}

.form-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(240px,1fr));
    gap:18px;
}

.form-group{
    display:flex;
    flex-direction:column;
}

.form-group label{
    font-size:13px;
    font-weight:700;
    color:#64748b;
    margin-bottom:8px;
    text-transform:uppercase;
}

.form-control{
    height:48px;
    border:none;
    background:#f3f5fa;
    border-radius:12px;
    padding:0 14px;
    font-size:14px;
}

select.form-control{
    cursor:pointer;
}

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

.btn-danger{
    background:#fee2e2;
    color:#dc2626;
    border:none;
    height:34px;
    padding:0 14px;
    border-radius:8px;
    font-weight:700;
    cursor:pointer;
    font-size:13px;
}

.crm-table{
    width:100%;
    border-collapse:collapse;
}

.crm-table th{
    text-align:left;
    padding:14px 16px;
    border-bottom:2px solid #f1f5f9;
    font-size:12px;
    font-weight:700;
    color:#64748b;
    text-transform:uppercase;
}

.crm-table td{
    padding:14px 16px;
    border-bottom:1px solid #f8fafc;
    font-size:14px;
}

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

.badge{
    display:inline-block;
    padding:4px 12px;
    border-radius:20px;
    font-size:12px;
    font-weight:700;
}

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

.checkbox-row{
    display:flex;
    align-items:center;
    gap:10px;
    margin-top:8px;
}

.checkbox-row input{
    width:18px;
    height:18px;
    cursor:pointer;
}

.checkbox-row label{
    font-size:14px;
    font-weight:600;
    color:#02122c;
    cursor:pointer;
}

.color-input{
    height:48px;
    border:none;
    background:#f3f5fa;
    border-radius:12px;
    padding:4px 8px;
    cursor:pointer;
    width:100%;
}

</style>
</head>
<body>

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

<div class="content-area">

    <div class="page-title">Telefonía</div>
    <div class="page-subtitle">Configuración completa de llamadas, troncales y marcador</div>

    <?php if($success): ?>
    <div class="success-box">✓ <?= htmlspecialchars($success) ?></div>
    <?php endif; ?>

    <!-- TABS -->
    <div class="tabs">
        <a href="?tab=general"      class="tab-btn <?= $tab=='general'      ? 'active':'' ?>">⚙️ General</a>
        <a href="?tab=trunks"       class="tab-btn <?= $tab=='trunks'       ? 'active':'' ?>">🔗 Troncales</a>
        <a href="?tab=dids"         class="tab-btn <?= $tab=='dids'         ? 'active':'' ?>">📞 DIDs</a>
        <a href="?tab=campaigns"    class="tab-btn <?= $tab=='campaigns'    ? 'active':'' ?>">📋 Campañas</a>
        <a href="?tab=dispositions" class="tab-btn <?= $tab=='dispositions' ? 'active':'' ?>">🏷️ Tipificaciones</a>
    </div>

    <?php /* ===================== TAB GENERAL ===================== */ ?>
    <?php if($tab === 'general'): ?>

    <div class="white-card">
        <div class="section-title">Conexión VICIdial</div>
        <form method="POST">
        <input type="hidden" name="action" value="save_general">
        <div class="form-grid">
            <div class="form-group">
                <label>URL VICIdial</label>
                <input type="text" name="vici_url" class="form-control"
                    value="<?= htmlspecialchars($vici_settings['vici_url'] ?? '') ?>"
                    placeholder="http://192.168.1.100">
            </div>
            <div class="form-group">
                <label>Usuario admin</label>
                <input type="text" name="vici_user" class="form-control"
                    value="<?= htmlspecialchars($vici_settings['vici_user'] ?? '') ?>"
                    placeholder="admin">
            </div>
            <div class="form-group">
                <label>Contraseña</label>
                <input type="password" name="vici_pass" class="form-control"
                    value="<?= htmlspecialchars($vici_settings['vici_pass'] ?? '') ?>">
            </div>
            <div class="form-group">
                <label>Source ID</label>
                <input type="text" name="vici_source" class="form-control"
                    value="<?= htmlspecialchars($vici_settings['vici_source'] ?? 'crm') ?>"
                    placeholder="crm">
            </div>
        </div>
        <button type="submit" class="btn-save">Guardar conexión</button>
        </form>
    </div>

    <?php endif; ?>

    <?php /* ===================== TAB TRONCALES ===================== */ ?>
    <?php if($tab === 'trunks'): ?>

    <div class="white-card">
        <div class="section-title">Añadir troncal SIP</div>
        <form method="POST">
        <input type="hidden" name="action" value="add_trunk">
        <div class="form-grid">
            <div class="form-group">
                <label>Nombre</label>
                <input type="text" name="trunk_name" class="form-control" placeholder="Carrier España" required>
            </div>
            <div class="form-group">
                <label>Host SIP</label>
                <input type="text" name="sip_host" class="form-control" placeholder="sip.carrier.com" required>
            </div>
            <div class="form-group">
                <label>Usuario SIP</label>
                <input type="text" name="sip_user" class="form-control" placeholder="usuario123" required>
            </div>
            <div class="form-group">
                <label>Contraseña SIP</label>
                <input type="password" name="sip_pass" class="form-control" required>
            </div>
            <div class="form-group">
                <label>Puerto</label>
                <input type="number" name="sip_port" class="form-control" value="5060">
            </div>
        </div>
        <button type="submit" class="btn-save">Añadir troncal</button>
        </form>
    </div>

    <div class="white-card">
        <div class="section-title">Troncales configuradas</div>
        <table class="crm-table">
            <thead>
                <tr>
                    <th>Nombre</th><th>Host</th><th>Usuario</th><th>Puerto</th><th></th>
                </tr>
            </thead>
            <tbody>
            <?php while($t = $trunks->fetch_assoc()): ?>
            <tr>
                <td><strong><?= htmlspecialchars($t['name']) ?></strong></td>
                <td><?= htmlspecialchars($t['sip_host']) ?></td>
                <td><?= htmlspecialchars($t['sip_user']) ?></td>
                <td><?= $t['sip_port'] ?></td>
                <td>
                    <form method="POST" style="display:inline">
                    <input type="hidden" name="action" value="delete_trunk">
                    <input type="hidden" name="trunk_id" value="<?= $t['id'] ?>">
                    <button type="submit" class="btn-danger"
                        onclick="return confirm('¿Eliminar troncal?')">Eliminar</button>
                    </form>
                </td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>

    <?php endif; ?>

    <?php /* ===================== TAB DIDs ===================== */ ?>
    <?php if($tab === 'dids'): ?>

    <div class="white-card">
        <div class="section-title">Añadir DID</div>
        <form method="POST">
        <input type="hidden" name="action" value="add_did">
        <div class="form-grid">
            <div class="form-group">
                <label>Troncal</label>
                <select name="trunk_id" class="form-control" required>
                    <option value="">Seleccionar</option>
                    <?php
                    $trunks2 = $conn->query("SELECT * FROM vici_trunks ORDER BY name ASC");
                    while($t = $trunks2->fetch_assoc()):
                    ?>
                    <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Número DID</label>
                <input type="text" name="did_number" class="form-control" placeholder="34911234567" required>
            </div>
            <div class="form-group">
                <label>Etiqueta</label>
                <input type="text" name="did_label" class="form-control" placeholder="Madrid principal">
            </div>
            <div class="form-group">
                <label>Campaña (opcional)</label>
                <select name="campaign_id" class="form-control">
                    <option value="0">Sin asignar</option>
                    <?php
                    $camps2 = $conn->query("SELECT * FROM campaigns ORDER BY campaign_name ASC");
                    while($c = $camps2->fetch_assoc()):
                    ?>
                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['campaign_name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
        </div>
        <button type="submit" class="btn-save">Añadir DID</button>
        </form>
    </div>

    <div class="white-card">
        <div class="section-title">DIDs configurados</div>
        <table class="crm-table">
            <thead>
                <tr>
                    <th>Número</th><th>Etiqueta</th><th>Troncal</th><th>Campaña</th><th></th>
                </tr>
            </thead>
            <tbody>
            <?php while($d = $dids->fetch_assoc()): ?>
            <tr>
                <td><strong><?= htmlspecialchars($d['number']) ?></strong></td>
                <td><?= htmlspecialchars($d['label'] ?? '—') ?></td>
                <td><?= htmlspecialchars($d['trunk_name'] ?? '—') ?></td>
                <td><?= htmlspecialchars($d['campaign_name'] ?? 'Sin asignar') ?></td>
                <td>
                    <form method="POST" style="display:inline">
                    <input type="hidden" name="action" value="delete_did">
                    <input type="hidden" name="did_id" value="<?= $d['id'] ?>">
                    <button type="submit" class="btn-danger"
                        onclick="return confirm('¿Eliminar DID?')">Eliminar</button>
                    </form>
                </td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>

    <?php endif; ?>

    <?php /* ===================== TAB CAMPAÑAS ===================== */ ?>
    <?php if($tab === 'campaigns'): ?>

    <div class="white-card">
        <div class="section-title">Configurar campaña en el marcador</div>
        <form method="POST">
        <input type="hidden" name="action" value="save_campaign_config">
        <div class="form-grid">
            <div class="form-group">
                <label>Campaña CRM</label>
                <select name="campaign_id" class="form-control" required>
                    <option value="">Seleccionar</option>
                    <?php
                    $camps3 = $conn->query("SELECT * FROM campaigns ORDER BY campaign_name ASC");
                    while($c = $camps3->fetch_assoc()):
                    ?>
                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['campaign_name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="form-group">
                <label>ID Campaña VICIdial</label>
                <input type="text" name="vici_campaign" class="form-control" placeholder="CAMP1">
            </div>
            <div class="form-group">
                <label>ID Lista VICIdial</label>
                <input type="text" name="vici_list" class="form-control" placeholder="998">
            </div>
            <div class="form-group">
                <label>Troncal</label>
                <select name="trunk_id" class="form-control">
                    <option value="0">Predeterminada</option>
                    <?php
                    $trunks3 = $conn->query("SELECT * FROM vici_trunks ORDER BY name ASC");
                    while($t = $trunks3->fetch_assoc()):
                    ?>
                    <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Modo de marcación</label>
                <select name="dial_mode" class="form-control">
                    <option value="manual">Manual</option>
                    <option value="preview">Preview</option>
                    <option value="progressive">Progresivo</option>
                    <option value="predictive">Predictivo</option>
                </select>
            </div>
            <div class="form-group">
                <label>Caller ID</label>
                <select name="caller_id_mode" class="form-control">
                    <option value="fixed">Fijo</option>
                    <option value="rotate">Rotación aleatoria</option>
                </select>
            </div>
            <div class="form-group">
                <label>Líneas por agente (predictivo)</label>
                <input type="number" name="max_lines" class="form-control" value="2" min="1" max="5">
            </div>
            <div class="form-group">
                <label>DID Inbound (si aplica)</label>
                <input type="text" name="inbound_did" class="form-control" placeholder="34911234567">
            </div>
        </div>
        <div class="checkbox-row" style="margin-top:16px">
            <input type="checkbox" name="inbound" id="inbound" value="1">
            <label for="inbound">Activar recepción de llamadas inbound en esta campaña</label>
        </div>
        <button type="submit" class="btn-save">Guardar configuración</button>
        </form>
    </div>

    <div class="white-card">
        <div class="section-title">Campañas configuradas</div>
        <table class="crm-table">
            <thead>
                <tr>
                    <th>Campaña</th><th>VICIdial ID</th><th>Modo</th><th>Troncal</th><th>Inbound</th>
                </tr>
            </thead>
            <tbody>
            <?php while($cfg = $campaign_cfgs->fetch_assoc()): ?>
            <tr>
                <td><strong><?= htmlspecialchars($cfg['campaign_name'] ?? '—') ?></strong></td>
                <td><?= htmlspecialchars($cfg['vici_campaign']) ?></td>
                <td>
                    <span class="badge" style="background:#ede9fe;color:#5b4bff">
                        <?= ucfirst($cfg['dial_mode']) ?>
                    </span>
                </td>
                <td><?= htmlspecialchars($cfg['trunk_name'] ?? 'Predeterminada') ?></td>
                <td>
                    <?php if($cfg['inbound']): ?>
                    <span class="badge" style="background:#dcfce7;color:#16a34a">Sí</span>
                    <?php else: ?>
                    <span class="badge" style="background:#f1f5f9;color:#64748b">No</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>

    <?php endif; ?>

    <?php /* ===================== TAB TIPIFICACIONES ===================== */ ?>
    <?php if($tab === 'dispositions'): ?>

    <div class="white-card">
        <div class="section-title">Añadir tipificación</div>
        <form method="POST">
        <input type="hidden" name="action" value="add_disposition">
        <div class="form-grid">
            <div class="form-group">
                <label>Campaña</label>
                <select name="campaign_id" class="form-control" required>
                    <option value="0">Todas las campañas</option>
                    <?php
                    $camps4 = $conn->query("SELECT * FROM campaigns ORDER BY campaign_name ASC");
                    while($c = $camps4->fetch_assoc()):
                    ?>
                    <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['campaign_name']) ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
            <div class="form-group">
                <label>Código (ej: SALE, NI, NA)</label>
                <input type="text" name="disp_code" class="form-control" placeholder="SALE" required>
            </div>
            <div class="form-group">
                <label>Etiqueta visible</label>
                <input type="text" name="disp_label" class="form-control" placeholder="Venta cerrada" required>
            </div>
            <div class="form-group">
                <label>Color</label>
                <input type="color" name="disp_color" class="color-input" value="#22c55e">
            </div>
        </div>
        <div style="display:flex;gap:24px;margin-top:16px">
            <div class="checkbox-row">
                <input type="checkbox" name="is_sale" id="is_sale" value="1">
                <label for="is_sale">Cuenta como venta</label>
            </div>
            <div class="checkbox-row">
                <input type="checkbox" name="rellamar" id="rellamar" value="1">
                <label for="rellamar">Programar rellamada</label>
            </div>
        </div>
        <button type="submit" class="btn-save">Añadir tipificación</button>
        </form>
    </div>

    <div class="white-card">
        <div class="section-title">Tipificaciones configuradas</div>
        <table class="crm-table">
            <thead>
                <tr>
                    <th>Campaña</th><th>Código</th><th>Etiqueta</th><th>Color</th><th>Venta</th><th>Rellamar</th><th></th>
                </tr>
            </thead>
            <tbody>
            <?php while($d = $dispositions->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($d['campaign_name'] ?? 'Global') ?></td>
                <td><strong><?= htmlspecialchars($d['code']) ?></strong></td>
                <td><?= htmlspecialchars($d['label']) ?></td>
                <td>
                    <span style="display:inline-block;width:20px;height:20px;border-radius:50%;background:<?= htmlspecialchars($d['color']) ?>"></span>
                    <?= htmlspecialchars($d['color']) ?>
                </td>
                <td><?= $d['is_sale'] ? '✅' : '—' ?></td>
                <td><?= $d['rellamar'] ? '🔄' : '—' ?></td>
                <td>
                    <form method="POST" style="display:inline">
                    <input type="hidden" name="action" value="delete_disposition">
                    <input type="hidden" name="disp_id" value="<?= $d['id'] ?>">
                    <button type="submit" class="btn-danger"
                        onclick="return confirm('¿Eliminar?')">Eliminar</button>
                    </form>
                </td>
            </tr>
            <?php endwhile; ?>
            </tbody>
        </table>
    </div>

    <?php endif; ?>

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