<?php
require_once '../../includes/auth.php';
require_once '../../config/database.php';
require_once '../../config/logger.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

if (!hasRole(['admin','diocesan_chairman','diocese_chairman','diocesan_secretary','diocesan_treasurer','diocesan_dom','diocesan_music_director'])) {
    echo json_encode(['success' => false, 'message' => 'No permission']);
    exit;
}

$adId = isset($_POST['ad_id']) ? (int)$_POST['ad_id'] : 0;
if ($adId <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    exit;
}

$ad = fetchRow("SELECT id, created_by, status, workflow_state, image_path FROM ads WHERE id = ?", [$adId]);
if (!$ad) {
    echo json_encode(['success' => false, 'message' => 'Ad not found']);
    exit;
}

$currentUserId = (int)$_SESSION['user_id'];
if ($ad['created_by'] != $currentUserId && !hasRole(['admin'])) {
    echo json_encode(['success' => false, 'message' => 'You can only delete your own advert']);
    exit;
}

if ($ad['status'] === 'approved' || $ad['workflow_state'] === 'approved') {
    echo json_encode(['success' => false, 'message' => 'Approved adverts cannot be deleted']);
    exit;
}

$img = $ad['image_path'];
$deleted = executeQuery("DELETE FROM ads WHERE id = ?", [$adId]);
if ($deleted) {
    if (!empty($img) && preg_match('/^[\w\-.]+$/', $img)) {
        $path = __DIR__ . '/../../uploads/ads/' . $img;
        if (is_file($path)) {
            @unlink($path);
        }
    }
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => 'Database error']);
}
