<!-- wp:html -->
<div dir="rtl" style="font-family: Verdana, Geneva, sans-serif; max-width: 1200px; margin: 20px auto; padding: 20px;">
    
    <!-- כותרת וניווט -->
    <div style="background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); color: white; padding: 25px; border-radius: 12px; margin-bottom: 25px; position: relative; overflow: hidden;">
        <div style="position: absolute; top: -50%; right: -10%; width: 200px; height: 200px; background: rgba(255,255,255,0.1); border-radius: 50%; z-index: 1;"></div>
        
        <div style="display: flex; justify-content: space-between; align-items: center; position: relative; z-index: 2; flex-wrap: wrap;">
            <div>
                <h1 style="margin: 0 0 10px 0; font-size: 28px;">🏠 פאנל ניהול נכסים - נָדְלָנִי</h1>
                <div id="brokerInfo">
                    <h3 id="brokerName" style="margin: 0; color: rgba(255,255,255,0.9);">טוען...</h3>
                    <p style="margin: 5px 0; font-size: 14px; opacity: 0.8;">מתווך נדל"ן | מערכת פרסום אוטומטית</p>
                </div>
            </div>
            
            <div style="display: flex; gap: 15px;">
                <div style="text-align: center; background: rgba(255,255,255,0.2); padding: 15px 20px; border-radius: 10px;">
                    <div style="font-size: 24px; font-weight: bold;" id="propertiesCount">0</div>
                    <div style="font-size: 12px; opacity: 0.9;">נכסים פעילים</div>
                </div>
                
                <div style="text-align: center; background: rgba(255,215,0,0.3); padding: 15px 20px; border-radius: 10px; border: 2px solid rgba(255,215,0,0.5);">
                    <div style="font-size: 24px; font-weight: bold; color: #ffd700;" id="nadelaniCredits">0</div>
                    <div style="font-size: 12px; opacity: 0.9;">⭐ ניקוד נדלני</div>
                </div>
            </div>
            
            <div style="text-align: left;">
                <button onclick="logout()" style="background: rgba(255,255,255,0.2); border: 1px solid rgba(255,255,255,0.3); color: white; padding: 8px 15px; border-radius: 6px; cursor: pointer; font-size: 14px;">
                    🚪 יציאה
                </button>
            </div>
        </div>
    </div>

    <!-- כלי בקרה -->
    <div style="background: white; border-radius: 12px; padding: 20px; margin-bottom: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
        
        <!-- כפתורי פעולה -->
        <div style="display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap;">
            <button onclick="refreshData()" id="refreshBtn" style="background: #17a2b8; color: white; border: none; padding: 10px 15px; border-radius: 6px; cursor: pointer; font-size: 14px; display: flex; align-items: center; gap: 5px;">
                <span id="refreshIcon">🔄</span> רענן נתונים
            </button>
            
            <button onclick="toggleAllProperties()" id="toggleAllBtn" style="background: #28a745; color: white; border: none; padding: 10px 15px; border-radius: 6px; cursor: pointer; font-size: 14px;">
                ⚡ הפעל הכל
            </button>
            
            <button onclick="showBulkActions()" style="background: #ffc107; color: #333; border: none; padding: 10px 15px; border-radius: 6px; cursor: pointer; font-size: 14px;">
                🤖 פרסום אוטומטי
            </button>
            
            <button onclick="showAutoPublishSettings()" style="background: #6f42c1; color: white; border: none; padding: 10px 15px; border-radius: 6px; cursor: pointer; font-size: 14px;">
                ⚙️ הגדרות אוטומציה
            </button>
        </div>

        <!-- חיפוש וסינון -->
        <div style="display: grid; grid-template-columns: 1fr auto auto auto; gap: 15px; align-items: center;">
            <input 
                type="text" 
                id="searchInput" 
                placeholder="🔍 חיפוש נכסים לפי שם, מיקום או תיאור..."
                style="padding: 12px 15px; border: 2px solid #e1e5e9; border-radius: 8px; font-size: 14px; width: 100%;"
                oninput="searchProperties()"
            >
            
            <select id="statusFilter" onchange="filterProperties()" style="padding: 12px; border: 2px solid #e1e5e9; border-radius: 8px; font-size: 14px;">
                <option value="all">כל הסטטוסים</option>
                <option value="on">פעיל בלבד</option>
                <option value="off">לא פעיל בלבד</option>
            </select>
            
            <select id="categoryFilter" onchange="filterProperties()" style="padding: 12px; border: 2px solid #e1e5e9; border-radius: 8px; font-size: 14px;">
                <option value="all">כל הקטגוריות</option>
                <option value="1">דירה</option>
                <option value="15">טריפלקס</option>
                <option value="16">יחידת דיור</option>
            </select>
            
            <button onclick="toggleView()" id="viewToggle" style="background: #6c757d; color: white; border: none; padding: 12px 15px; border-radius: 6px; cursor: pointer; font-size: 14px;">
                📋 טבלה
            </button>
        </div>
    </div>

    <!-- סטטוס טעינה -->
    <div id="loadingStatus" style="text-align: center; padding: 40px; background: white; border-radius: 12px; margin-bottom: 20px; display: none;">
        <div style="display: inline-block; width: 30px; height: 30px; border: 4px solid #007bff; border-radius: 50%; border-top-color: transparent; animation: spin 1s linear infinite;"></div>
        <p style="margin-top: 15px; color: #666;">טוען נתונים...</p>
    </div>

    <!-- הודעות סטטוס -->
    <div id="statusMessage" style="display: none; padding: 15px; margin-bottom: 20px; border-radius: 8px; text-align: center; font-weight: bold;"></div>

    <!-- תצוגת כרטיסים -->
    <div id="cardsView">
        <div id="propertiesList" style="display: grid; grid-template-columns: repeat(auto-fill, minmax(350px, 1fr)); gap: 20px;"></div>
    </div>

    <!-- תצוגת טבלה -->
    <div id="tableView" style="display: none; background: white; border-radius: 12px; padding: 20px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); overflow-x: auto;">
        <table style="width: 100%; border-collapse: collapse;">
            <thead>
                <tr style="background: #f8f9fa;">
                    <th style="padding: 15px 10px; text-align: right; border-bottom: 2px solid #dee2e6; font-weight: bold;">סטטוס</th>
                    <th style="padding: 15px 10px; text-align: right; border-bottom: 2px solid #dee2e6; font-weight: bold;">שם הנכס</th>
                    <th style="padding: 15px 10px; text-align: right; border-bottom: 2px solid #dee2e6; font-weight: bold;">מחיר</th>
                    <th style="padding: 15px 10px; text-align: right; border-bottom: 2px solid #dee2e6; font-weight: bold;">חדרים</th>
                    <th style="padding: 15px 10px; text-align: right; border-bottom: 2px solid #dee2e6; font-weight: bold;">מיקום</th>
                    <th style="padding: 15px 10px; text-align: center; border-bottom: 2px solid #dee2e6; font-weight: bold;">פעולות</th>
                </tr>
            </thead>
            <tbody id="tableBody"></tbody>
        </table>
    </div>

    <!-- חלון מודאלי לפרסום -->
    <div id="publishModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.7); z-index: 1000; justify-content: center; align-items: center;">
        <div style="background: white; padding: 30px; border-radius: 12px; width: 90%; max-width: 500px; direction: rtl; box-shadow: 0 10px 30px rgba(0,0,0,0.3);">
            <h3 style="margin-top: 0; color: #333; text-align: center;">📢 פרסום נכס</h3>
            <div id="publishContent"></div>
            <div style="display: flex; justify-content: center; gap: 15px; margin-top: 25px;">
                <button onclick="closeModal()" style="background: #6c757d; color: white; border: none; padding: 12px 25px; border-radius: 6px; cursor: pointer; font-size: 14px;">
                    ❌ ביטול
                </button>
                <button onclick="confirmPublish()" style="background: #28a745; color: white; border: none; padding: 12px 25px; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: bold;">
                    🚀 פרסם עכשיו
                </button>
            </div>
        </div>
    </div>
