<?php
/**
 * View Sale
 * LandSales Pro - Sale details and payment history
 */
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'];
$saleId = intval($_GET['id'] ?? 0);

if (!$saleId) {
    header('Location: index.php');
    exit;
}

// Get sale details
$sale = db_fetch_one("SELECT s.*, b.full_name as buyer_name, b.phone as buyer_phone, b.email as buyer_email,
    b.address as buyer_address, b.id_type, b.id_number,
    p.plot_number, p.size, p.size_unit, p.price as plot_price, p.block,
    pr.name as project_name, pr.location as project_location,
    a.full_name as agent_name, a.phone as agent_phone
    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 agents a ON s.agent_id = a.id
    WHERE s.id = ? AND s.user_id = ?", 'ii', [$saleId, $userId]);

if (!$sale) {
    setFlashMessage('error', 'Sale not found');
    header('Location: index.php');
    exit;
}

// Get payments
$payments = db_fetch_all("SELECT * FROM payments WHERE sale_id = ? ORDER BY payment_date DESC", 'i', [$saleId]);
$totalPaid = array_reduce($payments, function($sum, $p) {
    return $p['status'] === 'confirmed' ? $sum + $p['amount'] : $sum;
}, 0);
$balance = $sale['total_price'] - $totalPaid;
$paidPercent = $sale['total_price'] > 0 ? ($totalPaid / $sale['total_price']) * 100 : 0;

// Get payment schedule
$schedule = db_fetch_all("SELECT * FROM payment_schedule WHERE sale_id = ? ORDER BY installment_number", 'i', [$saleId]);

// Get LandSecure sync status
$landSecureSettings = getLandSecureSettings($userId);
$syncStatus = getSyncStatus($saleId);

// Handle status change
if (isset($_POST['action'])) {
    if ($_POST['action'] === 'cancel' && $sale['status'] === 'active') {
        db_execute("UPDATE sales SET status = 'cancelled' WHERE id = ? AND user_id = ?", 'ii', [$saleId, $userId]);
        db_execute("UPDATE plots SET status = 'available' WHERE id = ?", 'i', [$sale['plot_id']]);
        logActivity('sale_cancelled', "Cancelled sale {$sale['sale_number']}");
        setFlashMessage('success', 'Sale cancelled. Plot is now available.');
        header('Location: view.php?id=' . $saleId);
        exit;
    }
    if ($_POST['action'] === 'complete' && $balance <= 0) {
        db_execute("UPDATE sales SET status = 'completed' WHERE id = ? AND user_id = ?", 'ii', [$saleId, $userId]);
        logActivity('sale_completed', "Marked sale {$sale['sale_number']} as completed");
        setFlashMessage('success', 'Sale marked as completed.');
        header('Location: view.php?id=' . $saleId);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sale <?php echo $sale['sale_number']; ?> - <?php echo APP_NAME; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="<?php echo SITE_URL; ?>/assets/font-awesome/css/all.min.css">
</head>
<body>
    <?php include '../includes/sidebar.php'; ?>

    <div class="main-content">
        <div class="top-header">
            <button class="menu-toggle" onclick="toggleSidebar()">
                <i class="fas fa-bars"></i>
            </button>
            <h1 class="page-title">Sale <?php echo $sale['sale_number']; ?></h1>
            <div class="header-actions">
                <a href="index.php" class="btn btn-outline">
                    <i class="fas fa-arrow-left"></i> Back
                </a>
                <?php if ($balance > 0 && $sale['status'] === 'active'): ?>
                <a href="../payments/create.php?sale_id=<?php echo $saleId; ?>" class="btn btn-primary">
                    <i class="fas fa-money-bill-wave"></i> Record Payment
                </a>
                <?php endif; ?>
            </div>
        </div>

        <div class="content-wrapper">
            <?php $flash = getFlashMessage(); if ($flash): ?>
            <div class="alert alert-<?php echo $flash['type'] === 'success' ? 'success' : 'danger'; ?>">
                <i class="fas fa-<?php echo $flash['type'] === 'success' ? 'check-circle' : 'exclamation-circle'; ?>"></i>
                <?php echo htmlspecialchars($flash['message']); ?>
            </div>
            <?php endif; ?>

            <div class="detail-grid">
                <!-- Payment Summary Card -->
                <div class="summary-card">
                    <div class="summary-header <?php echo $sale['status']; ?>">
                        <span class="status-badge"><?php echo ucfirst($sale['status']); ?></span>
                        <div class="summary-title">Payment Progress</div>
                    </div>
                    <div class="summary-body">
                        <div class="progress-circle" data-percent="<?php echo round($paidPercent); ?>">
                            <svg viewBox="0 0 36 36">
                                <path class="circle-bg" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
                                <path class="circle" stroke-dasharray="<?php echo $paidPercent; ?>, 100" d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"/>
                            </svg>
                            <div class="percent"><?php echo round($paidPercent); ?>%</div>
                        </div>

                        <div class="summary-amounts">
                            <div class="amount-row">
                                <span class="amount-label">Total Price</span>
                                <span class="amount-value">TZS <?php echo number_format($sale['total_price']); ?></span>
                            </div>
                            <div class="amount-row success">
                                <span class="amount-label">Total Paid</span>
                                <span class="amount-value">TZS <?php echo number_format($totalPaid); ?></span>
                            </div>
                            <div class="amount-row <?php echo $balance > 0 ? 'warning' : 'success'; ?>">
                                <span class="amount-label">Balance</span>
                                <span class="amount-value">TZS <?php echo number_format($balance); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Sale Details -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-handshake"></i> Sale Details</h3>
                    </div>
                    <div class="card-body">
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="info-label">Sale Number</span>
                                <span class="info-value"><?php echo $sale['sale_number']; ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Sale Date</span>
                                <span class="info-value"><?php echo date('F j, Y', strtotime($sale['sale_date'])); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Payment Type</span>
                                <span class="info-value"><?php echo ucfirst($sale['payment_type']); ?>
                                    <?php if ($sale['payment_type'] === 'installment'): ?>
                                    (<?php echo $sale['installment_months']; ?> months)
                                    <?php endif; ?>
                                </span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Deposit</span>
                                <span class="info-value">TZS <?php echo number_format($sale['deposit_amount']); ?></span>
                            </div>
                        </div>
                        <?php if ($sale['notes']): ?>
                        <div class="notes-section">
                            <span class="info-label">Notes</span>
                            <p><?php echo nl2br(htmlspecialchars($sale['notes'])); ?></p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Plot Details -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-map-marker-alt"></i> Plot Information</h3>
                    </div>
                    <div class="card-body">
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="info-label">Plot Number</span>
                                <span class="info-value plot-number"><?php echo htmlspecialchars($sale['plot_number']); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Project</span>
                                <span class="info-value"><?php echo htmlspecialchars($sale['project_name']); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Location</span>
                                <span class="info-value"><?php echo htmlspecialchars($sale['project_location'] ?: 'N/A'); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Size</span>
                                <span class="info-value"><?php echo number_format($sale['size']); ?> <?php echo $sale['size_unit']; ?></span>
                            </div>
                            <?php if ($sale['block']): ?>
                            <div class="info-item">
                                <span class="info-label">Block</span>
                                <span class="info-value"><?php echo htmlspecialchars($sale['block']); ?></span>
                            </div>
                            <?php endif; ?>
                            <div class="info-item">
                                <span class="info-label">Plot Price</span>
                                <span class="info-value">TZS <?php echo number_format($sale['plot_price']); ?></span>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Buyer Details -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-user"></i> Buyer Information</h3>
                        <a href="../buyers/view.php?id=<?php echo $sale['buyer_id']; ?>" class="btn btn-outline btn-sm">View Profile</a>
                    </div>
                    <div class="card-body">
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="info-label">Full Name</span>
                                <span class="info-value"><?php echo htmlspecialchars($sale['buyer_name']); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Phone</span>
                                <span class="info-value"><a href="tel:<?php echo $sale['buyer_phone']; ?>"><?php echo $sale['buyer_phone']; ?></a></span>
                            </div>
                            <?php if ($sale['buyer_email']): ?>
                            <div class="info-item">
                                <span class="info-label">Email</span>
                                <span class="info-value"><a href="mailto:<?php echo $sale['buyer_email']; ?>"><?php echo $sale['buyer_email']; ?></a></span>
                            </div>
                            <?php endif; ?>
                            <?php if ($sale['id_type'] && $sale['id_number']): ?>
                            <div class="info-item">
                                <span class="info-label"><?php echo strtoupper($sale['id_type']); ?></span>
                                <span class="info-value"><?php echo htmlspecialchars($sale['id_number']); ?></span>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <?php if ($sale['agent_id']): ?>
                <!-- Agent Details -->
                <div class="card">
                    <div class="card-header">
                        <h3><i class="fas fa-user-tie"></i> Sales Agent</h3>
                    </div>
                    <div class="card-body">
                        <div class="info-grid">
                            <div class="info-item">
                                <span class="info-label">Agent Name</span>
                                <span class="info-value"><?php echo htmlspecialchars($sale['agent_name']); ?></span>
                            </div>
                            <div class="info-item">
                                <span class="info-label">Phone</span>
                                <span class="info-value"><a href="tel:<?php echo $sale['agent_phone']; ?>"><?php echo $sale['agent_phone']; ?></a></span>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- LandSecure Sync -->
                <?php if ($landSecureSettings['enabled'] && $sale['buyer_email']): ?>
                <div class="card landsecure-card">
                    <div class="card-header">
                        <h3><i class="fas fa-map-marked-alt"></i> LandSecure Sync</h3>
                    </div>
                    <div class="card-body">
                        <?php if ($syncStatus): ?>
                        <div class="sync-info">
                            <span class="info-label">Last Sync</span>
                            <span class="sync-status-badge <?php echo $syncStatus['status']; ?>">
                                <?php echo ucfirst(str_replace('_', ' ', $syncStatus['status'])); ?>
                            </span>
                            <small class="text-muted"><?php echo date('M j, Y H:i', strtotime($syncStatus['synced_at'])); ?></small>
                        </div>
                        <?php if ($syncStatus['response_message']): ?>
                        <p class="sync-message"><?php echo htmlspecialchars($syncStatus['response_message']); ?></p>
                        <?php endif; ?>
                        <?php else: ?>
                        <p class="text-muted">Not synced to LandSecure yet.</p>
                        <?php endif; ?>

                        <button type="button" class="btn btn-landsecure" onclick="syncToLandSecure()">
                            <i class="fas fa-sync-alt"></i>
                            <?php echo $syncStatus ? 'Sync Again' : 'Sync to LandSecure'; ?>
                        </button>
                    </div>
                </div>
                <?php elseif (!$sale['buyer_email']): ?>
                <div class="card">
                    <div class="card-body text-center text-muted">
                        <i class="fas fa-exclamation-circle"></i> Buyer has no email - cannot sync to LandSecure
                    </div>
                </div>
                <?php endif; ?>
            </div>

            <!-- Payment History -->
            <div class="card mt-4">
                <div class="card-header">
                    <h3><i class="fas fa-history"></i> Payment History</h3>
                    <?php if ($balance > 0 && $sale['status'] === 'active'): ?>
                    <a href="../payments/create.php?sale_id=<?php echo $saleId; ?>" class="btn btn-primary btn-sm">
                        <i class="fas fa-plus"></i> Add Payment
                    </a>
                    <?php endif; ?>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>Payment #</th>
                                <th>Date</th>
                                <th>Amount</th>
                                <th>Method</th>
                                <th>Status</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($payments)): ?>
                            <tr>
                                <td colspan="6" class="empty-row">
                                    <div class="empty-state">
                                        <i class="fas fa-money-bill-wave"></i>
                                        <p>No payments recorded yet</p>
                                    </div>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($payments as $payment): ?>
                            <tr>
                                <td><span class="payment-number"><?php echo $payment['payment_number']; ?></span></td>
                                <td><?php echo date('M j, Y', strtotime($payment['payment_date'])); ?></td>
                                <td class="text-success">TZS <?php echo number_format($payment['amount']); ?></td>
                                <td><?php echo ucfirst($payment['payment_method']); ?></td>
                                <td>
                                    <span class="status-badge status-<?php echo $payment['status']; ?>">
                                        <?php echo ucfirst($payment['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <a href="../payments/receipt.php?id=<?php echo $payment['id']; ?>" class="btn-icon" title="Receipt">
                                        <i class="fas fa-receipt"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

            <?php if (!empty($schedule)): ?>
            <!-- Payment Schedule -->
            <div class="card mt-4">
                <div class="card-header">
                    <h3><i class="fas fa-calendar-alt"></i> Payment Schedule</h3>
                </div>
                <div class="table-responsive">
                    <table class="data-table">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Due Date</th>
                                <th>Amount</th>
                                <th>Status</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($schedule as $item): ?>
                            <tr class="<?php echo $item['status'] === 'overdue' || (strtotime($item['due_date']) < time() && $item['status'] === 'pending') ? 'row-warning' : ''; ?>">
                                <td><?php echo $item['installment_number']; ?></td>
                                <td><?php echo date('M j, Y', strtotime($item['due_date'])); ?></td>
                                <td>TZS <?php echo number_format($item['amount']); ?></td>
                                <td>
                                    <?php
                                    $scheduleStatus = $item['status'];
                                    if ($scheduleStatus === 'pending' && strtotime($item['due_date']) < time()) {
                                        $scheduleStatus = 'overdue';
                                    }
                                    ?>
                                    <span class="status-badge status-<?php echo $scheduleStatus; ?>">
                                        <?php echo ucfirst($scheduleStatus); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>

            <!-- Actions -->
            <?php if ($sale['status'] === 'active'): ?>
            <div class="action-panel mt-4">
                <?php if ($balance <= 0): ?>
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="action" value="complete">
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-check-circle"></i> Mark as Completed
                    </button>
                </form>
                <?php endif; ?>
                <form method="POST" style="display: inline;" onsubmit="return confirm('Are you sure you want to cancel this sale? The plot will become available again.');">
                    <input type="hidden" name="action" value="cancel">
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-times-circle"></i> Cancel Sale
                    </button>
                </form>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <style>
        body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; margin: 0; background: #f1f5f9; }
        .header-actions { display: flex; gap: 0.75rem; }
        .btn { padding: 0.625rem 1.25rem; border-radius: 8px; font-weight: 500; text-decoration: none; display: inline-flex; align-items: center; gap: 0.5rem; transition: all 0.2s; border: none; cursor: pointer; font-size: 0.875rem; }
        .btn-sm { padding: 0.5rem 0.75rem; font-size: 0.8rem; }
        .btn-primary { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; }
        .btn-success { background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); color: white; }
        .btn-danger { background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); color: white; }
        .btn-outline { border: 1px solid #e2e8f0; background: white; color: #64748b; }

        .alert { padding: 1rem 1.5rem; border-radius: 10px; margin-bottom: 1.5rem; display: flex; align-items: center; gap: 0.75rem; }
        .alert-success { background: #dcfce7; border: 1px solid #86efac; color: #166534; }
        .alert-danger { background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }

        .detail-grid { display: grid; grid-template-columns: 300px 1fr; gap: 1.5rem; }

        .summary-card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .summary-header { padding: 1rem 1.25rem; color: white; text-align: center; }
        .summary-header.active { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
        .summary-header.completed { background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); }
        .summary-header.cancelled { background: linear-gradient(135deg, #94a3b8 0%, #64748b 100%); }
        .status-badge { font-size: 0.7rem; text-transform: uppercase; letter-spacing: 1px; opacity: 0.9; }
        .summary-title { font-size: 1.1rem; font-weight: 600; margin-top: 0.25rem; }
        .summary-body { padding: 1.5rem; }

        .progress-circle { width: 120px; height: 120px; margin: 0 auto 1.5rem; position: relative; }
        .progress-circle svg { width: 100%; height: 100%; transform: rotate(-90deg); }
        .circle-bg { fill: none; stroke: #e2e8f0; stroke-width: 3; }
        .circle { fill: none; stroke: #667eea; stroke-width: 3; stroke-linecap: round; transition: stroke-dasharray 0.5s ease; }
        .percent { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 1.5rem; font-weight: 700; color: #1e293b; }

        .summary-amounts { border-top: 1px solid #f1f5f9; padding-top: 1rem; }
        .amount-row { display: flex; justify-content: space-between; padding: 0.5rem 0; font-size: 0.9rem; }
        .amount-row.success .amount-value { color: #16a34a; }
        .amount-row.warning .amount-value { color: #d97706; }
        .amount-label { color: #64748b; }
        .amount-value { font-weight: 600; color: #1e293b; }

        .card { background: white; border-radius: 14px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); overflow: hidden; }
        .card-header { padding: 1rem 1.25rem; border-bottom: 1px solid #f1f5f9; background: #f8fafc; display: flex; justify-content: space-between; align-items: center; }
        .card-header h3 { margin: 0; font-size: 0.95rem; font-weight: 600; color: #1e293b; display: flex; align-items: center; gap: 0.5rem; }
        .card-header h3 i { color: #667eea; }
        .card-body { padding: 1.25rem; }

        .info-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; }
        .info-item { }
        .info-label { display: block; font-size: 0.75rem; color: #64748b; margin-bottom: 0.25rem; text-transform: uppercase; letter-spacing: 0.5px; }
        .info-value { font-weight: 500; color: #1e293b; }
        .info-value a { color: #667eea; text-decoration: none; }
        .plot-number { font-weight: 700; color: #667eea; }

        .notes-section { margin-top: 1rem; padding-top: 1rem; border-top: 1px solid #f1f5f9; }
        .notes-section p { margin: 0.5rem 0 0; color: #475569; font-size: 0.9rem; }

        .mt-4 { margin-top: 1.5rem; }

        .table-responsive { overflow-x: auto; }
        .data-table { width: 100%; border-collapse: collapse; }
        .data-table th, .data-table td { padding: 0.875rem 1rem; text-align: left; border-bottom: 1px solid #f1f5f9; }
        .data-table th { background: #f8fafc; font-weight: 600; font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.5px; color: #64748b; }
        .data-table tbody tr:hover { background: #f8fafc; }
        .row-warning { background: #fef3c7 !important; }

        .payment-number { font-family: monospace; font-weight: 600; color: #667eea; }
        .text-success { color: #16a34a; }

        .status-badge { padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.7rem; font-weight: 600; }
        .status-confirmed, .status-paid { background: #dcfce7; color: #16a34a; }
        .status-pending { background: #fef3c7; color: #d97706; }
        .status-overdue { background: #fee2e2; color: #dc2626; }

        .btn-icon { width: 32px; height: 32px; border-radius: 8px; display: flex; align-items: center; justify-content: center; color: #64748b; background: #f1f5f9; text-decoration: none; transition: all 0.2s; }
        .btn-icon:hover { background: #667eea; color: white; }

        .empty-row td { padding: 2rem; }
        .empty-state { text-align: center; color: #94a3b8; }
        .empty-state i { font-size: 1.5rem; margin-bottom: 0.5rem; }

        .action-panel { display: flex; gap: 1rem; justify-content: flex-end; }

        @media (max-width: 992px) {
            .detail-grid { grid-template-columns: 1fr; }
            .summary-card { order: -1; }
        }

        @media (max-width: 576px) {
            .info-grid { grid-template-columns: 1fr; }
            .action-panel { flex-direction: column; }
            .action-panel .btn { width: 100%; justify-content: center; }
        }

        /* LandSecure Sync Styles */
        .landsecure-card { border: 2px solid #e0e7ff; }
        .landsecure-card .card-header { background: linear-gradient(135deg, #667eea20, #764ba220); }
        .landsecure-card .card-header h3 i { color: #667eea; }

        .sync-info { margin-bottom: 1rem; }
        .sync-status-badge { display: inline-block; padding: 0.25rem 0.75rem; border-radius: 20px; font-size: 0.75rem; font-weight: 600; margin: 0 0.5rem; }
        .sync-status-badge.success { background: #dcfce7; color: #16a34a; }
        .sync-status-badge.pending { background: #fef3c7; color: #d97706; }
        .sync-status-badge.failed { background: #fee2e2; color: #dc2626; }
        .sync-status-badge.no_account { background: #e0e7ff; color: #4338ca; }

        .sync-message { font-size: 0.85rem; color: #64748b; margin: 0.5rem 0; }

        .btn-landsecure { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; width: 100%; justify-content: center; }
        .btn-landsecure:hover { opacity: 0.9; }
    </style>

    <script>
        function syncToLandSecure() {
            const btn = document.querySelector('.btn-landsecure');
            const originalText = btn.innerHTML;
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Syncing...';
            btn.disabled = true;

            fetch('<?php echo SITE_URL; ?>/ajax/sync-landsecure.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    sale_id: <?php echo $saleId; ?>,
                    action: 'sync'
                })
            })
            .then(response => response.json())
            .then(data => {
                btn.innerHTML = originalText;
                btn.disabled = false;

                if (data.success) {
                    alert('Success: ' + data.message);
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                btn.innerHTML = originalText;
                btn.disabled = false;
                alert('Connection error. Please try again.');
            });
        }
    </script>
</body>
</html>
