<?php
// CORS y headers
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");
date_default_timezone_set('America/Bogota');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

// Conexión (usa tu config existente)
require_once(__DIR__ . '/../config.php');
$mysqli->set_charset("utf8mb4");

// Util: normalizar from a "whatsapp:+XXXXXXXXXXX"
function normalize_from_whatsapp($from) {
    $from = trim($from ?? '');
    if ($from === '') return $from;
    // Quita espacios y asegura el prefijo
    $from = preg_replace('/\s+/', '', $from);
    if (stripos($from, 'whatsapp:') === 0) {
        // ya viene con whatsapp:
        if (strpos($from, 'whatsapp:+') !== 0) {
            $from = 'whatsapp:+' . ltrim(substr($from, 9), '+');
        }
        return $from;
    }
    // si solo viene +123..., anteponer "whatsapp:"
    if ($from[0] === '+') return 'whatsapp:' . $from;
    // si viene dígitos, anteponer todo
    $from = preg_replace('/[^\d+]/', '', $from);
    if ($from[0] !== '+') $from = '+' . $from;
    return 'whatsapp:' . $from;
}

// Leer JSON
$input = json_decode(file_get_contents("php://input"), true);

// Validar
$requeridos = ['slug_tienda','account_sid','auth_token','from_whatsapp'];
foreach ($requeridos as $k) {
    if (!isset($input[$k])) {
        echo json_encode(['success'=>false,'message'=>"Falta parámetro: $k"]); exit;
    }
}

$slug_tienda   = trim($input['slug_tienda']);
$account_sid   = trim($input['account_sid']);
$auth_token    = trim($input['auth_token']);
$from_whatsapp = normalize_from_whatsapp($input['from_whatsapp']);

if ($slug_tienda === '' || $account_sid === '' || $auth_token === '' || $from_whatsapp === '') {
    echo json_encode(['success'=>false,'message'=>'Todos los campos son obligatorios']); exit;
}

// ¿Existe ya el registro?
$stmt = $mysqli->prepare("SELECT id FROM twilio_config WHERE slug_tienda = ? LIMIT 1");
if (!$stmt) { echo json_encode(['success'=>false,'message'=>'Error prepare: '.$mysqli->error]); exit; }
$stmt->bind_param("s", $slug_tienda);
$stmt->execute();
$stmt->bind_result($idExistente);
$existe = $stmt->fetch();
$stmt->close();

if ($existe) {
    // UPDATE
    $stmt2 = $mysqli->prepare("UPDATE twilio_config 
        SET account_sid = ?, auth_token = ?, from_whatsapp = ?
        WHERE slug_tienda = ?");
    if (!$stmt2) { echo json_encode(['success'=>false,'message'=>'Error prepare: '.$mysqli->error]); exit; }
    $stmt2->bind_param("ssss", $account_sid, $auth_token, $from_whatsapp, $slug_tienda);
    if ($stmt2->execute()) {
        $stmt2->close();
        echo json_encode([
            'success'=>true,
            'message'=>'Configuración actualizada',
            'data'=>[
                'id'=>$idExistente,
                'slug_tienda'=>$slug_tienda,
                'account_sid'=>$account_sid,
                'auth_token'=>'***', // no eco completo por seguridad
                'from_whatsapp'=>$from_whatsapp
            ]
        ]);
    } else {
        echo json_encode(['success'=>false,'message'=>'Error al actualizar: '.$stmt2->error]);
    }
    exit;
} else {
    // INSERT
    $stmt3 = $mysqli->prepare("INSERT INTO twilio_config (slug_tienda, account_sid, auth_token, from_whatsapp) 
        VALUES (?, ?, ?, ?)");
    if (!$stmt3) { echo json_encode(['success'=>false,'message'=>'Error prepare: '.$mysqli->error]); exit; }
    $stmt3->bind_param("ssss", $slug_tienda, $account_sid, $auth_token, $from_whatsapp);
    if ($stmt3->execute()) {
        $nuevoId = $stmt3->insert_id;
        $stmt3->close();
        echo json_encode([
            'success'=>true,
            'message'=>'Configuración guardada',
            'data'=>[
                'id'=>$nuevoId,
                'slug_tienda'=>$slug_tienda,
                'account_sid'=>$account_sid,
                'auth_token'=>'***',
                'from_whatsapp'=>$from_whatsapp
            ]
        ]);
    } else {
        echo json_encode(['success'=>false,'message'=>'Error al guardar: '.$stmt3->error]);
    }
    exit;
}
