<?php
// cms/tracking-codes-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 {
    $pdo->beginTransaction();

    $tracking_codes_head = $_POST['tracking_codes_head'] ?? '';
    $tracking_codes_body = $_POST['tracking_codes_body'] ?? '';
    
    $stmt = $pdo->query("SELECT id FROM business_info ORDER BY updated_at DESC LIMIT 1");
    $currentRecord = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($currentRecord) {
        $id = $currentRecord['id'];
        $sql = "UPDATE tracking_codes SET tracking_codes_head=?, tracking_codes_body=? WHERE business_info_id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$tracking_codes_head, $tracking_codes_body, $id]);
    } else {
        echo json_encode(['success' => false, 'message' => 'No se encontró un registro de información del negocio para actualizar los códigos de seguimiento.']);
        exit;
    }

    $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()]);
}
?>