</div>

<style>
@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.property-card {
    background: white;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    transition: transform 0.3s, box-shadow 0.3s;
    border-right: 4px solid #007bff;
    position: relative;
}

.property-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}

.property-card.inactive {
    border-right-color: #dc3545;
    opacity: 0.8;
    background: #f8f9fa;
}

.property-image {
    width: 100%;
    height: 180px;
    object-fit: cover;
    border-radius: 8px;
    margin-bottom: 15px;
}

.property-title {
    font-size: 18px;
    font-weight: bold;
    color: #333;
    margin-bottom: 10px;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.property-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin: 15px 0;
    font-size: 14px;
    color: #666;
}

.property-meta span {
    background: #f8f9fa;
    padding: 4px 8px;
    border-radius: 4px;
    white-space: nowrap;
}

.property-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
    margin-top: 15px;
}

.btn-action {
    padding: 8px 12px;
    font-size: 12px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-weight: bold;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 4px;
    transition: all 0.2s;
    flex: 1;
    min-width: 80px;
    justify-content: center;
}

.btn-action:hover {
    transform: translateY(-1px);
}

.status-success { background-color: #d4edda; color: #155724; border: 1px solid #c3e6cb; }
.status-error { background-color: #f8d7da; color: #721c24; border: 1px solid #f5c6cb; }
.status-warning { background-color: #fff3cd; color: #856404; border: 1px solid #ffeaa7; }

@media (max-width: 768px) {
    .property-meta {
        flex-direction: column;
        gap: 5px;
    }
    
    .property-actions {
        flex-direction: column;
    }
    
    .btn-action {
        min-width: auto;
    }
}
</style>

<script>
// הגדרות גלובליות
const WEBHOOK_URL = 'https://hook.eu2.make.com/96rcexlj83qn94w3kavbl45alhozx2rx';
let currentBroker = null;
let allProperties = [];
let filteredProperties = [];
let currentView = 'cards';

// טעינה ראשונית
document.addEventListener('DOMContentLoaded', function() {
    initializeDashboard();
});

// אתחול הדשבורד
async function initializeDashboard() {
    // קבלת מזהה מתווך מ-URL או localStorage
    const urlParams = new URLSearchParams(window.location.search);
    const brokerIdFromUrl = urlParams.get('id');
    const savedBrokerId = localStorage.getItem('broker_id');
    
    const brokerId = brokerIdFromUrl || savedBrokerId;
    
    if (!brokerId) {
        showStatus('לא נמצא קוד מתווך. מפנה לעמוד הכניסה...', 'error');
        setTimeout(() => window.location.href = '/broker-login/', 2000);
        return;
    }
    
    await loadBrokerData(brokerId);
}

// טעינת נתוני המתווך
async function loadBrokerData(brokerId) {
    setLoading(true);
    
    try {
        const response = await fetch(WEBHOOK_URL, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                action: 'get_broker_properties',
                broker_id: brokerId
            })
        });

        const data = await response.json();

        if (data.success) {
            currentBroker = data.broker;
            allProperties = data.properties || [];
            filteredProperties = [...allProperties];

            // עדכון ממשק המשתמש
            updateBrokerInfo();
            displayProperties();
            showStatus('נתונים נטענו בהצלחה', 'success');
        } else {
            showStatus(data.message || 'שגיאה בטעינת הנתונים', 'error');
        }
    } catch (error) {
        console.error('Error:', error);
        showStatus('שגיאה בחיבור למערכת', 'error');
    } finally {
        setLoading(false);
    }
}

