<?php
/**
 * LandSecure Integration Settings
 * LandSales Pro - Configure sync to LandSecure
 */
define('APP_RUNNING', true);
require_once '../../../db_connect.php';
require_once '../../../includes/auth.php';
require_once '../../../includes/subscription.php';
require_once '../../../includes/functions.php';
require_once '../../../includes/landsecure_sync.php';

initSecureSession();
requireAuth();
requireSubscription();

$userId = $_SESSION['user_id'];
$pageTitle = 'LandSecure Integration';
$success = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save_settings';

    if ($action === 'save_settings') {
        $settings = [
            'enabled' => isset($_POST['enabled']),
            'api_url' => trim($_POST['api_url'] ?? 'https://landsecure.co.tz/api/receive_sold_land.php'),
            'api_key' => trim($_POST['api_key'] ?? ''),
            'auto_sync' => isset($_POST['auto_sync'])
        ];

        if (saveLandSecureSettings($userId, $settings)) {
            $success = 'Settings saved successfully!';
        } else {
            $error = 'Failed to save settings.';
        }
    } elseif ($action === 'test_connection') {
        $settings = getLandSecureSettings($userId);

        if (empty($settings['api_key'])) {
            $error = 'Please configure your API key first.';
        } else {
            // Test the connection
            $testData = [
                'buyer_email' => 'test@example.com',
                'plot_number' => 'TEST-001',
                'project_name' => 'Connection Test',
                'company_name' => 'Test Company',
                'sale_date' => date('Y-m-d'),
                'coordinates' => [
                    ['latitude' => -6.7924, 'longitude' => 37.6591, 'label' => 'Test Point']
                ]
            ];

            // We'll just check if we can reach the API
            $ch = curl_init($settings['api_url']);
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_NOBODY => true,
                CURLOPT_TIMEOUT => 10,
                CURLOPT_SSL_VERIFYPEER => true
            ]);

            curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            $error_msg = curl_error($ch);
            curl_close($ch);

            if ($error_msg) {
                $error = 'Connection failed: ' . $error_msg;
            } elseif ($httpCode >= 200 && $httpCode < 500) {
                $success = 'Connection to LandSecure API is working!';
            } else {
                $error = 'API returned HTTP status ' . $httpCode;
            }
        }
    } elseif ($action === 'sync_sale') {
        $saleId = intval($_POST['sale_id'] ?? 0);
        if ($saleId > 0) {
            $result = syncToLandSecure($saleId, $userId);
            if ($result['success']) {
                $success = $result['message'];
            } else {
                $error = $result['message'];
            }
        }
    }
}

// Get current settings
$settings = getLandSecureSettings($userId);

// Get pending syncs
$pendingSyncs = getPendingSyncs($userId);

