<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json');

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    try {
        $data = json_decode(file_get_contents('php://input'), true);

        if (!isset($data['id'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing masjid id']);
            exit;
        }

        $id = (int)$data['id'];
        $db = getDB();

        $checkStmt = $db->prepare('SELECT id FROM masjids WHERE id = ?');
        $checkStmt->execute([$id]);
        if (!$checkStmt->fetch(PDO::FETCH_ASSOC)) {
            http_response_code(404);
            echo json_encode(['error' => 'Masjid not found']);
            exit;
        }

        $childStmt = $db->prepare('SELECT id FROM need_points WHERE masjid_id = ?');
        $childStmt->execute([$id]);
        $childIds = array_map(function($row) {
            return (int)$row['id'];
        }, $childStmt->fetchAll(PDO::FETCH_ASSOC));

        $deleteStmt = $db->prepare('DELETE FROM masjids WHERE id = ?');
        $deleteStmt->execute([$id]);

        echo json_encode([
            'success' => true,
            'deleted_need_points' => count($childIds),
            'deleted_need_point_ids' => $childIds
        ]);
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['error' => $e->getMessage()]);
    }
} else {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
}
?>