// עדכון פרטי המתווך
function updateBrokerInfo() {
    if (!currentBroker) return;
    
    document.getElementById('brokerName').textContent = 
        `${currentBroker.first_name} ${currentBroker.last_name}`;
    
    const activeCount = allProperties.filter(p => p.status === 'on').length;
    document.getElementById('propertiesCount').textContent = activeCount;
    
    // עדכון ניקוד נדלני
    document.getElementById('nadelaniCredits').textContent = currentBroker.credits || '0';
}

// הצגת הנכסים
function displayProperties() {
    const cardsList = document.getElementById('propertiesList');
    const tableBody = document.getElementById('tableBody');
    
    if (filteredProperties.length === 0) {
        cardsList.innerHTML = `
            <div style="grid-column: 1 / -1; text-align: center; padding: 60px; background: white; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.1);">
                <div style="font-size: 48px; margin-bottom: 15px; opacity: 0.3;">🏠</div>
                <h3 style="color: #333; margin-bottom: 10px;">אין נכסים להצגה</h3>
                <p style="color: #666;">נכסים יופיעו כאן לאחר שיתווספו למערכת</p>
            </div>
        `;
        tableBody.innerHTML = '';
        return;
    }

    // תצוגת כרטיסים
    let cardsHTML = '';
    let tableHTML = '';

    filteredProperties.forEach(property => {
        const isActive = property.status === 'on';
        const statusText = isActive ? 'פעיל' : 'לא פעיל';
        const statusColor = isActive ? '#28a745' : '#dc3545';
        const toggleText = isActive ? 'השבת' : 'הפעל';
        const toggleIcon = isActive ? '⏸️' : '▶️';
        
        // בניית URL לתמונה
        const imageUrl = property.images ? 
            `https://nadelani.com/${property.images.split(',')[0].replace(/["\[\]]/g, '')}` : 
            'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 150" fill="%23f0f0f0"><rect width="200" height="150" fill="%23f8f9fa"/><text x="100" y="80" text-anchor="middle" fill="%23999" font-size="14">🏠 אין תמונה</text></svg>';

        // כרטיס
        cardsHTML += `
            <div class="property-card ${isActive ? '' : 'inactive'}">
                <img src="${imageUrl}" alt="${property.name}" class="property-image" onerror="this.src='data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 200 150\" fill=\"%23f0f0f0\"><rect width=\"200\" height=\"150\" fill=\"%23f8f9fa\"/><text x=\"100\" y=\"80\" text-anchor=\"middle\" fill=\"%23999\" font-size=\"14\">🏠 אין תמונה</text></svg>'">
                
                <div class="property-title">${property.name}</div>
                
                <div class="property-meta">
                    <span style="color: ${statusColor}; font-weight: bold;">● ${statusText}</span>
                    <span>💰 ${formatPrice(property.price)} ${getCurrency(property.currency_id)}</span>
                    <span>🏠 ${property.number_bedroom} חדרים</span>
                    <span>📍 ${property.location}</span>
                </div>
                
                <div class="property-actions">
                    <button onclick="toggleStatus(${property.id})" class="btn-action" style="background: ${isActive ? '#dc3545' : '#28a745'}; color: white;">
                        ${toggleIcon} ${toggleText}
                    </button>
                    <button onclick="publishProperty(${property.id})" class="btn-action" style="background: #007bff; color: white;">
                        📤 פרסם
                    </button>
                    <a href="https://nadelani.com/properties/${property.id}" target="_blank" class="btn-action" style="background: #17a2b8; color: white;">
                        👁️ צפה
                    </a>
                    <a href="https://nadelani.com/account/properties/${property.id}/edit" target="_blank" class="btn-action" style="background: #ffc107; color: #333;">
                        ✏️ ערוך
                    </a>
                </div>
            </div>
        `;

        // שורת טבלה
        tableHTML += `