<?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
require_once(__DIR__ . '/../config.php');
$mysqli->set_charset("utf8mb4");

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

// Validar
$requeridos = ['slug_tienda','phone_id','access_token','token_webhook','business_id','id_app'];
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']);
$phone_id      = trim($input['phone_id']);
$access_token  = trim($input['access_token']);
$token_webhook = trim($input['token_webhook']);
$business_id   = trim($input['business_id']);
$id_app        = trim($input['id_app']);

if ($slug_tienda === '' || $phone_id === '' || $access_token === '' || $token_webhook === '' || $business_id === '' || $id_app === '') {
    echo json_encode(['success'=>false,'message'=>'Todos los campos son obligatorios']); exit;
}

// ¿Existe ya el registro?
$stmt = $mysqli->prepare("SELECT id FROM waba_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 waba_config 
        SET phone_id = ?, access_token = ?, token_webhook = ?, business_id = ?, id_app = ?
        WHERE slug_tienda = ?");
    if (!$stmt2) { echo json_encode(['success'=>false,'message'=>'Error prepare: '.$mysqli->error]); exit; }
    $stmt2->bind_param("ssssss", $phone_id, $access_token, $token_webhook, $business_id, $id_app, $slug_tienda);
    if ($stmt2->execute()) {
        $stmt2->close();
        echo json_encode([
            'success'=>true,
            'message'=>'Configuración actualizada',
            'data'=>[
                'id'=>$idExistente,
                'slug_tienda'=>$slug_tienda,
                'phone_id'=>$phone_id,
                'access_token'=>$access_token,
                'token_webhook'=>$token_webhook,
                'business_id'=>$business_id,
                'id_app'=>$id_app
            ]
        ]);
    } else {
        echo json_encode(['success'=>false,'message'=>'Error al actualizar: '.$stmt2->error]);
    }
    exit;
} else {
    // INSERT
    $stmt3 = $mysqli->prepare("INSERT INTO waba_config (phone_id, access_token, slug_tienda, token_webhook, business_id, id_app) 
        VALUES (?, ?, ?, ?, ?, ?)");
    if (!$stmt3) { echo json_encode(['success'=>false,'message'=>'Error prepare: '.$mysqli->error]); exit; }
    $stmt3->bind_param("ssssss", $phone_id, $access_token, $slug_tienda, $token_webhook, $business_id, $id_app);
    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,
                'phone_id'=>$phone_id,
                'access_token'=>$access_token,
                'token_webhook'=>$token_webhook,
                'business_id'=>$business_id,
                'id_app'=>$id_app
            ]
        ]);
    } else {
        echo json_encode(['success'=>false,'message'=>'Error al guardar: '.$stmt3->error]);
    }
    exit;
}
