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

require_once 'config.php';

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    try {
        $db = getDB();
        $stmt = $db->query("\n            SELECT\n                np.id,\n                np.name,\n                np.latitude,\n                np.longitude,\n                np.masjid_id,\n                np.household_name,\n                np.head_name,\n                np.economic_status,\n                np.is_verified,\n                CASE WHEN EXISTS (\n                    SELECT 1\n                    FROM households h\n                    JOIN assistance_distributions ad ON ad.household_id = h.id\n                    WHERE h.need_point_id = np.id\n                      AND ad.delivery_status = 'delivered'\n                ) THEN 1 ELSE 0 END AS assisted,\n                np.created_at,\n                np.updated_at,\n                m.name AS masjid_name,\n                m.latitude AS masjid_latitude,\n                m.longitude AS masjid_longitude,\n                m.radius_meters\n            FROM need_points np\n            JOIN masjids m ON m.id = np.masjid_id\n            ORDER BY np.created_at DESC\n        ");

        $points = $stmt->fetchAll(PDO::FETCH_ASSOC);
        foreach ($points as &$point) {
            $point['distance_meters'] = haversineDistanceMeters(
                (float)$point['latitude'],
                (float)$point['longitude'],
                (float)$point['masjid_latitude'],
                (float)$point['masjid_longitude']
            );
        }
        unset($point);

        echo json_encode([
            'success' => true,
            'points' => $points
        ]);
    } 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']);
}
?>
