<?php

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

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

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

// Asegurar tabla system_settings
$conn->query("
CREATE TABLE IF NOT EXISTS system_settings (
    id            INT(11)      NOT NULL AUTO_INCREMENT,
    setting_key   VARCHAR(255) NOT NULL UNIQUE,
    setting_value LONGTEXT     DEFAULT NULL,
    updated_at    TIMESTAMP    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
");

if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $keys = [
        'anthropic_api_key',
        'vicidial_url',
        'vicidial_user',
        'vicidial_pass',
        'whatsapp_token',
        'whatsapp_phone_id',
        'smtp_host',
        'smtp_port',
        'smtp_user',
        'smtp_pass',
        'smtp_from',
    ];
    foreach($keys as $k){
        $v = trim($_POST[$k] ?? '');
        $ke = mysqli_real_escape_string($conn, $k);
        $ve = mysqli_real_escape_string($conn, $v);
        $conn->query("INSERT INTO system_settings (setting_key, setting_value) VALUES ('$ke','$ve')
                      ON DUPLICATE KEY UPDATE setting_value='$ve'");
    }
    $success = "Configuración guardada correctamente.";
}

// Leer settings actuales
$settings = [];
$q = $conn->query("SELECT setting_key, setting_value FROM system_settings");
while($r = $q->fetch_assoc()) $settings[$r['setting_key']] = $r['setting_value'];

function sv($settings, $key){ return htmlspecialchars($settings[$key] ?? ''); }

?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Integraciones</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; }
.section-card{ background:#fff; border-radius:20px; padding:28px; box-shadow:0 4px 20px rgba(0,0,0,.06); margin-bottom:24px; border-left:4px solid #5b4bff; }
.section-card.green{ border-color:#10b981; }
.section-card.orange{ border-color:#f59e0b; }
.section-card.blue{ border-color:#3b82f6; }
.section-title{ font-size:18px; font-weight:800; color:#02122c; margin-bottom:6px; display:flex; align-items:center; gap:10px; }
.section-desc{ font-size:13px; color:#64748b; margin-bottom:20px; }
.form-grid{ display:grid; grid-template-columns:repeat(auto-fit,minmax(240px,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{ 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:focus{ outline:none; border-color:#5b4bff; background:#fff; }
.status-badge{ display:inline-block; padding:4px 12px; border-radius:20px; font-size:12px; font-weight:700; }
.status-ok{ background:#dcfce7; color:#166534; }
.status-empty{ background:#f1f5f9; color:#94a3b8; }
.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; margin-top:8px; }
.alert-success{ background:#dcfce7; color:#166534; border-radius:12px; padding:14px 18px; margin-bottom:20px; font-weight:600; }
.tip{ background:#f8fafc; border-radius:10px; padding:12px 16px; font-size:13px; color:#64748b; margin-top:8px; }
.tip a{ color:#5b4bff; font-weight:700; }
</style>
</head>
<body>
<?php include("../includes/sidebar.php"); ?>
<div class="content-area">

    <div class="page-title">🔗 Integraciones</div>
    <div class="page-subtitle">Conecta el CRM con servicios externos</div>

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

    <form method="POST">

        <!-- ANTHROPIC / IA -->
        <div class="section-card">
            <div class="section-title">
                🤖 Anthropic IA
                <?php if(!empty($settings['anthropic_api_key'])): ?>
                <span class="status-badge status-ok">✅ Configurada</span>
                <?php else: ?>
                <span class="status-badge status-empty">Sin configurar</span>
                <?php endif; ?>
            </div>
            <div class="section-desc">Necesaria para Comparativas de Factura, AI Assistant y análisis inteligente.</div>
            <div class="form-grid">
                <div class="form-group" style="grid-column:1/-1">
                    <label>API Key de Anthropic</label>
                    <input type="password" name="anthropic_api_key" value="<?= sv($settings,'anthropic_api_key') ?>" placeholder="sk-ant-api03-...">
                </div>
            </div>
            <div class="tip">Consigue tu API key en <a href="https://console.anthropic.com" target="_blank">console.anthropic.com</a> → API Keys → Create Key</div>
        </div>

        <!-- VICIDIAL -->
        <div class="section-card green">
            <div class="section-title">
                📞 VICIdial
                <?php if(!empty($settings['vicidial_url'])): ?>
                <span class="status-badge status-ok">✅ Configurado</span>
                <?php else: ?>
                <span class="status-badge status-empty">Sin configurar</span>
                <?php endif; ?>
            </div>
            <div class="section-desc">Conexión con el servidor VICIdial para el marcador y gestión de llamadas.</div>
            <div class="form-grid">
                <div class="form-group">
                    <label>URL VICIdial</label>
                    <input type="text" name="vicidial_url" value="<?= sv($settings,'vicidial_url') ?>" placeholder="http://192.168.40.13">
                </div>
                <div class="form-group">
                    <label>Usuario admin</label>
                    <input type="text" name="vicidial_user" value="<?= sv($settings,'vicidial_user') ?>" placeholder="6666">
                </div>
                <div class="form-group">
                    <label>Contraseña</label>
                    <input type="password" name="vicidial_pass" value="<?= sv($settings,'vicidial_pass') ?>" placeholder="••••••••">
                </div>
            </div>
        </div>

        <!-- WHATSAPP -->
        <div class="section-card orange">
            <div class="section-title">
                💬 WhatsApp Business API
                <?php if(!empty($settings['whatsapp_token'])): ?>
                <span class="status-badge status-ok">✅ Configurado</span>
                <?php else: ?>
                <span class="status-badge status-empty">Sin configurar</span>
                <?php endif; ?>
            </div>
            <div class="section-desc">Para enviar mensajes y facturas simuladas directamente desde el CRM.</div>
            <div class="form-grid">
                <div class="form-group">
                    <label>Token de acceso</label>
                    <input type="password" name="whatsapp_token" value="<?= sv($settings,'whatsapp_token') ?>" placeholder="EAAxxxxxxxxx">
                </div>
                <div class="form-group">
                    <label>Phone Number ID</label>
                    <input type="text" name="whatsapp_phone_id" value="<?= sv($settings,'whatsapp_phone_id') ?>" placeholder="1234567890">
                </div>
            </div>
            <div class="tip">Configura desde <a href="https://developers.facebook.com/apps" target="_blank">Meta for Developers</a> → WhatsApp → API Setup</div>
        </div>

        <!-- EMAIL / SMTP -->
        <div class="section-card blue">
            <div class="section-title">
                📧 Email / SMTP
                <?php if(!empty($settings['smtp_host'])): ?>
                <span class="status-badge status-ok">✅ Configurado</span>
                <?php else: ?>
                <span class="status-badge status-empty">Sin configurar</span>
                <?php endif; ?>
            </div>
            <div class="section-desc">Para enviar correos desde el CRM — notificaciones, facturas, seguimientos.</div>
            <div class="form-grid">
                <div class="form-group">
                    <label>Servidor SMTP</label>
                    <input type="text" name="smtp_host" value="<?= sv($settings,'smtp_host') ?>" placeholder="smtp.gmail.com">
                </div>
                <div class="form-group">
                    <label>Puerto</label>
                    <input type="text" name="smtp_port" value="<?= sv($settings,'smtp_port') ?>" placeholder="587">
                </div>
                <div class="form-group">
                    <label>Usuario</label>
                    <input type="text" name="smtp_user" value="<?= sv($settings,'smtp_user') ?>" placeholder="correo@empresa.com">
                </div>
                <div class="form-group">
                    <label>Contraseña</label>
                    <input type="password" name="smtp_pass" value="<?= sv($settings,'smtp_pass') ?>" placeholder="••••••••">
                </div>
                <div class="form-group">
                    <label>Remitente (From)</label>
                    <input type="text" name="smtp_from" value="<?= sv($settings,'smtp_from') ?>" placeholder="CRM Wolfxell <crm@wolfxell.com>">
                </div>
            </div>
        </div>

        <button type="submit" class="btn-save">💾 Guardar todas las integraciones</button>

    </form>

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