// Get recent sync log
$recentSyncs = db_fetch_all("
    SELECT sl.*, s.sale_number, b.full_name as buyer_name, p.plot_number
    FROM landsecure_sync_log sl
    JOIN sales s ON sl.sale_id = s.id
    JOIN buyers b ON s.buyer_id = b.id
    JOIN plots p ON s.plot_id = p.id
    WHERE s.user_id = ?
    ORDER BY sl.created_at DESC
    LIMIT 20
", 'i', [$userId]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - LandSales Pro</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="<?php echo SITE_URL; ?>/assets/css/dashboard.css" rel="stylesheet">
    <style>
        .integration-header {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 2rem;
        }
        .integration-logo {
            width: 60px;
            height: 60px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 1.5rem;
        }
        .settings-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
        }
        .settings-card h5 {
            margin-bottom: 1rem;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .form-switch .form-check-input {
            width: 3rem;
            height: 1.5rem;
        }
        .sync-status {
            display: inline-flex;
            align-items: center;
            gap: 0.25rem;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .sync-status.success { background: #dcfce7; color: #166534; }
        .sync-status.pending { background: #fef3c7; color: #92400e; }
        .sync-status.failed { background: #fee2e2; color: #991b1b; }
        .sync-status.no_account { background: #e0e7ff; color: #3730a3; }

        .sync-table {
            font-size: 0.875rem;
        }
        .sync-table th {
            background: #f8fafc;
            font-weight: 600;
            color: #64748b;
            text-transform: uppercase;
            font-size: 0.75rem;
        }
        .btn-sync {
            padding: 0.25rem 0.5rem;
            font-size: 0.75rem;
        }
        .api-key-field {
            font-family: monospace;
        }
    </style>
</head>
<body>
    <?php include '../../includes/sidebar.php'; ?>

    <div class="main-content">
        <?php include '../../includes/header.php'; ?>

        <div class="content-wrapper">
            <?php if ($success): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($success); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>

            <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i><?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php endif; ?>

            <!-- Header -->
            <div class="integration-header">
                <div class="integration-logo">
                    <i class="fas fa-map-marked-alt"></i>
                </div>
                <div>
                    <h4 class="mb-0">LandSecure Integration</h4>
                    <p class="text-muted mb-0">Sync sold plots to buyer's LandSecure account</p>
                </div>
            </div>

            <div class="row">
                <div class="col-lg-6">
                    <!-- Settings Form -->
                    <div class="settings-card">
                        <h5><i class="fas fa-cog text-primary"></i> Integration Settings</h5>

                        <form method="POST">
                            <input type="hidden" name="action" value="save_settings">

                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="enabled" name="enabled"
                                           <?php echo $settings['enabled'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="enabled">
                                        <strong>Enable Integration</strong>
                                    </label>
                                </div>
                                <small class="text-muted">When enabled, sold plots can be synced to LandSecure</small>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">API Endpoint URL</label>
                                <input type="url" class="form-control" name="api_url"
                                       value="<?php echo htmlspecialchars($settings['api_url']); ?>"
                                       placeholder="https://landsecure.co.tz/api/receive_sold_land.php">
                                <small class="text-muted">The LandSecure API endpoint URL</small>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">API Key</label>
                                <input type="text" class="form-control api-key-field" name="api_key"
                                       value="<?php echo htmlspecialchars($settings['api_key']); ?>"
                                       placeholder="Enter your LandSecure API key">
                                <small class="text-muted">Get this from your LandSecure admin panel</small>
                            </div>

                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="auto_sync" name="auto_sync"
                                           <?php echo $settings['auto_sync'] ? 'checked' : ''; ?>>
                                    <label class="form-check-label" for="auto_sync">
                                        <strong>Auto-sync on Sale</strong>
                                    </label>
                                </div>
                                <small class="text-muted">Automatically sync when a sale is completed</small>
                            </div>

                            <div class="d-flex gap-2">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-1"></i> Save Settings
                                </button>
                                <button type="submit" name="action" value="test_connection" class="btn btn-outline-secondary">
                                    <i class="fas fa-plug me-1"></i> Test Connection
                                </button>
                            </div>
                        </form>
                    </div>

                    <!-- How It Works -->
                    <div class="settings-card">
                        <h5><i class="fas fa-info-circle text-info"></i> How It Works</h5>
                        <ol class="mb-0">
                            <li class="mb-2">When you sell a plot with GPS coordinates, the system can sync it to LandSecure</li>
                            <li class="mb-2">If the buyer has a LandSecure account (matched by email), the plot appears in their account</li>
                            <li class="mb-2">The buyer can view their plot boundaries and ownership certificate on LandSecure</li>
                            <li class="mb-0">If no account exists, the sync is marked as "No Account" - they can create one later</li>
                        </ol>
                    </div>
                </div>

                <div class="col-lg-6">
                    <!-- Pending Syncs -->
                    <?php if (!empty($pendingSyncs)): ?>
                    <div class="settings-card">
                        <h5><i class="fas fa-clock text-warning"></i> Pending Syncs (<?php echo count($pendingSyncs); ?>)</h5>
                        <div class="table-responsive">
                            <table class="table sync-table mb-0">
                                <thead>
                                    <tr>
                                        <th>Sale</th>
                                        <th>Buyer</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach (array_slice($pendingSyncs, 0, 5) as $sync): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($sync['sale_number']); ?></strong><br>
                                            <small class="text-muted"><?php echo htmlspecialchars($sync['plot_number']); ?></small>
                                        </td>
                                        <td>
                                            <?php echo htmlspecialchars($sync['buyer_name']); ?><br>
                                            <small class="text-muted"><?php echo htmlspecialchars($sync['buyer_email']); ?></small>
                                        </td>
                                        <td>
                                            <?php
                                            $status = $sync['sync_status'] ?? 'not_synced';
                                            $statusClass = $status === 'success' ? 'success' : ($status === 'no_account' ? 'no_account' : ($status === 'failed' ? 'failed' : 'pending'));
                                            ?>
                                            <span class="sync-status <?php echo $statusClass; ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', $status ?: 'Not Synced')); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <form method="POST" class="d-inline">
                                                <input type="hidden" name="action" value="sync_sale">
                                                <input type="hidden" name="sale_id" value="<?php echo $sync['sale_id']; ?>">
                                                <button type="submit" class="btn btn-primary btn-sync" <?php echo !$settings['enabled'] ? 'disabled' : ''; ?>>
                                                    <i class="fas fa-sync-alt"></i> Sync
                                                </button>
                                            </form>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Recent Sync Log -->
                    <div class="settings-card">
                        <h5><i class="fas fa-history text-secondary"></i> Recent Sync Log</h5>
                        <?php if (empty($recentSyncs)): ?>
                        <p class="text-muted mb-0">No sync history yet.</p>
                        <?php else: ?>
                        <div class="table-responsive">
                            <table class="table sync-table mb-0">
                                <thead>
                                    <tr>
                                        <th>Sale</th>
                                        <th>Status</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recentSyncs as $log): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($log['sale_number']); ?></strong><br>
                                            <small class="text-muted"><?php echo htmlspecialchars($log['buyer_name']); ?></small>
                                        </td>
                                        <td>
                                            <span class="sync-status <?php echo $log['status']; ?>">
                                                <?php echo ucfirst(str_replace('_', ' ', $log['status'])); ?>
                                            </span>
                                            <?php if ($log['response_message']): ?>
                                            <br><small class="text-muted"><?php echo htmlspecialchars(substr($log['response_message'], 0, 50)); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <small><?php echo date('M j, Y', strtotime($log['created_at'])); ?></small><br>
                                            <small class="text-muted"><?php echo date('H:i', strtotime($log['created_at'])); ?></small>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
