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

require_once 'config.php';

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

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

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

        $existing = getNeedPointWithMasjid($db, $id);
        if (!$existing) {
            http_response_code(404);
            echo json_encode(['error' => 'Point berkebutuhan not found']);
            exit;
        }

        $newName = isset($data['name']) ? trim($data['name']) : $existing['name'];
        if ($newName === '') {
            http_response_code(400);
            echo json_encode(['error' => 'Name cannot be empty']);
            exit;
        }

        $newLatitude = array_key_exists('latitude', $data) ? $data['latitude'] : $existing['latitude'];
        $newLongitude = array_key_exists('longitude', $data) ? $data['longitude'] : $existing['longitude'];

        if (!is_numeric($newLatitude) || !is_numeric($newLongitude)) {
            http_response_code(400);
            echo json_encode(['error' => 'Latitude and longitude must be numeric values']);
            exit;
        }

        $newLatitude = (float)$newLatitude;
        $newLongitude = (float)$newLongitude;

        if ($newLatitude < -90 || $newLatitude > 90) {
            http_response_code(400);
            echo json_encode(['error' => 'Latitude must be between -90 and 90']);
            exit;
        }

        if ($newLongitude < -180 || $newLongitude > 180) {
            http_response_code(400);
            echo json_encode(['error' => 'Longitude must be between -180 and 180']);
            exit;
        }

        $nearestMasjid = findNearestMasjidCoveringPoint($db, $newLatitude, $newLongitude);
        if ($nearestMasjid === null) {
            http_response_code(400);
            echo json_encode(['error' => 'Point must remain inside at least one masjid radius']);
            exit;
        }

            // allow updating household fields as well
            $newHouseholdName = array_key_exists('household_name', $data) ? trim($data['household_name']) : $existing['household_name'];
            $newHeadName = array_key_exists('head_name', $data) ? trim($data['head_name']) : $existing['head_name'];
            $newEconomic = array_key_exists('economic_status', $data) ? trim($data['economic_status']) : $existing['economic_status'];

            $updateStmt = $db->prepare('
                UPDATE need_points
                SET name = ?, latitude = ?, longitude = ?, masjid_id = ?, household_name = ?, head_name = ?, economic_status = ?, updated_at = CURRENT_TIMESTAMP
                WHERE id = ?
            ');
            $updateStmt->execute([
                $newName,
                $newLatitude,
                $newLongitude,
                (int)$nearestMasjid['id'],
                $newHouseholdName,
                $newHeadName,
                $newEconomic,
                $id
            ]);

        $updated = getNeedPointWithMasjid($db, $id);
        $updated['distance_meters'] = $nearestMasjid['distance_meters'];

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