<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }

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

$db  = DB::connect();
$tid = (int) $_SESSION['tenant_id'];
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

// Verificar onboarding completo
$stmt = $db->prepare("SELECT onboarding_status FROM tenants WHERE id = :t AND deleted_at IS NULL LIMIT 1");
$stmt->execute([':t' => $tid]);
if ($stmt->fetchColumn() !== 'live') {
    header('Location: /onboarding');
    exit;
}

// Datos del tenant
$stmt = $db->prepare("SELECT * FROM tenants WHERE id = :t AND deleted_at IS NULL LIMIT 1");
$stmt->execute([':t' => $tid]);
$tenant = $stmt->fetch() ?: [];

// Vale config (horarios, greeting, tone)
$stmt = $db->prepare("SELECT * FROM vale_config WHERE tenant_id = :t LIMIT 1");
$stmt->execute([':t' => $tid]);
$valeConfig = $stmt->fetch() ?: [];

// Servicios activos
$stmt = $db->prepare("SELECT * FROM services WHERE tenant_id = :t AND active = 1 ORDER BY id");
$stmt->execute([':t' => $tid]);
$services = $stmt->fetchAll();

// Servicios inactivos (archivados)
$stmt = $db->prepare("SELECT * FROM services WHERE tenant_id = :t AND active = 0 ORDER BY id");
$stmt->execute([':t' => $tid]);
$servicesArchived = $stmt->fetchAll();

// Staff (tabla puede no existir todavía)
$staff = [];
try {
    $stmt = $db->prepare("SELECT * FROM staff WHERE tenant_id = :t AND activo = 1 ORDER BY id");
    $stmt->execute([':t' => $tid]);
    $staff = $stmt->fetchAll();
} catch (Throwable $e) { /* tabla aún no migrada */ }

// Horarios (texto libre en vale_config.hours_json)
$horasTexto = '';
if (!empty($valeConfig['hours_json'])) {
    $decoded = json_decode($valeConfig['hours_json'], true);
    $horasTexto = is_array($decoded) ? ($decoded['texto'] ?? '') : '';
}

// Flash message
$flash = $_SESSION['negocio_flash'] ?? '';
unset($_SESSION['negocio_flash']);

