<?php
// FINAL SCRIPT: delete_offer.php

// --- 1. Prevent Network Errors & Set Up ---
ob_start();

error_reporting(E_ALL);
ini_set('display_errors', 0);
ini_set('log_errors', 1);

require 'db_connect.php'; 

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

ob_clean();

$response = [];

// --- 2. Validation ---
if (!isset($conn) || $conn->connect_error) {
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Server Error: Database connection is not available.';
    echo json_encode($response);
    exit;
}

// Check for the offer ID, which is essential for deletion
if (!isset($_POST['id']) || empty($_POST['id'])) {
    http_response_code(400); 
    $response['status'] = 'error';
    $response['message'] = 'Offer ID is missing.';
    echo json_encode($response);
    exit;
}

// --- 3. Assign and Sanitize Data ---
$offer_id = intval($_POST['id']);

// --- 4. Prepare and Execute the Database DELETE ---
$sql = "DELETE FROM offers WHERE id = ?";

$stmt = $conn->prepare($sql);

if ($stmt) {
    // Bind the integer ID to the query
    $stmt->bind_param("i", $offer_id);
    
    if ($stmt->execute()) {
        // --- Success ---
        // Check if any row was actually affected
        if ($stmt->affected_rows > 0) {
            $response['status'] = 'success';
            $response['message'] = 'Offer deleted successfully.';
        } else {
            // This happens if the ID did not exist
            http_response_code(404); // Not Found
            $response['status'] = 'error';
            $response['message'] = 'Offer not found or already deleted.';
        }
    } else {
        // --- Failure (Database Execute) ---
        http_response_code(500);
        $response['status'] = 'error';
        $response['message'] = 'Database Error: Could not execute the deletion. ' . $stmt->error;
    }
    $stmt->close();
} else {
    // --- Failure (Database Prepare) ---
    http_response_code(500);
    $response['status'] = 'error';
    $response['message'] = 'Database Error: Could not prepare the statement. ' . $conn->error;
}

// --- 5. Final Clean Output ---
echo json_encode($response);

$conn->close();
exit;
?>