<?php
/**
 * LandSecure Sync Functions
 * LandSales Pro - Syncs sold plot data to LandSecure
 */

if (!defined('APP_RUNNING')) {
    die('Direct access not allowed');
}

/**
 * Get LandSecure integration settings
 */
function getLandSecureSettings($userId = null) {
    global $conn;

    // Default settings
    $defaults = [
        'enabled' => false,
        'api_url' => 'https://landsecure.co.tz/api/receive_sold_land.php',
        'api_key' => '',
        'auto_sync' => true // Automatically sync on sale completion
    ];

    if ($userId) {
        // Check user-specific settings
        $userId = intval($userId);
        $result = db_fetch_one("SELECT * FROM user_settings WHERE user_id = ? AND setting_key = 'landsecure_integration'", 'i', [$userId]);

        if ($result && !empty($result['setting_value'])) {
            $userSettings = json_decode($result['setting_value'], true);
            if ($userSettings) {
                return array_merge($defaults, $userSettings);
            }
        }
    }

    return $defaults;
}

/**
 * Save LandSecure integration settings
 */
function saveLandSecureSettings($userId, $settings) {
    $userId = intval($userId);
    $settingsJson = json_encode($settings);

    // Check if settings exist
    $existing = db_fetch_one("SELECT id FROM user_settings WHERE user_id = ? AND setting_key = 'landsecure_integration'", 'i', [$userId]);

    if ($existing) {
        return db_execute(
            "UPDATE user_settings SET setting_value = ?, updated_at = NOW() WHERE user_id = ? AND setting_key = 'landsecure_integration'",
            'si',
            [$settingsJson, $userId]
        );
    } else {
        return db_execute(
            "INSERT INTO user_settings (user_id, setting_key, setting_value, created_at) VALUES (?, 'landsecure_integration', ?, NOW())",
            'is',
            [$userId, $settingsJson]
        );
    }
}

/**
 * Sync a sold plot to LandSecure
 *
 * @param int $saleId The sale ID
 * @param int $userId The user ID (seller)
 * @return array Result with success status and message
 */
function syncToLandSecure($saleId, $userId) {
    // Get settings
    $settings = getLandSecureSettings($userId);

    if (!$settings['enabled']) {
        return [
            'success' => false,
            'message' => 'LandSecure integration is not enabled',
            'status' => 'disabled'
        ];
    }

    if (empty($settings['api_key'])) {
        return [
            'success' => false,
            'message' => 'LandSecure API key is not configured',
            'status' => 'not_configured'
        ];
    }

    // Get sale details
    $sale = db_fetch_one("
        SELECT s.*, p.plot_number, p.size, p.size_unit, p.center_latitude, p.center_longitude,
               pr.name as project_name, pr.location as project_location,
               b.full_name as buyer_name, b.email as buyer_email, b.phone as buyer_phone,
               u.company_name as seller_company
        FROM sales s
        JOIN plots p ON s.plot_id = p.id
        JOIN projects pr ON p.project_id = pr.id
        JOIN buyers b ON s.buyer_id = b.id
        JOIN users u ON s.user_id = u.id
        WHERE s.id = ? AND s.user_id = ?
    ", 'ii', [$saleId, $userId]);

    if (!$sale) {
        return [
            'success' => false,
            'message' => 'Sale not found',
            'status' => 'not_found'
        ];
    }

    // Check if buyer has email
    if (empty($sale['buyer_email'])) {
        return [
            'success' => false,
            'message' => 'Buyer does not have an email address',
            'status' => 'no_email'
        ];
    }

    // Get plot coordinates
    $coordinates = getPlotCoordinates($sale['plot_id']);

    if (empty($coordinates)) {
        // Use center point as single coordinate if no polygon exists
        if ($sale['center_latitude'] && $sale['center_longitude']) {
            $coordinates = [
                ['latitude' => $sale['center_latitude'], 'longitude' => $sale['center_longitude'], 'label' => 'Center Point']
            ];
        } else {
            return [
                'success' => false,
                'message' => 'No GPS coordinates found for this plot',
                'status' => 'no_coordinates'
            ];
        }
    }

    // Prepare data for API
    $data = [
        'buyer_email' => $sale['buyer_email'],
        'buyer_name' => $sale['buyer_name'],
        'buyer_phone' => $sale['buyer_phone'],
        'plot_number' => $sale['plot_number'],
        'project_name' => $sale['project_name'],
        'company_name' => $sale['seller_company'] ?? 'Land Developer',
        'sale_date' => $sale['sale_date'],
        'sale_price' => floatval($sale['total_price']),
        'plot_size' => floatval($sale['size']),
        'size_unit' => $sale['size_unit'],
        'sale_id' => intval($saleId),
        'plot_id' => intval($sale['plot_id']),
        'coordinates' => $coordinates,
        'notes' => "Project: {$sale['project_name']} ({$sale['project_location']})"
    ];

    // Send to LandSecure API
    $result = sendToLandSecureAPI($settings['api_url'], $settings['api_key'], $data);

    // Log the sync attempt
    logSyncAttempt($saleId, $sale['plot_id'], $sale['buyer_email'], $result);

    return $result;
}

/**
 * Get plot coordinates from database
 */
function getPlotCoordinates($plotId) {
    $plotId = intval($plotId);

    $points = db_fetch_all("
        SELECT latitude, longitude, point_order, point_label as label
        FROM plot_coordinates
        WHERE plot_id = ?
        ORDER BY point_order ASC
    ", 'i', [$plotId]);

    if (!$points) {
        return [];
    }

    return array_map(function($point) {
        return [
            'latitude' => floatval($point['latitude']),
            'longitude' => floatval($point['longitude']),
            'label' => $point['label'] ?? 'Point ' . $point['point_order']
        ];
    }, $points);
}

/**
 * Send data to LandSecure API
 */
function sendToLandSecureAPI($apiUrl, $apiKey, $data) {
    $ch = curl_init($apiUrl);

    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'X-API-Key: ' . $apiKey
        ],
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => true
    ]);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);

    curl_close($ch);

    if ($error) {
        return [
            'success' => false,
            'message' => 'Connection error: ' . $error,
            'status' => 'connection_error'
        ];
    }

    $responseData = json_decode($response, true);

    if (!$responseData) {
        return [
            'success' => false,
            'message' => 'Invalid response from LandSecure API',
            'status' => 'invalid_response',
            'http_code' => $httpCode
        ];
    }

    // Return the API response
    return [
        'success' => $responseData['success'] ?? false,
        'message' => $responseData['message'] ?? 'Unknown response',
        'status' => $responseData['data']['status'] ?? 'unknown',
        'data' => $responseData['data'] ?? null,
        'http_code' => $httpCode
    ];
}

