<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST");
date_default_timezone_set('America/Bogota');

require_once(__DIR__ . '/../config.php');

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

$slug = $input['slug'] ?? null;
$telefono = $input['telefono'] ?? null;
$nombre = $input['nombre'] ?? '';
$foto = $input['foto'] ?? '';

if (!$slug || !$telefono) {
    echo json_encode(['success' => false, 'message' => 'Faltan parámetros']);
    exit;
}

// Verificar si ya existe el contacto
$stmt = $mysqli->prepare("SELECT id FROM contactos WHERE slug_tienda = ? AND telefono = ?");
$stmt->bind_param("ss", $slug, $telefono);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    // Ya existe, actualizamos
    $stmt->close();
    $stmt = $mysqli->prepare("UPDATE contactos SET nombre = ?, foto = ? WHERE slug_tienda = ? AND telefono = ?");
    $stmt->bind_param("ssss", $nombre, $foto, $slug, $telefono);
    $success = $stmt->execute();
} else {
    // No existe, insertamos
    $stmt->close();
    $stmt = $mysqli->prepare("INSERT INTO contactos (slug_tienda, telefono, nombre, foto) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $slug, $telefono, $nombre, $foto);
    $success = $stmt->execute();
}

if ($success) {
    echo json_encode(['success' => true, 'message' => 'Contacto guardado']);
} else {
    echo json_encode(['success' => false, 'message' => 'Error: ' . $stmt->error]);
}

$stmt->close();
