<?php
// API endpoint to delete a property
session_start();
header('Content-Type: application/json');

// Check authentication
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_role'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

// Check authorization - only admins can delete properties
if ($_SESSION['user_role'] !== 'admin') {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized. Only admins can delete properties']);
    exit;
}

// Include database configuration
require_once __DIR__ . '/../config.php';

// Get JSON data from request body
$data = json_decode(file_get_contents('php://input'), true);

if (!isset($data['property_id']) || empty($data['property_id'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Property ID is required']);
    exit;
}

$property_id = intval($data['property_id']);

try {
    // Prepare and execute delete query
    $stmt = $mysqli->prepare("DELETE FROM properties WHERE id = ?");
    if (!$stmt) {
        throw new Exception("Prepare failed: " . $mysqli->error);
    }

    $stmt->bind_param("i", $property_id);
    
    if (!$stmt->execute()) {
        throw new Exception("Execute failed: " . $stmt->error);
    }

    if ($stmt->affected_rows > 0) {
        echo json_encode([
            'success' => true,
            'message' => 'Property deleted successfully'
        ]);
    } else {
        http_response_code(404);
        echo json_encode([
            'success' => false,
            'message' => 'Property not found'
        ]);
    }

    $stmt->close();
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error deleting property: ' . $e->getMessage()
    ]);
}

$mysqli->close();
?>