/**
 * Log sync attempt to database
 */
function logSyncAttempt($saleId, $plotId, $buyerEmail, $result) {
    $status = 'pending';

    if ($result['success']) {
        $status = 'success';
    } elseif (isset($result['status'])) {
        if ($result['status'] === 'no_account') {
            $status = 'no_account';
        } else {
            $status = 'failed';
        }
    }

    $landSecureId = $result['data']['land_id'] ?? null;

    db_execute("
        INSERT INTO landsecure_sync_log
        (sale_id, plot_id, buyer_email, landsecure_land_id, status, response_message, synced_at)
        VALUES (?, ?, ?, ?, ?, ?, NOW())
    ", 'iisiss', [
        $saleId,
        $plotId,
        $buyerEmail,
        $landSecureId,
        $status,
        $result['message']
    ]);
}

/**
 * Get sync status for a sale
 */
function getSyncStatus($saleId) {
    return db_fetch_one("
        SELECT * FROM landsecure_sync_log
        WHERE sale_id = ?
        ORDER BY created_at DESC
        LIMIT 1
    ", 'i', [$saleId]);
}

/**
 * Get all pending syncs
 */
function getPendingSyncs($userId) {
    return db_fetch_all("
        SELECT s.id as sale_id, s.sale_number, b.full_name as buyer_name, b.email as buyer_email,
               p.plot_number, pr.name as project_name,
               sl.status as sync_status, sl.response_message, sl.synced_at
        FROM sales s
        JOIN buyers b ON s.buyer_id = b.id
        JOIN plots p ON s.plot_id = p.id
        JOIN projects pr ON p.project_id = pr.id
        LEFT JOIN landsecure_sync_log sl ON s.id = sl.sale_id
        WHERE s.user_id = ?
        AND b.email IS NOT NULL
        AND b.email != ''
        AND (sl.status IS NULL OR sl.status IN ('pending', 'failed', 'no_account'))
        ORDER BY s.created_at DESC
    ", 'i', [$userId]);
}

/**
 * Retry failed syncs
 */
function retryFailedSyncs($userId) {
    $failedSyncs = db_fetch_all("
        SELECT DISTINCT sl.sale_id
        FROM landsecure_sync_log sl
        JOIN sales s ON sl.sale_id = s.id
        WHERE s.user_id = ? AND sl.status = 'failed'
    ", 'i', [$userId]);

    $results = [];
    foreach ($failedSyncs as $sync) {
        $results[] = syncToLandSecure($sync['sale_id'], $userId);
    }

    return $results;
}
