<?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['name']) || !isset($data['latitude']) || !isset($data['longitude'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Missing required fields: name, latitude, or longitude']);
            exit;
        }

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

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

        $latitude = (float)$data['latitude'];
        $longitude = (float)$data['longitude'];

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

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

        $db = getDB();
        $nearestMasjid = findNearestMasjidCoveringPoint($db, $latitude, $longitude);

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

        // optional household details
        $householdName = isset($data['household_name']) ? trim($data['household_name']) : null;
        $headName = isset($data['head_name']) ? trim($data['head_name']) : null;
        $economicStatus = isset($data['economic_status']) ? trim($data['economic_status']) : null;

        // generate defaults when missing
        if (!$householdName) $householdName = 'Keluarga ' . substr(md5(uniqid('', true)), 0, 8);
        if (!$headName) {
            $firstNames = ['Ahmad','Budi','Siti','Aulia','Rizal','Dewi','Agus','Fitri','Hendra','Yulia'];
            $lastNames = ['Santoso','Wijaya','Pratama','Hidayat','Saputra','Nur','Ibrahim','Setiawan','Rahman','Putri'];
            $headName = $firstNames[array_rand($firstNames)] . ' ' . $lastNames[array_rand($lastNames)];
        }
        if (!$economicStatus) {
            $statuses = ['sangat_miskin','miskin','rentan','cukup','baik'];
            $economicStatus = $statuses[array_rand($statuses)];
        }

        $insertStmt = $db->prepare('INSERT INTO need_points (name, latitude, longitude, masjid_id, household_name, head_name, economic_status) VALUES (?, ?, ?, ?, ?, ?, ?)');
        $insertStmt->execute([$name, $latitude, $longitude, (int)$nearestMasjid['id'], $householdName, $headName, $economicStatus]);

        $pointId = (int)$db->lastInsertId();
        $point = getNeedPointWithMasjid($db, $pointId);
        $point['distance_meters'] = $nearestMasjid['distance_meters'];

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