// POST: actualizar info del negocio (formulario manual secundario)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'update_info') {
        $name   = mb_substr(trim($_POST['name']        ?? ''), 0, 160);
        $ciudad = mb_substr(trim($_POST['ciudad']      ?? ''), 0, 80);
        $dir    = mb_substr(trim($_POST['direccion']   ?? ''), 0, 255);
        $tel    = mb_substr(trim($_POST['telefono']    ?? ''), 0, 32);
        $desc   = mb_substr(trim($_POST['descripcion'] ?? ''), 0, 500);
        if ($name !== '') {
            $db->prepare(
                "UPDATE tenants SET name = :n, ciudad = :c, direccion = :d, telefono = :p, descripcion = :desc WHERE id = :t"
            )->execute([
                ':n' => $name, ':c' => $ciudad ?: null, ':d' => $dir ?: null,
                ':p' => $tel ?: null, ':desc' => $desc ?: null, ':t' => $tid,
            ]);
            $_SESSION['tenant_name'] = $name;
        }
        $_SESSION['negocio_flash'] = 'Información actualizada.';
    } elseif ($action === 'add_service') {
        $nombre = mb_substr(trim($_POST['nombre'] ?? ''), 0, 120);
        $dur    = is_numeric($_POST['duracion_min'] ?? '') ? (int)$_POST['duracion_min'] : null;
        $precio = is_numeric($_POST['precio']       ?? '') ? (float)$_POST['precio']     : null;
        if ($nombre !== '') {
            $db->prepare("INSERT INTO services (tenant_id, name, duration_min, price_min, price_max, active) VALUES (:t,:n,:d,:p,:p,1)")
               ->execute([':t' => $tid, ':n' => $nombre, ':d' => $dur, ':p' => $precio]);
        }
        $_SESSION['negocio_flash'] = 'Servicio agregado.';
    } elseif ($action === 'delete_service') {
        $sid = (int)($_POST['service_id'] ?? 0);
        if ($sid) {
            $db->prepare("UPDATE services SET active = 0 WHERE id = :s AND tenant_id = :t")
               ->execute([':s' => $sid, ':t' => $tid]);
        }
        $_SESSION['negocio_flash'] = 'Servicio archivado.';
    } elseif ($action === 'update_hours') {
        $horas = mb_substr(trim($_POST['horarios'] ?? ''), 0, 400);
        $db->prepare("INSERT INTO vale_config (tenant_id, hours_json) VALUES (:t,:h) ON DUPLICATE KEY UPDATE hours_json = VALUES(hours_json)")
           ->execute([':t' => $tid, ':h' => json_encode(['texto' => $horas], JSON_UNESCAPED_UNICODE)]);
        $_SESSION['negocio_flash'] = 'Horarios actualizados.';

    } elseif ($action === 'upload_asset') {
        $assetType = in_array($_POST['asset_type'] ?? '', ['logo', 'banner'], true)
            ? $_POST['asset_type'] : null;
        $file = $_FILES['asset'] ?? null;

        if (!$assetType || !$file || ($file['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) {
            $_SESSION['negocio_flash'] = 'Error: seleccioná un archivo válido.';
        } else {
            $maxBytes = $assetType === 'logo' ? 2 * 1024 * 1024 : 5 * 1024 * 1024;
            if ($file['size'] > $maxBytes) {
                $_SESSION['negocio_flash'] = $assetType === 'logo'
                    ? 'Logo muy grande (máx 2 MB).' : 'Portada muy grande (máx 5 MB).';
            } else {
                $finfo    = new finfo(FILEINFO_MIME_TYPE);
                $mime     = $finfo->file($file['tmp_name']);
                $mimeExts = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp'];
                if (!isset($mimeExts[$mime])) {
                    $_SESSION['negocio_flash'] = 'Solo se aceptan imágenes JPG, PNG o WebP.';
                } else {
                    $dir  = dirname(__DIR__, 2) . '/public/uploads/tenants/' . $tid;
                    if (!is_dir($dir)) { mkdir($dir, 0755, true); }
                    $ext  = $mimeExts[$mime];
                    $file_name = $assetType . '.' . $ext;
                    $dest = $dir . '/' . $file_name;
                    if (!move_uploaded_file($file['tmp_name'], $dest)) {
                        $_SESSION['negocio_flash'] = 'Error al guardar el archivo.';
                    } else {
                        $url = '/uploads/tenants/' . $tid . '/' . $file_name;
                        $col = $assetType === 'logo' ? 'logo_url' : 'banner_url';
                        $db->prepare("UPDATE tenants SET {$col} = :u WHERE id = :t")
                           ->execute([':u' => $url, ':t' => $tid]);
                        // Extracción automática de colores al subir el logo
                        if ($assetType === 'logo') {
                            _negocioExtractColors($db, $tid, $dest);
                        }
                        $_SESSION['negocio_flash'] = $assetType === 'logo'
                            ? 'Logo actualizado. Colores extraídos con IA.' : 'Portada actualizada.';
                    }
                }
            }
        }

    } elseif ($action === 'update_colors') {
        $primary = trim($_POST['color_primario'] ?? '');
        $accent  = trim($_POST['color_acento']   ?? '');
        if (preg_match('/^#[0-9A-Fa-f]{6}$/', $primary)) {
            $textoCta = _negocioWcagTextColor($primary);
            $accentVal = preg_match('/^#[0-9A-Fa-f]{6}$/', $accent) ? $accent : null;
            $db->prepare("UPDATE tenants SET color_primario = :p, color_acento = :a, color_texto_cta = :t WHERE id = :id")
               ->execute([':p' => $primary, ':a' => $accentVal, ':t' => $textoCta, ':id' => $tid]);
            $_SESSION['negocio_flash'] = 'Colores actualizados.';
        } else {
            $_SESSION['negocio_flash'] = 'Color primario no válido.';
        }

    } elseif ($action === 'extract_colors') {
        // AJAX: extrae colores del logo vía Gemini Vision y retorna JSON
        header('Content-Type: application/json; charset=utf-8');
        $stmt = $db->prepare("SELECT logo_url FROM tenants WHERE id = :t AND deleted_at IS NULL LIMIT 1");
        $stmt->execute([':t' => $tid]);
        $logoUrl = (string)$stmt->fetchColumn();
        if (!$logoUrl) {
            echo json_encode(['ok' => false, 'error' => 'Primero subí un logo.']); exit;
        }
        $logoPath = dirname(__DIR__, 2) . '/public' . parse_url($logoUrl, PHP_URL_PATH);
        if (!file_exists($logoPath)) {
            echo json_encode(['ok' => false, 'error' => 'Archivo no encontrado.']); exit;
        }
        $colors = _negocioExtractColors($db, $tid, $logoPath);
        echo json_encode($colors ? ['ok' => true, 'colors' => $colors] : ['ok' => false, 'error' => 'No se pudo extraer la paleta. Verificá la clave Gemini.']);
        exit;
    }

    header('Location: /negocio');
    exit;
}

// ── Helpers de branding ───────────────────────────────────────────────────────

function _negocioWcagTextColor(string $hex): string {
    $hex = ltrim($hex, '#');
    $lin = function(float $c): float {
        return $c <= 0.03928 ? $c / 12.92 : (($c + 0.055) / 1.055) ** 2.4;
    };
    $r = $lin(hexdec(substr($hex,0,2)) / 255);
    $g = $lin(hexdec(substr($hex,2,2)) / 255);
    $b = $lin(hexdec(substr($hex,4,2)) / 255);
    $lum = 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
    // Contraste con blanco: 1.05 / (lum + 0.05). WCAG AA mínimo = 4.5
    return (1.05 / ($lum + 0.05)) >= 4.5 ? '#ffffff' : '#211C16';
}

function _negocioExtractColors(PDO $db, int $tid, string $imagePath): ?array {
    $apiKey = getenv('GEMINI_API_KEY');
    if (!$apiKey || !file_exists($imagePath)) return null;
    try {
        $imageData = base64_encode(file_get_contents($imagePath));
        $mime      = (new finfo(FILEINFO_MIME_TYPE))->file($imagePath);
        $prompt    = 'Analizá este logo de negocio. Respondé SOLO con JSON válido (sin texto extra):'
            . ' {"primary":"#RRGGBB","accent":"#RRGGBB"}'
            . ' primary = color dominante de la marca, accent = color secundario.'
            . ' Si el logo es monocromático usá #A23D2C como primary y #DDA02C como accent.';
        $body = json_encode([
            'contents' => [['role' => 'user', 'parts' => [
                ['inline_data' => ['mime_type' => $mime, 'data' => $imageData]],
                ['text' => $prompt],
            ]]],
            'generationConfig' => ['temperature' => 0.1, 'maxOutputTokens' => 60],
        ]);
        $model = 'gemini-2.0-flash';
        $ch = curl_init("https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$apiKey}");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body, CURLOPT_TIMEOUT => 10,
            CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
        ]);
        $resp   = curl_exec($ch);
        curl_close($ch);
        $data   = json_decode($resp, true);
        $text   = trim($data['candidates'][0]['content']['parts'][0]['text'] ?? '');
        if (!preg_match('/\{[^}]+\}/s', $text, $m)) return null;
        $colors = json_decode($m[0], true);
        if (!isset($colors['primary']) || !preg_match('/^#[0-9A-Fa-f]{6}$/', $colors['primary'])) return null;
        $primary   = $colors['primary'];
        $accent    = (isset($colors['accent']) && preg_match('/^#[0-9A-Fa-f]{6}$/', $colors['accent']))
            ? $colors['accent'] : '#DDA02C';
        $textoCta  = _negocioWcagTextColor($primary);
        $db->prepare("UPDATE tenants SET color_primario = :p, color_acento = :a, color_texto_cta = :t WHERE id = :id")
           ->execute([':p' => $primary, ':a' => $accent, ':t' => $textoCta, ':id' => $tid]);
        return ['primary' => $primary, 'accent' => $accent, 'text_cta' => $textoCta];
    } catch (Throwable $_e) {
        error_log('[negocio:extractColors] ' . $_e->getMessage());
        return null;
    }
}

require dirname(__DIR__) . '/views/negocio.php';
