<?php
// /IAMarketing/api-db/ia-ads-generator-delete.php
ob_start();
require_once __DIR__ . '/../client-information.php'; 
ob_clean();

header('Content-Type: application/json');

if (!isset($pdo)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection error.']);
    exit;
}

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

if (isset($data['id'])) {
    $ad_id = $data['id'];
    $business_id = 1; // Assuming business_info_id = 1

    try {
        // Delete the row based on ID and ensure it belongs to the current business
        $sql = "DELETE FROM ia_ads_generator_results WHERE id = ? AND business_info_id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$ad_id, $business_id]);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Anuncio publicitario eliminado con éxito.']);
        } else {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'No se encontró el anuncio para eliminar.']);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database error while deleting ad: ' . $e->getMessage()]);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Ad ID not received for deletion.']);
}
?>