<?php
/**
 * Sync Land API Endpoint
 * Handles syncing land 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 {
    // Check if this is an update or insert
    $server_id = isset($input['server_id']) ? intval($input['server_id']) : null;
    $local_id = $input['local_id'] ?? null;

    if ($server_id) {
        // Update existing land
        $stmt = $conn->prepare("
            UPDATE lands SET
                land_name = ?,
                location_address = ?,
                total_area = ?,
                area_unit = ?,
                notes = ?,
                updated_at = NOW()
            WHERE id = ? AND user_id = ?
        ");

        $stmt->bind_param(
            'ssdssii',
            $input['land_name'],
            $input['location_address'],
            $input['total_area'],
            $input['area_unit'],
            $input['notes'],
            $server_id,
            $user_id
        );

        if ($stmt->execute()) {
            echo json_encode([
                'success' => true,
                'message' => 'Land updated successfully',
                'server_id' => $server_id,
                'local_id' => $local_id
            ]);
        } else {
            throw new Exception('Failed to update land');
        }
    } else {
        // Insert new land
        $stmt = $conn->prepare("
            INSERT INTO lands (user_id, land_name, location_address, total_area, area_unit, notes, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())
        ");

        $stmt->bind_param(
            'issdss',
            $user_id,
            $input['land_name'],
            $input['location_address'],
            $input['total_area'],
            $input['area_unit'],
            $input['notes']
        );

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

            // Log activity
            $action = 'create_land';
            $description = "Created land: " . $input['land_name'] . " (offline sync)";
            $ip = $_SERVER['REMOTE_ADDR'];

            $log_stmt = $conn->prepare("INSERT INTO activity_logs (user_id, action, description, ip_address) VALUES (?, ?, ?, ?)");
            $log_stmt->bind_param('isss', $user_id, $action, $description, $ip);
            $log_stmt->execute();

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