<?php
session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'error' => 'No autorizado']);
    exit;
}

require_once 'db/config.php';

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$field = isset($_POST['field']) ? $_POST['field'] : '';
$value = isset($_POST['value']) ? trim($_POST['value']) : '';

if ($id <= 0 || !in_array($field, ['titulo', 'texto'])) {
    echo json_encode(['success' => false, 'error' => 'Datos inválidos.']);
    exit;
}

try {
    $db = db();

    // Check if this update will result in a completely empty row
    if (empty($value)) {
        $other_field = ($field === 'titulo') ? 'texto' : 'titulo';
        
        $stmt_check = $db->prepare("SELECT $other_field FROM cobertura_xpress WHERE id = ?");
        $stmt_check->execute([$id]);
        $other_value = $stmt_check->fetchColumn();

        if ($other_value !== false && empty(trim($other_value))) {
            // Both fields are empty, so delete the row
            $stmt_delete = $db->prepare("DELETE FROM cobertura_xpress WHERE id = ?");
            if ($stmt_delete->execute([$id])) {
                echo json_encode(['success' => true, 'deleted' => true]);
            } else {
                echo json_encode(['success' => false, 'error' => 'No se pudo eliminar la fila.']);
            }
            exit;
        }
    }

    // If not deleting, proceed with the update
    $stmt = $db->prepare("UPDATE cobertura_xpress SET $field = ? WHERE id = ?");
    
    if ($stmt->execute([$value, $id])) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => 'No se pudo actualizar en la base de datos.']);
    }
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'error' => 'Error de base de datos: ' . $e->getMessage()]);
}