<?php
session_start();
require_once "config.php";

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

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$agent_id = intval($_SESSION['user_id']);

// Accept both POST JSON and form-urlencoded
$input = file_get_contents("php://input");
$data = json_decode($input, true);

if ($_SERVER['CONTENT_TYPE'] === 'application/json' && isset($data['id'])) {
    $property_id = intval($data['id']);
} elseif (isset($_POST['id'])) {
    $property_id = intval($_POST['id']);
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid property ID (not received)']);
    exit;
}

if ($property_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid property ID']);
    exit;
}

// Check if property belongs to agent
$stmt = $conn->prepare("SELECT id FROM properties WHERE id = ? AND user_id = ?");
$stmt->bind_param("ii", $property_id, $agent_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'Property not found or unauthorized']);
    exit;
}

// Delete property images (DB + files)
$imgQuery = $conn->prepare("SELECT image_path FROM property_images WHERE property_id = ?");
$imgQuery->bind_param("i", $property_id);
$imgQuery->execute();
$imgRes = $imgQuery->get_result();
while ($row = $imgRes->fetch_assoc()) {
    $path = $row['image_path'];
    if ($path && file_exists($path)) unlink($path);
}
$conn->query("DELETE FROM property_images WHERE property_id = $property_id");

// Delete property videos (DB + files)
$vidQuery = $conn->prepare("SELECT video_path FROM property_videos WHERE property_id = ?");
$vidQuery->bind_param("i", $property_id);
$vidQuery->execute();
$vidRes = $vidQuery->get_result();
while ($row = $vidRes->fetch_assoc()) {
    $path = $row['video_path'];
    if ($path && file_exists($path)) unlink($path);
}
$conn->query("DELETE FROM property_videos WHERE property_id = $property_id");

// Delete property record
$conn->query("DELETE FROM properties WHERE id = $property_id AND user_id = $agent_id");

echo json_encode(['success' => true, 'message' => 'Property deleted successfully']);
