<?php
/**
 * Sync to LandSecure AJAX Endpoint
 * LandSales Pro - Sync sold plot data to LandSecure
 */
define('APP_RUNNING', true);
require_once '../db_connect.php';
require_once '../includes/auth.php';
require_once '../includes/functions.php';
require_once '../includes/landsecure_sync.php';

header('Content-Type: application/json');

initSecureSession();

if (!isAuthenticated()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid method']);
    exit;
}

$userId = $_SESSION['user_id'];

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

$saleId = intval($input['sale_id'] ?? 0);
$action = $input['action'] ?? 'sync';

if (!$saleId) {
    echo json_encode(['success' => false, 'error' => 'Sale ID is required']);
    exit;
}

// Verify sale belongs to user
$sale = db_fetch_one("SELECT id FROM sales WHERE id = ? AND user_id = ?", 'ii', [$saleId, $userId]);

if (!$sale) {
    echo json_encode(['success' => false, 'error' => 'Sale not found']);
    exit;
}

// Perform sync
$result = syncToLandSecure($saleId, $userId);

echo json_encode([
    'success' => $result['success'],
    'message' => $result['message'],
    'status' => $result['status'] ?? 'unknown',
    'data' => $result['data'] ?? null
]);
