<?php
// cms/social-links-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();
    $social_links = json_decode($_POST['social_links_json'] ?? '[]', true);

    $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'];
        
        $stmtDelete = $pdo->prepare("DELETE FROM social_links WHERE business_info_id = ?");
        $stmtDelete->execute([$id]);

        $sqlLink = "INSERT INTO social_links (business_info_id, link_icon, link_url) VALUES (?, ?, ?)";
        $stmtLink = $pdo->prepare($sqlLink);
        foreach ($social_links as $link) {
            $icon = htmlspecialchars(strip_tags($link['icon'] ?? ''));
            $url = htmlspecialchars(strip_tags($link['url'] ?? ''));
            if (!empty($url)) {
                $stmtLink->execute([$id, $icon, $url]);
            }
        }
    } else {
        echo json_encode(['success' => false, 'message' => 'Método No Permitido']);
        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()]);
}
?>