<?php
// cms/coverage-update.php
header('Content-Type: application/json');

require_once('db_connection.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método No Permitido']);
    exit;
}

try {
    // Iniciar transacción
    $pdo->beginTransaction();

    // Sanitizar y validar inputs
    $coverage_badge = htmlspecialchars(strip_tags($_POST['coverage-badge'] ?? ''));
    $coverage_title_1 = htmlspecialchars(strip_tags($_POST['coverage-title-1'] ?? ''));
    $coverage_title_2 = htmlspecialchars(strip_tags($_POST['coverage-title-2'] ?? ''));
    $coverage_map_embed = $_POST['coverage-map-embed'] ?? '';
    $coverage_description = htmlspecialchars(strip_tags($_POST['coverage-description'] ?? ''));
    
    $cities = json_decode($_POST['cities_json'] ?? '[]', true);

    // Insertar/Actualizar en la tabla principal
    $stmt = $pdo->query("SELECT id FROM cms_coverage ORDER BY updated_at DESC LIMIT 1");
    $currentRecord = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($currentRecord) {
        $coverageId = $currentRecord['id'];
        $sql = "UPDATE cms_coverage SET coverage_badge=?, coverage_title_1=?, coverage_title_2=?, coverage_map_embed=?, coverage_description=? WHERE id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$coverage_badge, $coverage_title_1, $coverage_title_2, $coverage_map_embed, $coverage_description, $coverageId]);
    } else {
        $sql = "INSERT INTO cms_coverage (coverage_badge, coverage_title_1, coverage_title_2, coverage_map_embed, coverage_description) VALUES (?, ?, ?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$coverage_badge, $coverage_title_1, $coverage_title_2, $coverage_map_embed, $coverage_description]);
        $coverageId = $pdo->lastInsertId();
    }
    
    // Eliminar ciudades antiguas
    if (isset($coverageId)) {
        $stmt = $pdo->prepare("DELETE FROM cms_coverage_cities WHERE coverage_id = ?");
        $stmt->execute([$coverageId]);

        // Insertar nuevas ciudades
        $sqlCity = "INSERT INTO cms_coverage_cities (coverage_id, city_name) VALUES (?, ?)";
        $stmtCity = $pdo->prepare($sqlCity);
        foreach ($cities as $city) {
            $cityName = htmlspecialchars(strip_tags($city['city_name'] ?? ''));
            if (!empty($cityName)) {
                $stmtCity->execute([$coverageId, $cityName]);
            }
        }
    }

    $pdo->commit();
    echo json_encode(['success' => true, 'message' => 'SiteFlow Actualizado Exitosamente']);
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>