<?php
/**
 * Sync Beacon Point API Endpoint
 * Handles syncing beacon point data from offline storage
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

session_start();
require_once '../db_connect.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit;
}

$user_id = $_SESSION['user_id'];

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

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

try {
    $land_id = intval($input['land_id']);
    $local_id = $input['local_id'] ?? null;

    // Verify land belongs to user
    $check = $conn->prepare("SELECT id FROM lands WHERE id = ? AND user_id = ?");
    $check->bind_param('ii', $land_id, $user_id);
    $check->execute();
    $result = $check->get_result();

    if ($result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Land not found or access denied']);
        exit;
    }

    // Check if this is an update or insert
    $server_id = isset($input['server_id']) ? intval($input['server_id']) : null;

    if ($server_id) {
        // Update existing beacon point
        $stmt = $conn->prepare("
            UPDATE beacon_points SET
                latitude = ?,
                longitude = ?,
                point_name = ?,
                point_order = ?,
                description = ?
            WHERE id = ? AND land_id = ?
        ");

        $stmt->bind_param(
            'ddssiii',
            $input['latitude'],
            $input['longitude'],
            $input['point_name'],
            $input['point_order'],
            $input['description'],
            $server_id,
            $land_id
        );

        if ($stmt->execute()) {
            echo json_encode([
                'success' => true,
                'message' => 'Beacon point updated successfully',
                'server_id' => $server_id,
                'local_id' => $local_id
            ]);
        } else {
            throw new Exception('Failed to update beacon point');
        }
    } else {
        // Insert new beacon point
        $stmt = $conn->prepare("
            INSERT INTO beacon_points (land_id, latitude, longitude, point_name, point_order, description, created_at)
            VALUES (?, ?, ?, ?, ?, ?, NOW())
        ");

        $stmt->bind_param(
            'iddsss',
            $land_id,
            $input['latitude'],
            $input['longitude'],
            $input['point_name'],
            $input['point_order'],
            $input['description']
        );

        if ($stmt->execute()) {
            $new_id = $conn->insert_id;

            // Recalculate land area
            updateLandArea($conn, $land_id);

            echo json_encode([
                'success' => true,
                'message' => 'Beacon point created successfully',
                'server_id' => $new_id,
                'local_id' => $local_id
            ]);
        } else {
            throw new Exception('Failed to create beacon point');
        }
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

/**
 * Recalculate and update land area based on beacon points
 */
function updateLandArea($conn, $land_id) {
    $points = $conn->query("SELECT latitude, longitude FROM beacon_points WHERE land_id = $land_id ORDER BY point_order");
    $coords = [];

    while ($point = $points->fetch_assoc()) {
        $coords[] = [$point['latitude'], $point['longitude']];
    }

    if (count($coords) >= 3) {
        $area = calculatePolygonArea($coords);
        $conn->query("UPDATE lands SET total_area = $area, area_unit = 'sqm' WHERE id = $land_id");
    }
}

/**
 * Calculate polygon area using Shoelace formula
 */
function calculatePolygonArea($coords) {
    $n = count($coords);
    if ($n < 3) return 0;

    $area = 0;
    for ($i = 0; $i < $n; $i++) {
        $j = ($i + 1) % $n;
        $area += $coords[$i][0] * $coords[$j][1];
        $area -= $coords[$j][0] * $coords[$i][1];
    }

    // Convert to square meters (approximate)
    $area = abs($area / 2) * 111319.9 * 111319.9 * cos(deg2rad($coords[0][0]));

    return round($area, 2);
}
